1 | /* |
2 | * Copyright 2004-2014 H2 Group. Multiple-Licensed under the MPL 2.0, |
3 | * and the EPL 1.0 (http://h2database.com/html/license.html). |
4 | * Initial Developer: H2 Group |
5 | */ |
6 | package org.h2.engine; |
7 | |
8 | import java.util.HashMap; |
9 | |
10 | import org.h2.api.ErrorCode; |
11 | import org.h2.message.DbException; |
12 | import org.h2.util.Utils; |
13 | |
14 | /** |
15 | * The base class for settings. |
16 | */ |
17 | public class SettingsBase { |
18 | |
19 | private final HashMap<String, String> settings; |
20 | |
21 | protected SettingsBase(HashMap<String, String> s) { |
22 | this.settings = s; |
23 | } |
24 | |
25 | /** |
26 | * Get the setting for the given key. |
27 | * |
28 | * @param key the key |
29 | * @param defaultValue the default value |
30 | * @return the setting |
31 | */ |
32 | protected boolean get(String key, boolean defaultValue) { |
33 | String s = get(key, "" + defaultValue); |
34 | try { |
35 | return Boolean.parseBoolean(s); |
36 | } catch (NumberFormatException e) { |
37 | throw DbException.get(ErrorCode.DATA_CONVERSION_ERROR_1, |
38 | e, "key:" + key + " value:" + s); |
39 | } |
40 | } |
41 | |
42 | /** |
43 | * Get the setting for the given key. |
44 | * |
45 | * @param key the key |
46 | * @param defaultValue the default value |
47 | * @return the setting |
48 | */ |
49 | protected int get(String key, int defaultValue) { |
50 | String s = get(key, "" + defaultValue); |
51 | try { |
52 | return Integer.decode(s); |
53 | } catch (NumberFormatException e) { |
54 | throw DbException.get(ErrorCode.DATA_CONVERSION_ERROR_1, |
55 | e, "key:" + key + " value:" + s); |
56 | } |
57 | } |
58 | |
59 | /** |
60 | * Get the setting for the given key. |
61 | * |
62 | * @param key the key |
63 | * @param defaultValue the default value |
64 | * @return the setting |
65 | */ |
66 | protected String get(String key, String defaultValue) { |
67 | StringBuilder buff = new StringBuilder("h2."); |
68 | boolean nextUpper = false; |
69 | for (char c : key.toCharArray()) { |
70 | if (c == '_') { |
71 | nextUpper = true; |
72 | } else { |
73 | // Character.toUpperCase / toLowerCase ignores the locale |
74 | buff.append(nextUpper ? Character.toUpperCase(c) : Character.toLowerCase(c)); |
75 | nextUpper = false; |
76 | } |
77 | } |
78 | String sysProperty = buff.toString(); |
79 | String v = settings.get(key); |
80 | if (v == null) { |
81 | v = Utils.getProperty(sysProperty, defaultValue); |
82 | settings.put(key, v); |
83 | } |
84 | return v; |
85 | } |
86 | |
87 | /** |
88 | * Check if the settings contains the given key. |
89 | * |
90 | * @param k the key |
91 | * @return true if they do |
92 | */ |
93 | protected boolean containsKey(String k) { |
94 | return settings.containsKey(k); |
95 | } |
96 | |
97 | /** |
98 | * Get all settings. |
99 | * |
100 | * @return the settings |
101 | */ |
102 | public HashMap<String, String> getSettings() { |
103 | return settings; |
104 | } |
105 | |
106 | } |