source: josm/trunk/src/org/openstreetmap/josm/data/Preferences.java@ 14144

Last change on this file since 14144 was 14144, checked in by Don-vip, 6 years ago

see #15229 - code refactoring - add PlatformHook.getPossiblePreferenceDirs()

  • Property svn:eol-style set to native
File size: 30.8 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.data;
3
4import static org.openstreetmap.josm.tools.I18n.marktr;
5import static org.openstreetmap.josm.tools.I18n.tr;
6import static org.openstreetmap.josm.tools.Utils.getSystemEnv;
7import static org.openstreetmap.josm.tools.Utils.getSystemProperty;
8
9import java.awt.GraphicsEnvironment;
10import java.io.File;
11import java.io.IOException;
12import java.io.PrintWriter;
13import java.io.Reader;
14import java.io.StringWriter;
15import java.nio.charset.StandardCharsets;
16import java.nio.file.InvalidPathException;
17import java.util.ArrayList;
18import java.util.Collection;
19import java.util.Collections;
20import java.util.HashMap;
21import java.util.HashSet;
22import java.util.Iterator;
23import java.util.LinkedList;
24import java.util.List;
25import java.util.Map;
26import java.util.Map.Entry;
27import java.util.Optional;
28import java.util.Set;
29import java.util.SortedMap;
30import java.util.TreeMap;
31import java.util.concurrent.TimeUnit;
32import java.util.function.Predicate;
33import java.util.stream.Stream;
34
35import javax.swing.JOptionPane;
36import javax.xml.stream.XMLStreamException;
37
38import org.openstreetmap.josm.Main;
39import org.openstreetmap.josm.data.preferences.ColorInfo;
40import org.openstreetmap.josm.data.preferences.NamedColorProperty;
41import org.openstreetmap.josm.data.preferences.PreferencesReader;
42import org.openstreetmap.josm.data.preferences.PreferencesWriter;
43import org.openstreetmap.josm.io.OfflineAccessException;
44import org.openstreetmap.josm.io.OnlineResource;
45import org.openstreetmap.josm.spi.preferences.AbstractPreferences;
46import org.openstreetmap.josm.spi.preferences.Config;
47import org.openstreetmap.josm.spi.preferences.IBaseDirectories;
48import org.openstreetmap.josm.spi.preferences.ListSetting;
49import org.openstreetmap.josm.spi.preferences.Setting;
50import org.openstreetmap.josm.spi.preferences.StringSetting;
51import org.openstreetmap.josm.tools.CheckParameterUtil;
52import org.openstreetmap.josm.tools.ListenerList;
53import org.openstreetmap.josm.tools.Logging;
54import org.openstreetmap.josm.tools.PlatformManager;
55import org.openstreetmap.josm.tools.Utils;
56import org.xml.sax.SAXException;
57
58/**
59 * This class holds all preferences for JOSM.
60 *
61 * Other classes can register their beloved properties here. All properties will be
62 * saved upon set-access.
63 *
64 * Each property is a key=setting pair, where key is a String and setting can be one of
65 * 4 types:
66 * string, list, list of lists and list of maps.
67 * In addition, each key has a unique default value that is set when the value is first
68 * accessed using one of the get...() methods. You can use the same preference
69 * key in different parts of the code, but the default value must be the same
70 * everywhere. A default value of null means, the setting has been requested, but
71 * no default value was set. This is used in advanced preferences to present a list
72 * off all possible settings.
73 *
74 * At the moment, you cannot put the empty string for string properties.
75 * put(key, "") means, the property is removed.
76 *
77 * @author imi
78 * @since 74
79 */
80public class Preferences extends AbstractPreferences {
81
82 private static final String[] OBSOLETE_PREF_KEYS = {
83 };
84
85 private static final long MAX_AGE_DEFAULT_PREFERENCES = TimeUnit.DAYS.toSeconds(50);
86
87 private final IBaseDirectories dirs;
88
89 /**
90 * Determines if preferences file is saved each time a property is changed.
91 */
92 private boolean saveOnPut = true;
93
94 /**
95 * Maps the setting name to the current value of the setting.
96 * The map must not contain null as key or value. The mapped setting objects
97 * must not have a null value.
98 */
99 protected final SortedMap<String, Setting<?>> settingsMap = new TreeMap<>();
100
101 /**
102 * Maps the setting name to the default value of the setting.
103 * The map must not contain null as key or value. The value of the mapped
104 * setting objects can be null.
105 */
106 protected final SortedMap<String, Setting<?>> defaultsMap = new TreeMap<>();
107
108 private final Predicate<Entry<String, Setting<?>>> NO_DEFAULT_SETTINGS_ENTRY =
109 e -> !e.getValue().equals(defaultsMap.get(e.getKey()));
110
111 /**
112 * Indicates whether {@link #init(boolean)} completed successfully.
113 * Used to decide whether to write backup preference file in {@link #save()}
114 */
115 protected boolean initSuccessful;
116
117 private final ListenerList<org.openstreetmap.josm.spi.preferences.PreferenceChangedListener> listeners = ListenerList.create();
118
119 private final HashMap<String, ListenerList<org.openstreetmap.josm.spi.preferences.PreferenceChangedListener>> keyListeners = new HashMap<>();
120
121 /**
122 * Constructs a new {@code Preferences}.
123 */
124 public Preferences() {
125 this.dirs = Config.getDirs();
126 }
127
128 /**
129 * Constructs a new {@code Preferences}.
130 *
131 * @param dirs the directories to use for saving the preferences
132 */
133 public Preferences(IBaseDirectories dirs) {
134 this.dirs = dirs;
135 }
136
137 /**
138 * Constructs a new {@code Preferences} from an existing instance.
139 * @param pref existing preferences to copy
140 * @since 12634
141 */
142 public Preferences(Preferences pref) {
143 this(pref.dirs);
144 settingsMap.putAll(pref.settingsMap);
145 defaultsMap.putAll(pref.defaultsMap);
146 }
147
148 /**
149 * Adds a new preferences listener.
150 * @param listener The listener to add
151 * @since 12881
152 */
153 @Override
154 public void addPreferenceChangeListener(org.openstreetmap.josm.spi.preferences.PreferenceChangedListener listener) {
155 if (listener != null) {
156 listeners.addListener(listener);
157 }
158 }
159
160 /**
161 * Removes a preferences listener.
162 * @param listener The listener to remove
163 * @since 12881
164 */
165 @Override
166 public void removePreferenceChangeListener(org.openstreetmap.josm.spi.preferences.PreferenceChangedListener listener) {
167 listeners.removeListener(listener);
168 }
169
170 /**
171 * Adds a listener that only listens to changes in one preference
172 * @param key The preference key to listen to
173 * @param listener The listener to add.
174 * @since 12881
175 */
176 @Override
177 public void addKeyPreferenceChangeListener(String key, org.openstreetmap.josm.spi.preferences.PreferenceChangedListener listener) {
178 listenersForKey(key).addListener(listener);
179 }
180
181 /**
182 * Adds a weak listener that only listens to changes in one preference
183 * @param key The preference key to listen to
184 * @param listener The listener to add.
185 * @since 10824
186 */
187 public void addWeakKeyPreferenceChangeListener(String key, org.openstreetmap.josm.spi.preferences.PreferenceChangedListener listener) {
188 listenersForKey(key).addWeakListener(listener);
189 }
190
191 private ListenerList<org.openstreetmap.josm.spi.preferences.PreferenceChangedListener> listenersForKey(String key) {
192 return keyListeners.computeIfAbsent(key, k -> ListenerList.create());
193 }
194
195 /**
196 * Removes a listener that only listens to changes in one preference
197 * @param key The preference key to listen to
198 * @param listener The listener to add.
199 * @since 12881
200 */
201 @Override
202 public void removeKeyPreferenceChangeListener(String key, org.openstreetmap.josm.spi.preferences.PreferenceChangedListener listener) {
203 Optional.ofNullable(keyListeners.get(key)).orElseThrow(
204 () -> new IllegalArgumentException("There are no listeners registered for " + key))
205 .removeListener(listener);
206 }
207
208 protected void firePreferenceChanged(String key, Setting<?> oldValue, Setting<?> newValue) {
209 final org.openstreetmap.josm.spi.preferences.PreferenceChangeEvent evt =
210 new org.openstreetmap.josm.spi.preferences.DefaultPreferenceChangeEvent(key, oldValue, newValue);
211 listeners.fireEvent(listener -> listener.preferenceChanged(evt));
212
213 ListenerList<org.openstreetmap.josm.spi.preferences.PreferenceChangedListener> forKey = keyListeners.get(key);
214 if (forKey != null) {
215 forKey.fireEvent(listener -> listener.preferenceChanged(evt));
216 }
217 }
218
219 /**
220 * Get the base name of the JOSM directories for preferences, cache and user data.
221 * Default value is "JOSM", unless overridden by system property "josm.dir.name".
222 * @return the base name of the JOSM directories for preferences, cache and user data
223 */
224 public String getJOSMDirectoryBaseName() {
225 String name = getSystemProperty("josm.dir.name");
226 if (name != null)
227 return name;
228 else
229 return "JOSM";
230 }
231
232 /**
233 * Get the base directories associated with this preference instance.
234 * @return the base directories
235 */
236 public IBaseDirectories getDirs() {
237 return dirs;
238 }
239
240 /**
241 * Returns the user preferences file (preferences.xml).
242 * @return The user preferences file (preferences.xml)
243 */
244 public File getPreferenceFile() {
245 return new File(dirs.getPreferencesDirectory(false), "preferences.xml");
246 }
247
248 /**
249 * Returns the cache file for default preferences.
250 * @return the cache file for default preferences
251 */
252 public File getDefaultsCacheFile() {
253 return new File(dirs.getCacheDirectory(true), "default_preferences.xml");
254 }
255
256 /**
257 * Returns the user plugin directory.
258 * @return The user plugin directory
259 */
260 public File getPluginsDirectory() {
261 return new File(dirs.getUserDataDirectory(false), "plugins");
262 }
263
264 private static void addPossibleResourceDir(Set<String> locations, String s) {
265 if (s != null) {
266 if (!s.endsWith(File.separator)) {
267 s += File.separator;
268 }
269 locations.add(s);
270 }
271 }
272
273 /**
274 * Returns a set of all existing directories where resources could be stored.
275 * @return A set of all existing directories where resources could be stored.
276 */
277 public Collection<String> getAllPossiblePreferenceDirs() {
278 Set<String> locations = new HashSet<>();
279 addPossibleResourceDir(locations, dirs.getPreferencesDirectory(false).getPath());
280 addPossibleResourceDir(locations, dirs.getUserDataDirectory(false).getPath());
281 addPossibleResourceDir(locations, getSystemEnv("JOSM_RESOURCES"));
282 addPossibleResourceDir(locations, getSystemProperty("josm.resources"));
283 locations.addAll(PlatformManager.getPlatform().getPossiblePreferenceDirs());
284 return locations;
285 }
286
287 /**
288 * Gets all normal (string) settings that have a key starting with the prefix
289 * @param prefix The start of the key
290 * @return The key names of the settings
291 */
292 public synchronized Map<String, String> getAllPrefix(final String prefix) {
293 final Map<String, String> all = new TreeMap<>();
294 for (final Entry<String, Setting<?>> e : settingsMap.entrySet()) {
295 if (e.getKey().startsWith(prefix) && (e.getValue() instanceof StringSetting)) {
296 all.put(e.getKey(), ((StringSetting) e.getValue()).getValue());
297 }
298 }
299 return all;
300 }
301
302 /**
303 * Gets all list settings that have a key starting with the prefix
304 * @param prefix The start of the key
305 * @return The key names of the list settings
306 */
307 public synchronized List<String> getAllPrefixCollectionKeys(final String prefix) {
308 final List<String> all = new LinkedList<>();
309 for (Map.Entry<String, Setting<?>> entry : settingsMap.entrySet()) {
310 if (entry.getKey().startsWith(prefix) && entry.getValue() instanceof ListSetting) {
311 all.add(entry.getKey());
312 }
313 }
314 return all;
315 }
316
317 /**
318 * Get all named colors, including customized and the default ones.
319 * @return a map of all named colors (maps preference key to {@link ColorInfo})
320 */
321 public synchronized Map<String, ColorInfo> getAllNamedColors() {
322 final Map<String, ColorInfo> all = new TreeMap<>();
323 for (final Entry<String, Setting<?>> e : settingsMap.entrySet()) {
324 if (!e.getKey().startsWith(NamedColorProperty.NAMED_COLOR_PREFIX))
325 continue;
326 Utils.instanceOfAndCast(e.getValue(), ListSetting.class)
327 .map(ListSetting::getValue)
328 .map(lst -> ColorInfo.fromPref(lst, false))
329 .ifPresent(info -> all.put(e.getKey(), info));
330 }
331 for (final Entry<String, Setting<?>> e : defaultsMap.entrySet()) {
332 if (!e.getKey().startsWith(NamedColorProperty.NAMED_COLOR_PREFIX))
333 continue;
334 Utils.instanceOfAndCast(e.getValue(), ListSetting.class)
335 .map(ListSetting::getValue)
336 .map(lst -> ColorInfo.fromPref(lst, true))
337 .ifPresent(infoDef -> {
338 ColorInfo info = all.get(e.getKey());
339 if (info == null) {
340 all.put(e.getKey(), infoDef);
341 } else {
342 info.setDefaultValue(infoDef.getDefaultValue());
343 }
344 });
345 }
346 return all;
347 }
348
349 /**
350 * Called after every put. In case of a problem, do nothing but output the error in log.
351 * @throws IOException if any I/O error occurs
352 */
353 public synchronized void save() throws IOException {
354 save(getPreferenceFile(), settingsMap.entrySet().stream().filter(NO_DEFAULT_SETTINGS_ENTRY), false);
355 }
356
357 /**
358 * Stores the defaults to the defaults file
359 * @throws IOException If the file could not be saved
360 */
361 public synchronized void saveDefaults() throws IOException {
362 save(getDefaultsCacheFile(), defaultsMap.entrySet().stream(), true);
363 }
364
365 protected void save(File prefFile, Stream<Entry<String, Setting<?>>> settings, boolean defaults) throws IOException {
366 if (!defaults) {
367 /* currently unused, but may help to fix configuration issues in future */
368 putInt("josm.version", Version.getInstance().getVersion());
369 }
370
371 File backupFile = new File(prefFile + "_backup");
372
373 // Backup old preferences if there are old preferences
374 if (initSuccessful && prefFile.exists() && prefFile.length() > 0) {
375 Utils.copyFile(prefFile, backupFile);
376 }
377
378 try (PreferencesWriter writer = new PreferencesWriter(
379 new PrintWriter(new File(prefFile + "_tmp"), StandardCharsets.UTF_8.name()), false, defaults)) {
380 writer.write(settings);
381 } catch (SecurityException e) {
382 throw new IOException(e);
383 }
384
385 File tmpFile = new File(prefFile + "_tmp");
386 Utils.copyFile(tmpFile, prefFile);
387 Utils.deleteFile(tmpFile, marktr("Unable to delete temporary file {0}"));
388
389 setCorrectPermissions(prefFile);
390 setCorrectPermissions(backupFile);
391 }
392
393 private static void setCorrectPermissions(File file) {
394 if (!file.setReadable(false, false) && Logging.isTraceEnabled()) {
395 Logging.trace(tr("Unable to set file non-readable {0}", file.getAbsolutePath()));
396 }
397 if (!file.setWritable(false, false) && Logging.isTraceEnabled()) {
398 Logging.trace(tr("Unable to set file non-writable {0}", file.getAbsolutePath()));
399 }
400 if (!file.setExecutable(false, false) && Logging.isTraceEnabled()) {
401 Logging.trace(tr("Unable to set file non-executable {0}", file.getAbsolutePath()));
402 }
403 if (!file.setReadable(true, true) && Logging.isTraceEnabled()) {
404 Logging.trace(tr("Unable to set file readable {0}", file.getAbsolutePath()));
405 }
406 if (!file.setWritable(true, true) && Logging.isTraceEnabled()) {
407 Logging.trace(tr("Unable to set file writable {0}", file.getAbsolutePath()));
408 }
409 }
410
411 /**
412 * Loads preferences from settings file.
413 * @throws IOException if any I/O error occurs while reading the file
414 * @throws SAXException if the settings file does not contain valid XML
415 * @throws XMLStreamException if an XML error occurs while parsing the file (after validation)
416 */
417 protected void load() throws IOException, SAXException, XMLStreamException {
418 File pref = getPreferenceFile();
419 PreferencesReader.validateXML(pref);
420 PreferencesReader reader = new PreferencesReader(pref, false);
421 reader.parse();
422 settingsMap.clear();
423 settingsMap.putAll(reader.getSettings());
424 removeObsolete(reader.getVersion());
425 }
426
427 /**
428 * Loads default preferences from default settings cache file.
429 *
430 * Discards entries older than {@link #MAX_AGE_DEFAULT_PREFERENCES}.
431 *
432 * @throws IOException if any I/O error occurs while reading the file
433 * @throws SAXException if the settings file does not contain valid XML
434 * @throws XMLStreamException if an XML error occurs while parsing the file (after validation)
435 */
436 protected void loadDefaults() throws IOException, XMLStreamException, SAXException {
437 File def = getDefaultsCacheFile();
438 PreferencesReader.validateXML(def);
439 PreferencesReader reader = new PreferencesReader(def, true);
440 reader.parse();
441 defaultsMap.clear();
442 long minTime = System.currentTimeMillis() / 1000 - MAX_AGE_DEFAULT_PREFERENCES;
443 for (Entry<String, Setting<?>> e : reader.getSettings().entrySet()) {
444 if (e.getValue().getTime() >= minTime) {
445 defaultsMap.put(e.getKey(), e.getValue());
446 }
447 }
448 }
449
450 /**
451 * Loads preferences from XML reader.
452 * @param in XML reader
453 * @throws XMLStreamException if any XML stream error occurs
454 * @throws IOException if any I/O error occurs
455 */
456 public void fromXML(Reader in) throws XMLStreamException, IOException {
457 PreferencesReader reader = new PreferencesReader(in, false);
458 reader.parse();
459 settingsMap.clear();
460 settingsMap.putAll(reader.getSettings());
461 }
462
463 /**
464 * Initializes preferences.
465 * @param reset if {@code true}, current settings file is replaced by the default one
466 */
467 public void init(boolean reset) {
468 initSuccessful = false;
469 // get the preferences.
470 File prefDir = dirs.getPreferencesDirectory(false);
471 if (prefDir.exists()) {
472 if (!prefDir.isDirectory()) {
473 Logging.warn(tr("Failed to initialize preferences. Preference directory ''{0}'' is not a directory.",
474 prefDir.getAbsoluteFile()));
475 if (!GraphicsEnvironment.isHeadless()) {
476 JOptionPane.showMessageDialog(
477 Main.parent,
478 tr("<html>Failed to initialize preferences.<br>Preference directory ''{0}'' is not a directory.</html>",
479 prefDir.getAbsoluteFile()),
480 tr("Error"),
481 JOptionPane.ERROR_MESSAGE
482 );
483 }
484 return;
485 }
486 } else {
487 if (!prefDir.mkdirs()) {
488 Logging.warn(tr("Failed to initialize preferences. Failed to create missing preference directory: {0}",
489 prefDir.getAbsoluteFile()));
490 if (!GraphicsEnvironment.isHeadless()) {
491 JOptionPane.showMessageDialog(
492 Main.parent,
493 tr("<html>Failed to initialize preferences.<br>Failed to create missing preference directory: {0}</html>",
494 prefDir.getAbsoluteFile()),
495 tr("Error"),
496 JOptionPane.ERROR_MESSAGE
497 );
498 }
499 return;
500 }
501 }
502
503 File preferenceFile = getPreferenceFile();
504 try {
505 if (!preferenceFile.exists()) {
506 Logging.info(tr("Missing preference file ''{0}''. Creating a default preference file.", preferenceFile.getAbsoluteFile()));
507 resetToDefault();
508 save();
509 } else if (reset) {
510 File backupFile = new File(prefDir, "preferences.xml.bak");
511 PlatformManager.getPlatform().rename(preferenceFile, backupFile);
512 Logging.warn(tr("Replacing existing preference file ''{0}'' with default preference file.", preferenceFile.getAbsoluteFile()));
513 resetToDefault();
514 save();
515 }
516 } catch (IOException | InvalidPathException e) {
517 Logging.error(e);
518 if (!GraphicsEnvironment.isHeadless()) {
519 JOptionPane.showMessageDialog(
520 Main.parent,
521 tr("<html>Failed to initialize preferences.<br>Failed to reset preference file to default: {0}</html>",
522 getPreferenceFile().getAbsoluteFile()),
523 tr("Error"),
524 JOptionPane.ERROR_MESSAGE
525 );
526 }
527 return;
528 }
529 try {
530 load();
531 initSuccessful = true;
532 } catch (IOException | SAXException | XMLStreamException e) {
533 Logging.error(e);
534 File backupFile = new File(prefDir, "preferences.xml.bak");
535 if (!GraphicsEnvironment.isHeadless()) {
536 JOptionPane.showMessageDialog(
537 Main.parent,
538 tr("<html>Preferences file had errors.<br> Making backup of old one to <br>{0}<br> " +
539 "and creating a new default preference file.</html>",
540 backupFile.getAbsoluteFile()),
541 tr("Error"),
542 JOptionPane.ERROR_MESSAGE
543 );
544 }
545 PlatformManager.getPlatform().rename(preferenceFile, backupFile);
546 try {
547 resetToDefault();
548 save();
549 } catch (IOException e1) {
550 Logging.error(e1);
551 Logging.warn(tr("Failed to initialize preferences. Failed to reset preference file to default: {0}", getPreferenceFile()));
552 }
553 }
554 File def = getDefaultsCacheFile();
555 if (def.exists()) {
556 try {
557 loadDefaults();
558 } catch (IOException | XMLStreamException | SAXException e) {
559 Logging.error(e);
560 Logging.warn(tr("Failed to load defaults cache file: {0}", def));
561 defaultsMap.clear();
562 if (!def.delete()) {
563 Logging.warn(tr("Failed to delete faulty defaults cache file: {0}", def));
564 }
565 }
566 }
567 }
568
569 /**
570 * Resets the preferences to their initial state. This resets all values and file associations.
571 * The default values and listeners are not removed.
572 * <p>
573 * It is meant to be called before {@link #init(boolean)}
574 * @since 10876
575 */
576 public void resetToInitialState() {
577 resetToDefault();
578 saveOnPut = true;
579 initSuccessful = false;
580 }
581
582 /**
583 * Reset all values stored in this map to the default values. This clears the preferences.
584 */
585 public final void resetToDefault() {
586 settingsMap.clear();
587 }
588
589 /**
590 * Set a value for a certain setting. The changed setting is saved to the preference file immediately.
591 * Due to caching mechanisms on modern operating systems and hardware, this shouldn't be a performance problem.
592 * @param key the unique identifier for the setting
593 * @param setting the value of the setting. In case it is null, the key-value entry will be removed.
594 * @return {@code true}, if something has changed (i.e. value is different than before)
595 */
596 @Override
597 public boolean putSetting(final String key, Setting<?> setting) {
598 CheckParameterUtil.ensureParameterNotNull(key);
599 if (setting != null && setting.getValue() == null)
600 throw new IllegalArgumentException("setting argument must not have null value");
601 Setting<?> settingOld;
602 Setting<?> settingCopy = null;
603 synchronized (this) {
604 if (setting == null) {
605 settingOld = settingsMap.remove(key);
606 if (settingOld == null)
607 return false;
608 } else {
609 settingOld = settingsMap.get(key);
610 if (setting.equals(settingOld))
611 return false;
612 if (settingOld == null && setting.equals(defaultsMap.get(key)))
613 return false;
614 settingCopy = setting.copy();
615 settingsMap.put(key, settingCopy);
616 }
617 if (saveOnPut) {
618 try {
619 save();
620 } catch (IOException | InvalidPathException e) {
621 File file = getPreferenceFile();
622 try {
623 file = file.getAbsoluteFile();
624 } catch (SecurityException ex) {
625 Logging.trace(ex);
626 }
627 Logging.log(Logging.LEVEL_WARN, tr("Failed to persist preferences to ''{0}''", file), e);
628 }
629 }
630 }
631 // Call outside of synchronized section in case some listener wait for other thread that wait for preference lock
632 firePreferenceChanged(key, settingOld, settingCopy);
633 return true;
634 }
635
636 /**
637 * Get a setting of any type
638 * @param key The key for the setting
639 * @param def The default value to use if it was not found
640 * @return The setting
641 */
642 public synchronized Setting<?> getSetting(String key, Setting<?> def) {
643 return getSetting(key, def, Setting.class);
644 }
645
646 /**
647 * Get settings value for a certain key and provide default a value.
648 * @param <T> the setting type
649 * @param key the identifier for the setting
650 * @param def the default value. For each call of getSetting() with a given key, the default value must be the same.
651 * <code>def</code> must not be null, but the value of <code>def</code> can be null.
652 * @param klass the setting type (same as T)
653 * @return the corresponding value if the property has been set before, {@code def} otherwise
654 */
655 @SuppressWarnings("unchecked")
656 @Override
657 public synchronized <T extends Setting<?>> T getSetting(String key, T def, Class<T> klass) {
658 CheckParameterUtil.ensureParameterNotNull(key);
659 CheckParameterUtil.ensureParameterNotNull(def);
660 Setting<?> oldDef = defaultsMap.get(key);
661 if (oldDef != null && oldDef.isNew() && oldDef.getValue() != null && def.getValue() != null && !def.equals(oldDef)) {
662 Logging.info("Defaults for " + key + " differ: " + def + " != " + defaultsMap.get(key));
663 }
664 if (def.getValue() != null || oldDef == null) {
665 Setting<?> defCopy = def.copy();
666 defCopy.setTime(System.currentTimeMillis() / 1000);
667 defCopy.setNew(true);
668 defaultsMap.put(key, defCopy);
669 }
670 Setting<?> prop = settingsMap.get(key);
671 if (klass.isInstance(prop)) {
672 return (T) prop;
673 } else {
674 return def;
675 }
676 }
677
678 @Override
679 public Set<String> getKeySet() {
680 return Collections.unmodifiableSet(settingsMap.keySet());
681 }
682
683 @Override
684 public Map<String, Setting<?>> getAllSettings() {
685 return new TreeMap<>(settingsMap);
686 }
687
688 /**
689 * Gets a map of all currently known defaults
690 * @return The map (key/setting)
691 */
692 public Map<String, Setting<?>> getAllDefaults() {
693 return new TreeMap<>(defaultsMap);
694 }
695
696 /**
697 * Replies the collection of plugin site URLs from where plugin lists can be downloaded.
698 * @return the collection of plugin site URLs
699 * @see #getOnlinePluginSites
700 */
701 public Collection<String> getPluginSites() {
702 return getList("pluginmanager.sites", Collections.singletonList(Config.getUrls().getJOSMWebsite()+"/pluginicons%<?plugins=>"));
703 }
704
705 /**
706 * Returns the list of plugin sites available according to offline mode settings.
707 * @return the list of available plugin sites
708 * @since 8471
709 */
710 public Collection<String> getOnlinePluginSites() {
711 Collection<String> pluginSites = new ArrayList<>(getPluginSites());
712 for (Iterator<String> it = pluginSites.iterator(); it.hasNext();) {
713 try {
714 OnlineResource.JOSM_WEBSITE.checkOfflineAccess(it.next(), Config.getUrls().getJOSMWebsite());
715 } catch (OfflineAccessException ex) {
716 Logging.log(Logging.LEVEL_WARN, ex);
717 it.remove();
718 }
719 }
720 return pluginSites;
721 }
722
723 /**
724 * Sets the collection of plugin site URLs.
725 *
726 * @param sites the site URLs
727 */
728 public void setPluginSites(Collection<String> sites) {
729 putList("pluginmanager.sites", new ArrayList<>(sites));
730 }
731
732 /**
733 * Returns XML describing these preferences.
734 * @param nopass if password must be excluded
735 * @return XML
736 */
737 public String toXML(boolean nopass) {
738 return toXML(settingsMap.entrySet(), nopass, false);
739 }
740
741 /**
742 * Returns XML describing the given preferences.
743 * @param settings preferences settings
744 * @param nopass if password must be excluded
745 * @param defaults true, if default values are converted to XML, false for
746 * regular preferences
747 * @return XML
748 */
749 public String toXML(Collection<Entry<String, Setting<?>>> settings, boolean nopass, boolean defaults) {
750 try (
751 StringWriter sw = new StringWriter();
752 PreferencesWriter prefWriter = new PreferencesWriter(new PrintWriter(sw), nopass, defaults)
753 ) {
754 prefWriter.write(settings);
755 sw.flush();
756 return sw.toString();
757 } catch (IOException e) {
758 Logging.error(e);
759 return null;
760 }
761 }
762
763 /**
764 * Removes obsolete preference settings. If you throw out a once-used preference
765 * setting, add it to the list here with an expiry date (written as comment). If you
766 * see something with an expiry date in the past, remove it from the list.
767 * @param loadedVersion JOSM version when the preferences file was written
768 */
769 private void removeObsolete(int loadedVersion) {
770 Logging.trace("Remove obsolete preferences for version {0}", Integer.toString(loadedVersion));
771 for (String key : OBSOLETE_PREF_KEYS) {
772 if (settingsMap.containsKey(key)) {
773 settingsMap.remove(key);
774 Logging.info(tr("Preference setting {0} has been removed since it is no longer used.", key));
775 }
776 }
777 }
778
779 /**
780 * Enables or not the preferences file auto-save mechanism (save each time a setting is changed).
781 * This behaviour is enabled by default.
782 * @param enable if {@code true}, makes JOSM save preferences file each time a setting is changed
783 * @since 7085
784 */
785 public final void enableSaveOnPut(boolean enable) {
786 synchronized (this) {
787 saveOnPut = enable;
788 }
789 }
790}
Note: See TracBrowser for help on using the repository browser.