001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.spi.preferences;
003
004import java.util.Arrays;
005import java.util.Collection;
006import java.util.Collections;
007import java.util.HashSet;
008import java.util.LinkedList;
009import java.util.List;
010import java.util.Map;
011import java.util.Map.Entry;
012import java.util.Set;
013import java.util.TreeMap;
014import java.util.stream.Collectors;
015
016import org.openstreetmap.josm.io.DefaultProxySelector;
017import org.openstreetmap.josm.io.auth.CredentialsAgent;
018import org.openstreetmap.josm.io.auth.CredentialsManager;
019import org.openstreetmap.josm.tools.Logging;
020import org.openstreetmap.josm.tools.Utils;
021
022/**
023 * Abstract implementation of the {@link IPreferences} interface.
024 * @since 12847
025 */
026public abstract class AbstractPreferences implements IPreferences {
027    /** The preference key for sensitive keys */
028    private static final String KEY_SENSITIVE_KEYS = "sensitive.keys";
029
030    /** A set of sensitive keys that should not be seen/distributed outside of specific callers (like a {@link CredentialsAgent}) */
031    private static final Set<String> SENSITIVE_KEYS = new HashSet<>();
032
033    @Override
034    public synchronized String get(final String key, final String def) {
035        return getSetting(key, new StringSetting(def), StringSetting.class).getValue();
036    }
037
038    @Override
039    public boolean put(final String key, String value) {
040        return putSetting(key, Utils.isEmpty(value) ? null : new StringSetting(value));
041    }
042
043    @Override
044    public boolean getBoolean(final String key, final boolean def) {
045        return Boolean.parseBoolean(get(key, Boolean.toString(def)));
046    }
047
048    @Override
049    public boolean putBoolean(final String key, final boolean value) {
050        return put(key, Boolean.toString(value));
051    }
052
053    @Override
054    public synchronized int getInt(String key, int def) {
055        String v = get(key, Integer.toString(def));
056        if (v.isEmpty())
057            return def;
058
059        try {
060            return Integer.parseInt(v);
061        } catch (NumberFormatException e) {
062            // fall out
063            Logging.trace(e);
064        }
065        return def;
066    }
067
068    @Override
069    public boolean putInt(String key, int value) {
070        return put(key, Integer.toString(value));
071    }
072
073    @Override
074    public long getLong(String key, long def) {
075        String v = get(key, Long.toString(def));
076        if (null == v)
077            return def;
078
079        try {
080            return Long.parseLong(v);
081        } catch (NumberFormatException e) {
082            // fall out
083            Logging.trace(e);
084        }
085        return def;
086    }
087
088    @Override
089    public boolean putLong(final String key, final long value) {
090        return put(key, Long.toString(value));
091    }
092
093    @Override
094    public synchronized double getDouble(String key, double def) {
095        String v = get(key, Double.toString(def));
096        if (null == v)
097            return def;
098
099        try {
100            return Double.parseDouble(v);
101        } catch (NumberFormatException e) {
102            // fall out
103            Logging.trace(e);
104        }
105        return def;
106    }
107
108    @Override
109    public boolean putDouble(final String key, final double value) {
110        return put(key, Double.toString(value));
111    }
112
113    @Override
114    public List<String> getList(String key, List<String> def) {
115        return getSetting(key, new ListSetting(def), ListSetting.class).getValue();
116    }
117
118    @Override
119    public boolean putList(String key, List<String> value) {
120        return putSetting(key, value == null ? null : new ListSetting(value));
121    }
122
123    @Override
124    public List<List<String>> getListOfLists(String key, List<List<String>> def) {
125        return getSetting(key, new ListListSetting(def), ListListSetting.class).getValue();
126    }
127
128    @Override
129    public boolean putListOfLists(String key, List<List<String>> value) {
130        return putSetting(key, value == null ? null : new ListListSetting(value));
131    }
132
133    @Override
134    public List<Map<String, String>> getListOfMaps(String key, List<Map<String, String>> def) {
135        return getSetting(key, new MapListSetting(def), MapListSetting.class).getValue();
136    }
137
138    @Override
139    public boolean putListOfMaps(String key, List<Map<String, String>> value) {
140        return putSetting(key, value == null ? null : new MapListSetting(value));
141    }
142
143    /**
144     * Gets a map of all settings that are currently stored
145     * @return The settings
146     */
147    public abstract Map<String, Setting<?>> getAllSettings();
148
149    /**
150     * Set a value for a certain setting. The changed setting is saved to the preference file immediately.
151     * Due to caching mechanisms on modern operating systems and hardware, this shouldn't be a performance problem.
152     * @param key the unique identifier for the setting
153     * @param setting the value of the setting. In case it is null, the key-value entry will be removed.
154     * @return {@code true}, if something has changed (i.e. value is different than before)
155     */
156    public abstract boolean putSetting(String key, Setting<?> setting);
157
158    /**
159     * Get settings value for a certain key and provide default a value.
160     * @param <T> the setting type
161     * @param key the identifier for the setting
162     * @param def the default value. For each call of getSetting() with a given key, the default value must be the same.
163     * <code>def</code> must not be null, but the value of <code>def</code> can be null.
164     * @param klass the setting type (same as T)
165     * @return the corresponding value if the property has been set before, {@code def} otherwise
166     */
167    public abstract <T extends Setting<?>> T getSetting(String key, T def, Class<T> klass);
168
169    /**
170     * Gets all normal (string) settings that have a key starting with the prefix
171     * @param prefix The start of the key
172     * @return The key names of the settings
173     */
174    public Map<String, String> getAllPrefix(String prefix) {
175        return getAllSettings().entrySet().stream()
176                .filter(e -> e.getKey().startsWith(prefix) && (e.getValue() instanceof StringSetting))
177                .collect(Collectors.toMap(Entry::getKey, e -> ((StringSetting) e.getValue()).getValue(), (a, b) -> b, TreeMap::new));
178    }
179
180    /**
181     * Gets all list settings that have a key starting with the prefix
182     * @param prefix The start of the key
183     * @return The key names of the list settings
184     */
185    public List<String> getAllPrefixCollectionKeys(String prefix) {
186        return getAllSettings().entrySet().stream()
187                .filter(entry -> entry.getKey().startsWith(prefix) && entry.getValue() instanceof ListSetting)
188                .map(Entry::getKey)
189                .collect(Collectors.toCollection(LinkedList::new));
190    }
191
192    @Override
193    public void addSensitive(CredentialsAgent caller, String key) {
194        if (SENSITIVE_KEYS.isEmpty()) {
195            populateSensitiveKeys();
196        }
197        if (CredentialsManager.getInstance().getCredentialsAgentClass().equals(caller.getClass())) {
198            SENSITIVE_KEYS.add(key);
199            putList("sensitive.keys", SENSITIVE_KEYS.stream().sorted().collect(Collectors.toList()));
200        }
201    }
202
203    @Override
204    public Collection<String> getSensitive() {
205        if (SENSITIVE_KEYS.isEmpty()) {
206            populateSensitiveKeys();
207        }
208        return Collections.unmodifiableSet(SENSITIVE_KEYS);
209    }
210
211    @Override
212    public void removeSensitive(String key) {
213        if (KEY_SENSITIVE_KEYS.equals(key)) {
214            throw new IllegalArgumentException(KEY_SENSITIVE_KEYS + " cannot be removed from the sensitive key list.");
215        }
216        // Reset the key first -- avoid race conditions where a sensitive value might be visible if we start restricting access in the future.
217        put(key, null);
218        SENSITIVE_KEYS.remove(key);
219        putList(KEY_SENSITIVE_KEYS, SENSITIVE_KEYS.stream().sorted().collect(Collectors.toList()));
220    }
221
222    /**
223     * Populate the sensitive key set from preferences
224     */
225    private void populateSensitiveKeys() {
226        SENSITIVE_KEYS.addAll(getList(KEY_SENSITIVE_KEYS, Arrays.asList("sensitive.keys", "osm-server.username", "osm-server.password",
227                DefaultProxySelector.PROXY_USER, DefaultProxySelector.PROXY_PASS,
228                "oauth.access-token.key", "oauth.access-token.secret")));
229    }
230}