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

Last change on this file since 12840 was 12840, checked in by bastiK, 7 years ago

see #15229 - extract interface for Preferences class

some changes to the method names and signatures

  • to be more in line with java.util.prefs.Preferences:
    put(String, boolean) -> putBoolean(String, boolean)
    getInteger(String) -> getInt(String)
    putInteger(String, Integer) -> putInt(String, int)
    putDouble(String, Double) -> putDouble(String, double)
    
  • for internal consistency with Setting classes:
    getCollection -> getList
    putCollection -> putList
    getArray -> getListOfLists
    putArray -> putListOfLists
    getListOfStructs -> getListOfMaps
    putListOfStructs -> putListOfMaps
    
  • Property svn:eol-style set to native
File size: 65.0 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;
6
7import java.awt.Color;
8import java.awt.GraphicsEnvironment;
9import java.awt.Toolkit;
10import java.io.File;
11import java.io.IOException;
12import java.io.PrintWriter;
13import java.io.Reader;
14import java.io.StringReader;
15import java.io.StringWriter;
16import java.lang.annotation.Retention;
17import java.lang.annotation.RetentionPolicy;
18import java.lang.reflect.Field;
19import java.nio.charset.StandardCharsets;
20import java.util.AbstractMap;
21import java.util.ArrayList;
22import java.util.Collection;
23import java.util.Collections;
24import java.util.HashMap;
25import java.util.HashSet;
26import java.util.Iterator;
27import java.util.LinkedHashMap;
28import java.util.LinkedList;
29import java.util.List;
30import java.util.Map;
31import java.util.Map.Entry;
32import java.util.Objects;
33import java.util.Optional;
34import java.util.ResourceBundle;
35import java.util.Set;
36import java.util.SortedMap;
37import java.util.TreeMap;
38import java.util.concurrent.TimeUnit;
39import java.util.function.Predicate;
40import java.util.regex.Matcher;
41import java.util.regex.Pattern;
42import java.util.stream.Collectors;
43import java.util.stream.Stream;
44
45import javax.json.Json;
46import javax.json.JsonArray;
47import javax.json.JsonArrayBuilder;
48import javax.json.JsonObject;
49import javax.json.JsonObjectBuilder;
50import javax.json.JsonReader;
51import javax.json.JsonString;
52import javax.json.JsonValue;
53import javax.json.JsonWriter;
54import javax.swing.JOptionPane;
55import javax.xml.stream.XMLStreamException;
56
57import org.openstreetmap.josm.Main;
58import org.openstreetmap.josm.data.preferences.AbstractPreferences;
59import org.openstreetmap.josm.data.preferences.BooleanProperty;
60import org.openstreetmap.josm.data.preferences.ColorProperty;
61import org.openstreetmap.josm.data.preferences.IPreferences;
62import org.openstreetmap.josm.data.preferences.IntegerProperty;
63import org.openstreetmap.josm.data.preferences.ListListSetting;
64import org.openstreetmap.josm.data.preferences.ListSetting;
65import org.openstreetmap.josm.data.preferences.LongProperty;
66import org.openstreetmap.josm.data.preferences.MapListSetting;
67import org.openstreetmap.josm.data.preferences.PreferencesReader;
68import org.openstreetmap.josm.data.preferences.PreferencesWriter;
69import org.openstreetmap.josm.data.preferences.Setting;
70import org.openstreetmap.josm.data.preferences.StringSetting;
71import org.openstreetmap.josm.data.preferences.sources.ExtendedSourceEntry;
72import org.openstreetmap.josm.data.preferences.sources.ValidatorPrefHelper;
73import org.openstreetmap.josm.io.OfflineAccessException;
74import org.openstreetmap.josm.io.OnlineResource;
75import org.openstreetmap.josm.tools.CheckParameterUtil;
76import org.openstreetmap.josm.tools.ColorHelper;
77import org.openstreetmap.josm.tools.I18n;
78import org.openstreetmap.josm.tools.JosmRuntimeException;
79import org.openstreetmap.josm.tools.ListenerList;
80import org.openstreetmap.josm.tools.Logging;
81import org.openstreetmap.josm.tools.MultiMap;
82import org.openstreetmap.josm.tools.Utils;
83import org.xml.sax.SAXException;
84
85/**
86 * This class holds all preferences for JOSM.
87 *
88 * Other classes can register their beloved properties here. All properties will be
89 * saved upon set-access.
90 *
91 * Each property is a key=setting pair, where key is a String and setting can be one of
92 * 4 types:
93 * string, list, list of lists and list of maps.
94 * In addition, each key has a unique default value that is set when the value is first
95 * accessed using one of the get...() methods. You can use the same preference
96 * key in different parts of the code, but the default value must be the same
97 * everywhere. A default value of null means, the setting has been requested, but
98 * no default value was set. This is used in advanced preferences to present a list
99 * off all possible settings.
100 *
101 * At the moment, you cannot put the empty string for string properties.
102 * put(key, "") means, the property is removed.
103 *
104 * @author imi
105 * @since 74
106 */
107public class Preferences extends AbstractPreferences {
108
109 private static final String COLOR_PREFIX = "color.";
110
111 private static final String[] OBSOLETE_PREF_KEYS = {
112 "imagery.layers.addedIds", /* remove entry after June 2017 */
113 "projection", /* remove entry after Nov. 2017 */
114 "projection.sub", /* remove entry after Nov. 2017 */
115 };
116
117 private static final long MAX_AGE_DEFAULT_PREFERENCES = TimeUnit.DAYS.toSeconds(50);
118
119 /**
120 * Internal storage for the preference directory.
121 * Do not access this variable directly!
122 * @see #getPreferencesDirectory()
123 */
124 private File preferencesDir;
125
126 /**
127 * Internal storage for the cache directory.
128 */
129 private File cacheDir;
130
131 /**
132 * Internal storage for the user data directory.
133 */
134 private File userdataDir;
135
136 /**
137 * Determines if preferences file is saved each time a property is changed.
138 */
139 private boolean saveOnPut = true;
140
141 /**
142 * Maps the setting name to the current value of the setting.
143 * The map must not contain null as key or value. The mapped setting objects
144 * must not have a null value.
145 */
146 protected final SortedMap<String, Setting<?>> settingsMap = new TreeMap<>();
147
148 /**
149 * Maps the setting name to the default value of the setting.
150 * The map must not contain null as key or value. The value of the mapped
151 * setting objects can be null.
152 */
153 protected final SortedMap<String, Setting<?>> defaultsMap = new TreeMap<>();
154
155 private final Predicate<Entry<String, Setting<?>>> NO_DEFAULT_SETTINGS_ENTRY =
156 e -> !e.getValue().equals(defaultsMap.get(e.getKey()));
157
158 /**
159 * Maps color keys to human readable color name
160 */
161 protected final SortedMap<String, String> colornames = new TreeMap<>();
162
163 /**
164 * Indicates whether {@link #init(boolean)} completed successfully.
165 * Used to decide whether to write backup preference file in {@link #save()}
166 */
167 protected boolean initSuccessful;
168
169 /**
170 * Event triggered when a preference entry value changes.
171 */
172 public interface PreferenceChangeEvent {
173 /**
174 * Returns the preference key.
175 * @return the preference key
176 */
177 String getKey();
178
179 /**
180 * Returns the old preference value.
181 * @return the old preference value
182 */
183 Setting<?> getOldValue();
184
185 /**
186 * Returns the new preference value.
187 * @return the new preference value
188 */
189 Setting<?> getNewValue();
190 }
191
192 /**
193 * Listener to preference change events.
194 * @since 10600 (functional interface)
195 */
196 @FunctionalInterface
197 public interface PreferenceChangedListener {
198 /**
199 * Trigerred when a preference entry value changes.
200 * @param e the preference change event
201 */
202 void preferenceChanged(PreferenceChangeEvent e);
203 }
204
205 private static class DefaultPreferenceChangeEvent implements PreferenceChangeEvent {
206 private final String key;
207 private final Setting<?> oldValue;
208 private final Setting<?> newValue;
209
210 DefaultPreferenceChangeEvent(String key, Setting<?> oldValue, Setting<?> newValue) {
211 this.key = key;
212 this.oldValue = oldValue;
213 this.newValue = newValue;
214 }
215
216 @Override
217 public String getKey() {
218 return key;
219 }
220
221 @Override
222 public Setting<?> getOldValue() {
223 return oldValue;
224 }
225
226 @Override
227 public Setting<?> getNewValue() {
228 return newValue;
229 }
230 }
231
232 private final ListenerList<PreferenceChangedListener> listeners = ListenerList.create();
233
234 private final HashMap<String, ListenerList<PreferenceChangedListener>> keyListeners = new HashMap<>();
235
236 /**
237 * Constructs a new {@code Preferences}.
238 */
239 public Preferences() {
240 // Default constructor
241 }
242
243 /**
244 * Constructs a new {@code Preferences} from an existing instance.
245 * @param pref existing preferences to copy
246 * @since 12634
247 */
248 public Preferences(Preferences pref) {
249 settingsMap.putAll(pref.settingsMap);
250 defaultsMap.putAll(pref.defaultsMap);
251 colornames.putAll(pref.colornames);
252 }
253
254 /**
255 * Adds a new preferences listener.
256 * @param listener The listener to add
257 */
258 @Override
259 public void addPreferenceChangeListener(PreferenceChangedListener listener) {
260 if (listener != null) {
261 listeners.addListener(listener);
262 }
263 }
264
265 /**
266 * Removes a preferences listener.
267 * @param listener The listener to remove
268 */
269 @Override
270 public void removePreferenceChangeListener(PreferenceChangedListener listener) {
271 listeners.removeListener(listener);
272 }
273
274 /**
275 * Adds a listener that only listens to changes in one preference
276 * @param key The preference key to listen to
277 * @param listener The listener to add.
278 * @since 10824
279 */
280 @Override
281 public void addKeyPreferenceChangeListener(String key, PreferenceChangedListener listener) {
282 listenersForKey(key).addListener(listener);
283 }
284
285 /**
286 * Adds a weak listener that only listens to changes in one preference
287 * @param key The preference key to listen to
288 * @param listener The listener to add.
289 * @since 10824
290 */
291 public void addWeakKeyPreferenceChangeListener(String key, PreferenceChangedListener listener) {
292 listenersForKey(key).addWeakListener(listener);
293 }
294
295 private ListenerList<PreferenceChangedListener> listenersForKey(String key) {
296 ListenerList<PreferenceChangedListener> keyListener = keyListeners.get(key);
297 if (keyListener == null) {
298 keyListener = ListenerList.create();
299 keyListeners.put(key, keyListener);
300 }
301 return keyListener;
302 }
303
304 /**
305 * Removes a listener that only listens to changes in one preference
306 * @param key The preference key to listen to
307 * @param listener The listener to add.
308 */
309 @Override
310 public void removeKeyPreferenceChangeListener(String key, PreferenceChangedListener listener) {
311 Optional.ofNullable(keyListeners.get(key)).orElseThrow(
312 () -> new IllegalArgumentException("There are no listeners registered for " + key))
313 .removeListener(listener);
314 }
315
316 protected void firePreferenceChanged(String key, Setting<?> oldValue, Setting<?> newValue) {
317 final PreferenceChangeEvent evt = new DefaultPreferenceChangeEvent(key, oldValue, newValue);
318 listeners.fireEvent(listener -> listener.preferenceChanged(evt));
319
320 ListenerList<PreferenceChangedListener> forKey = keyListeners.get(key);
321 if (forKey != null) {
322 forKey.fireEvent(listener -> listener.preferenceChanged(evt));
323 }
324 }
325
326 /**
327 * Get the base name of the JOSM directories for preferences, cache and
328 * user data.
329 * Default value is "JOSM", unless overridden by system property "josm.dir.name".
330 * @return the base name of the JOSM directories for preferences, cache and
331 * user data
332 */
333 public String getJOSMDirectoryBaseName() {
334 String name = System.getProperty("josm.dir.name");
335 if (name != null)
336 return name;
337 else
338 return "JOSM";
339 }
340
341 /**
342 * Returns the user defined preferences directory, containing the preferences.xml file
343 * @return The user defined preferences directory, containing the preferences.xml file
344 * @since 7834
345 */
346 public File getPreferencesDirectory() {
347 if (preferencesDir != null)
348 return preferencesDir;
349 String path;
350 path = System.getProperty("josm.pref");
351 if (path != null) {
352 preferencesDir = new File(path).getAbsoluteFile();
353 } else {
354 path = System.getProperty("josm.home");
355 if (path != null) {
356 preferencesDir = new File(path).getAbsoluteFile();
357 } else {
358 preferencesDir = Main.platform.getDefaultPrefDirectory();
359 }
360 }
361 return preferencesDir;
362 }
363
364 /**
365 * Returns the user data directory, containing autosave, plugins, etc.
366 * Depending on the OS it may be the same directory as preferences directory.
367 * @return The user data directory, containing autosave, plugins, etc.
368 * @since 7834
369 */
370 public File getUserDataDirectory() {
371 if (userdataDir != null)
372 return userdataDir;
373 String path;
374 path = System.getProperty("josm.userdata");
375 if (path != null) {
376 userdataDir = new File(path).getAbsoluteFile();
377 } else {
378 path = System.getProperty("josm.home");
379 if (path != null) {
380 userdataDir = new File(path).getAbsoluteFile();
381 } else {
382 userdataDir = Main.platform.getDefaultUserDataDirectory();
383 }
384 }
385 return userdataDir;
386 }
387
388 /**
389 * Returns the user preferences file (preferences.xml).
390 * @return The user preferences file (preferences.xml)
391 */
392 public File getPreferenceFile() {
393 return new File(getPreferencesDirectory(), "preferences.xml");
394 }
395
396 /**
397 * Returns the cache file for default preferences.
398 * @return the cache file for default preferences
399 */
400 public File getDefaultsCacheFile() {
401 return new File(getCacheDirectory(), "default_preferences.xml");
402 }
403
404 /**
405 * Returns the user plugin directory.
406 * @return The user plugin directory
407 */
408 public File getPluginsDirectory() {
409 return new File(getUserDataDirectory(), "plugins");
410 }
411
412 /**
413 * Get the directory where cached content of any kind should be stored.
414 *
415 * If the directory doesn't exist on the file system, it will be created by this method.
416 *
417 * @return the cache directory
418 */
419 public File getCacheDirectory() {
420 if (cacheDir != null)
421 return cacheDir;
422 String path = System.getProperty("josm.cache");
423 if (path != null) {
424 cacheDir = new File(path).getAbsoluteFile();
425 } else {
426 path = System.getProperty("josm.home");
427 if (path != null) {
428 cacheDir = new File(path, "cache");
429 } else {
430 path = get("cache.folder", null);
431 if (path != null) {
432 cacheDir = new File(path).getAbsoluteFile();
433 } else {
434 cacheDir = Main.platform.getDefaultCacheDirectory();
435 }
436 }
437 }
438 if (!cacheDir.exists() && !cacheDir.mkdirs()) {
439 Logging.warn(tr("Failed to create missing cache directory: {0}", cacheDir.getAbsoluteFile()));
440 JOptionPane.showMessageDialog(
441 Main.parent,
442 tr("<html>Failed to create missing cache directory: {0}</html>", cacheDir.getAbsoluteFile()),
443 tr("Error"),
444 JOptionPane.ERROR_MESSAGE
445 );
446 }
447 return cacheDir;
448 }
449
450 private static void addPossibleResourceDir(Set<String> locations, String s) {
451 if (s != null) {
452 if (!s.endsWith(File.separator)) {
453 s += File.separator;
454 }
455 locations.add(s);
456 }
457 }
458
459 /**
460 * Returns a set of all existing directories where resources could be stored.
461 * @return A set of all existing directories where resources could be stored.
462 */
463 public Collection<String> getAllPossiblePreferenceDirs() {
464 Set<String> locations = new HashSet<>();
465 addPossibleResourceDir(locations, getPreferencesDirectory().getPath());
466 addPossibleResourceDir(locations, getUserDataDirectory().getPath());
467 addPossibleResourceDir(locations, System.getenv("JOSM_RESOURCES"));
468 addPossibleResourceDir(locations, System.getProperty("josm.resources"));
469 if (Main.isPlatformWindows()) {
470 String appdata = System.getenv("APPDATA");
471 if (appdata != null && System.getenv("ALLUSERSPROFILE") != null
472 && appdata.lastIndexOf(File.separator) != -1) {
473 appdata = appdata.substring(appdata.lastIndexOf(File.separator));
474 locations.add(new File(new File(System.getenv("ALLUSERSPROFILE"),
475 appdata), "JOSM").getPath());
476 }
477 } else {
478 locations.add("/usr/local/share/josm/");
479 locations.add("/usr/local/lib/josm/");
480 locations.add("/usr/share/josm/");
481 locations.add("/usr/lib/josm/");
482 }
483 return locations;
484 }
485
486 /**
487 * Gets all normal (string) settings that have a key starting with the prefix
488 * @param prefix The start of the key
489 * @return The key names of the settings
490 */
491 public synchronized Map<String, String> getAllPrefix(final String prefix) {
492 final Map<String, String> all = new TreeMap<>();
493 for (final Entry<String, Setting<?>> e : settingsMap.entrySet()) {
494 if (e.getKey().startsWith(prefix) && (e.getValue() instanceof StringSetting)) {
495 all.put(e.getKey(), ((StringSetting) e.getValue()).getValue());
496 }
497 }
498 return all;
499 }
500
501 /**
502 * Gets all list settings that have a key starting with the prefix
503 * @param prefix The start of the key
504 * @return The key names of the list settings
505 */
506 public synchronized List<String> getAllPrefixCollectionKeys(final String prefix) {
507 final List<String> all = new LinkedList<>();
508 for (Map.Entry<String, Setting<?>> entry : settingsMap.entrySet()) {
509 if (entry.getKey().startsWith(prefix) && entry.getValue() instanceof ListSetting) {
510 all.add(entry.getKey());
511 }
512 }
513 return all;
514 }
515
516 /**
517 * Gets all known colors (preferences starting with the color prefix)
518 * @return All colors
519 */
520 public synchronized Map<String, String> getAllColors() {
521 final Map<String, String> all = new TreeMap<>();
522 for (final Entry<String, Setting<?>> e : defaultsMap.entrySet()) {
523 if (e.getKey().startsWith(COLOR_PREFIX) && e.getValue() instanceof StringSetting) {
524 StringSetting d = (StringSetting) e.getValue();
525 if (d.getValue() != null) {
526 all.put(e.getKey().substring(6), d.getValue());
527 }
528 }
529 }
530 for (final Entry<String, Setting<?>> e : settingsMap.entrySet()) {
531 if (e.getKey().startsWith(COLOR_PREFIX) && (e.getValue() instanceof StringSetting)) {
532 all.put(e.getKey().substring(6), ((StringSetting) e.getValue()).getValue());
533 }
534 }
535 return all;
536 }
537
538 /**
539 * Gets an boolean that may be specialized
540 * @param key The basic key
541 * @param specName The sub-key to append to the key
542 * @param def The default value
543 * @return The boolean value or the default value if it could not be parsed
544 */
545 public synchronized boolean getBoolean(final String key, final String specName, final boolean def) {
546 boolean generic = getBoolean(key, def);
547 String skey = key+'.'+specName;
548 Setting<?> prop = settingsMap.get(skey);
549 if (prop instanceof StringSetting)
550 return Boolean.parseBoolean(((StringSetting) prop).getValue());
551 else
552 return generic;
553 }
554
555 /**
556 * Set a boolean value for a certain setting.
557 * @param key the unique identifier for the setting
558 * @param value The new value
559 * @return {@code true}, if something has changed (i.e. value is different than before)
560 * @see BooleanProperty
561 * @deprecated use {@link IPreferences#putBoolean(String, boolean)}
562 */
563 @Deprecated
564 public boolean put(final String key, final boolean value) {
565 return put(key, Boolean.toString(value));
566 }
567
568 /**
569 * Set a boolean value for a certain setting.
570 * @param key the unique identifier for the setting
571 * @param value The new value
572 * @return {@code true}, if something has changed (i.e. value is different than before)
573 * @see IntegerProperty#put(Integer)
574 * @deprecated use {@link IPreferences#putInt(String, int)}
575 */
576 @Deprecated
577 public boolean putInteger(final String key, final Integer value) {
578 return put(key, Integer.toString(value));
579 }
580
581 /**
582 * Set a boolean value for a certain setting.
583 * @param key the unique identifier for the setting
584 * @param value The new value
585 * @return {@code true}, if something has changed (i.e. value is different than before)
586 * @see DoubleProperty#put(Double)
587 * @deprecated use {@link IPreferences#putDouble(java.lang.String, double)}
588 */
589 @Deprecated
590 public boolean putDouble(final String key, final Double value) {
591 return put(key, Double.toString(value));
592 }
593
594 /**
595 * Set a boolean value for a certain setting.
596 * @param key the unique identifier for the setting
597 * @param value The new value
598 * @return {@code true}, if something has changed (i.e. value is different than before)
599 * @see LongProperty#put(Long)
600 */
601 public boolean putLong(final String key, final Long value) {
602 return put(key, Long.toString(value));
603 }
604
605 /**
606 * Called after every put. In case of a problem, do nothing but output the error in log.
607 * @throws IOException if any I/O error occurs
608 */
609 public synchronized void save() throws IOException {
610 save(getPreferenceFile(), settingsMap.entrySet().stream().filter(NO_DEFAULT_SETTINGS_ENTRY), false);
611 }
612
613 /**
614 * Stores the defaults to the defaults file
615 * @throws IOException If the file could not be saved
616 */
617 public synchronized void saveDefaults() throws IOException {
618 save(getDefaultsCacheFile(), defaultsMap.entrySet().stream(), true);
619 }
620
621 protected void save(File prefFile, Stream<Entry<String, Setting<?>>> settings, boolean defaults) throws IOException {
622 if (!defaults) {
623 /* currently unused, but may help to fix configuration issues in future */
624 putInt("josm.version", Version.getInstance().getVersion());
625
626 updateSystemProperties();
627 }
628
629 File backupFile = new File(prefFile + "_backup");
630
631 // Backup old preferences if there are old preferences
632 if (initSuccessful && prefFile.exists() && prefFile.length() > 0) {
633 Utils.copyFile(prefFile, backupFile);
634 }
635
636 try (PreferencesWriter writer = new PreferencesWriter(
637 new PrintWriter(new File(prefFile + "_tmp"), StandardCharsets.UTF_8.name()), false, defaults)) {
638 writer.write(settings);
639 }
640
641 File tmpFile = new File(prefFile + "_tmp");
642 Utils.copyFile(tmpFile, prefFile);
643 Utils.deleteFile(tmpFile, marktr("Unable to delete temporary file {0}"));
644
645 setCorrectPermissions(prefFile);
646 setCorrectPermissions(backupFile);
647 }
648
649 private static void setCorrectPermissions(File file) {
650 if (!file.setReadable(false, false) && Logging.isTraceEnabled()) {
651 Logging.trace(tr("Unable to set file non-readable {0}", file.getAbsolutePath()));
652 }
653 if (!file.setWritable(false, false) && Logging.isTraceEnabled()) {
654 Logging.trace(tr("Unable to set file non-writable {0}", file.getAbsolutePath()));
655 }
656 if (!file.setExecutable(false, false) && Logging.isTraceEnabled()) {
657 Logging.trace(tr("Unable to set file non-executable {0}", file.getAbsolutePath()));
658 }
659 if (!file.setReadable(true, true) && Logging.isTraceEnabled()) {
660 Logging.trace(tr("Unable to set file readable {0}", file.getAbsolutePath()));
661 }
662 if (!file.setWritable(true, true) && Logging.isTraceEnabled()) {
663 Logging.trace(tr("Unable to set file writable {0}", file.getAbsolutePath()));
664 }
665 }
666
667 /**
668 * Loads preferences from settings file.
669 * @throws IOException if any I/O error occurs while reading the file
670 * @throws SAXException if the settings file does not contain valid XML
671 * @throws XMLStreamException if an XML error occurs while parsing the file (after validation)
672 */
673 protected void load() throws IOException, SAXException, XMLStreamException {
674 File pref = getPreferenceFile();
675 PreferencesReader.validateXML(pref);
676 PreferencesReader reader = new PreferencesReader(pref, false);
677 reader.parse();
678 settingsMap.clear();
679 settingsMap.putAll(reader.getSettings());
680 updateSystemProperties();
681 removeObsolete(reader.getVersion());
682 }
683
684 /**
685 * Loads default preferences from default settings cache file.
686 *
687 * Discards entries older than {@link #MAX_AGE_DEFAULT_PREFERENCES}.
688 *
689 * @throws IOException if any I/O error occurs while reading the file
690 * @throws SAXException if the settings file does not contain valid XML
691 * @throws XMLStreamException if an XML error occurs while parsing the file (after validation)
692 */
693 protected void loadDefaults() throws IOException, XMLStreamException, SAXException {
694 File def = getDefaultsCacheFile();
695 PreferencesReader.validateXML(def);
696 PreferencesReader reader = new PreferencesReader(def, true);
697 reader.parse();
698 defaultsMap.clear();
699 long minTime = System.currentTimeMillis() / 1000 - MAX_AGE_DEFAULT_PREFERENCES;
700 for (Entry<String, Setting<?>> e : reader.getSettings().entrySet()) {
701 if (e.getValue().getTime() >= minTime) {
702 defaultsMap.put(e.getKey(), e.getValue());
703 }
704 }
705 }
706
707 /**
708 * Loads preferences from XML reader.
709 * @param in XML reader
710 * @throws XMLStreamException if any XML stream error occurs
711 * @throws IOException if any I/O error occurs
712 */
713 public void fromXML(Reader in) throws XMLStreamException, IOException {
714 PreferencesReader reader = new PreferencesReader(in, false);
715 reader.parse();
716 settingsMap.clear();
717 settingsMap.putAll(reader.getSettings());
718 }
719
720 /**
721 * Initializes preferences.
722 * @param reset if {@code true}, current settings file is replaced by the default one
723 */
724 public void init(boolean reset) {
725 initSuccessful = false;
726 // get the preferences.
727 File prefDir = getPreferencesDirectory();
728 if (prefDir.exists()) {
729 if (!prefDir.isDirectory()) {
730 Logging.warn(tr("Failed to initialize preferences. Preference directory ''{0}'' is not a directory.",
731 prefDir.getAbsoluteFile()));
732 JOptionPane.showMessageDialog(
733 Main.parent,
734 tr("<html>Failed to initialize preferences.<br>Preference directory ''{0}'' is not a directory.</html>",
735 prefDir.getAbsoluteFile()),
736 tr("Error"),
737 JOptionPane.ERROR_MESSAGE
738 );
739 return;
740 }
741 } else {
742 if (!prefDir.mkdirs()) {
743 Logging.warn(tr("Failed to initialize preferences. Failed to create missing preference directory: {0}",
744 prefDir.getAbsoluteFile()));
745 JOptionPane.showMessageDialog(
746 Main.parent,
747 tr("<html>Failed to initialize preferences.<br>Failed to create missing preference directory: {0}</html>",
748 prefDir.getAbsoluteFile()),
749 tr("Error"),
750 JOptionPane.ERROR_MESSAGE
751 );
752 return;
753 }
754 }
755
756 File preferenceFile = getPreferenceFile();
757 try {
758 if (!preferenceFile.exists()) {
759 Logging.info(tr("Missing preference file ''{0}''. Creating a default preference file.", preferenceFile.getAbsoluteFile()));
760 resetToDefault();
761 save();
762 } else if (reset) {
763 File backupFile = new File(prefDir, "preferences.xml.bak");
764 Main.platform.rename(preferenceFile, backupFile);
765 Logging.warn(tr("Replacing existing preference file ''{0}'' with default preference file.", preferenceFile.getAbsoluteFile()));
766 resetToDefault();
767 save();
768 }
769 } catch (IOException e) {
770 Logging.error(e);
771 JOptionPane.showMessageDialog(
772 Main.parent,
773 tr("<html>Failed to initialize preferences.<br>Failed to reset preference file to default: {0}</html>",
774 getPreferenceFile().getAbsoluteFile()),
775 tr("Error"),
776 JOptionPane.ERROR_MESSAGE
777 );
778 return;
779 }
780 try {
781 load();
782 initSuccessful = true;
783 } catch (IOException | SAXException | XMLStreamException e) {
784 Logging.error(e);
785 File backupFile = new File(prefDir, "preferences.xml.bak");
786 JOptionPane.showMessageDialog(
787 Main.parent,
788 tr("<html>Preferences file had errors.<br> Making backup of old one to <br>{0}<br> " +
789 "and creating a new default preference file.</html>",
790 backupFile.getAbsoluteFile()),
791 tr("Error"),
792 JOptionPane.ERROR_MESSAGE
793 );
794 Main.platform.rename(preferenceFile, backupFile);
795 try {
796 resetToDefault();
797 save();
798 } catch (IOException e1) {
799 Logging.error(e1);
800 Logging.warn(tr("Failed to initialize preferences. Failed to reset preference file to default: {0}", getPreferenceFile()));
801 }
802 }
803 File def = getDefaultsCacheFile();
804 if (def.exists()) {
805 try {
806 loadDefaults();
807 } catch (IOException | XMLStreamException | SAXException e) {
808 Logging.error(e);
809 Logging.warn(tr("Failed to load defaults cache file: {0}", def));
810 defaultsMap.clear();
811 if (!def.delete()) {
812 Logging.warn(tr("Failed to delete faulty defaults cache file: {0}", def));
813 }
814 }
815 }
816 }
817
818 /**
819 * Resets the preferences to their initial state. This resets all values and file associations.
820 * The default values and listeners are not removed.
821 * <p>
822 * It is meant to be called before {@link #init(boolean)}
823 * @since 10876
824 */
825 public void resetToInitialState() {
826 resetToDefault();
827 preferencesDir = null;
828 cacheDir = null;
829 userdataDir = null;
830 saveOnPut = true;
831 initSuccessful = false;
832 }
833
834 /**
835 * Reset all values stored in this map to the default values. This clears the preferences.
836 */
837 public final void resetToDefault() {
838 settingsMap.clear();
839 }
840
841 /**
842 * Convenience method for accessing colour preferences.
843 * <p>
844 * To be removed: end of 2016
845 *
846 * @param colName name of the colour
847 * @param def default value
848 * @return a Color object for the configured colour, or the default value if none configured.
849 * @deprecated Use a {@link ColorProperty} instead.
850 */
851 @Deprecated
852 public synchronized Color getColor(String colName, Color def) {
853 return getColor(colName, null, def);
854 }
855
856 /* only for preferences */
857 public synchronized String getColorName(String o) {
858 Matcher m = Pattern.compile("mappaint\\.(.+?)\\.(.+)").matcher(o);
859 if (m.matches()) {
860 return tr("Paint style {0}: {1}", tr(I18n.escape(m.group(1))), tr(I18n.escape(m.group(2))));
861 }
862 m = Pattern.compile("layer (.+)").matcher(o);
863 if (m.matches()) {
864 return tr("Layer: {0}", tr(I18n.escape(m.group(1))));
865 }
866 return tr(I18n.escape(colornames.containsKey(o) ? colornames.get(o) : o));
867 }
868
869 /**
870 * Convenience method for accessing colour preferences.
871 * <p>
872 * To be removed: end of 2016
873 * @param colName name of the colour
874 * @param specName name of the special colour settings
875 * @param def default value
876 * @return a Color object for the configured colour, or the default value if none configured.
877 * @deprecated Use a {@link ColorProperty} instead.
878 * You can replace this by: <code>new ColorProperty(colName, def).getChildColor(specName)</code>
879 */
880 @Deprecated
881 public synchronized Color getColor(String colName, String specName, Color def) {
882 String colKey = ColorProperty.getColorKey(colName);
883 registerColor(colKey, colName);
884 String colStr = specName != null ? get(COLOR_PREFIX+specName) : "";
885 if (colStr.isEmpty()) {
886 colStr = get(colKey, ColorHelper.color2html(def, true));
887 }
888 if (colStr != null && !colStr.isEmpty()) {
889 return ColorHelper.html2color(colStr);
890 } else {
891 return def;
892 }
893 }
894
895 /**
896 * Registers a color name conversion for the global color registry.
897 * @param colKey The key
898 * @param colName The name of the color.
899 * @since 10824
900 */
901 public void registerColor(String colKey, String colName) {
902 if (!colKey.equals(colName)) {
903 colornames.put(colKey, colName);
904 }
905 }
906
907 /**
908 * Gets the default color that was registered with the preference
909 * @param colKey The color name
910 * @return The color
911 */
912 public synchronized Color getDefaultColor(String colKey) {
913 StringSetting col = Utils.cast(defaultsMap.get(COLOR_PREFIX+colKey), StringSetting.class);
914 String colStr = col == null ? null : col.getValue();
915 return colStr == null || colStr.isEmpty() ? null : ColorHelper.html2color(colStr);
916 }
917
918 /**
919 * Stores a color
920 * @param colKey The color name
921 * @param val The color
922 * @return true if the setting was modified
923 * @see ColorProperty#put(Color)
924 */
925 public synchronized boolean putColor(String colKey, Color val) {
926 return put(COLOR_PREFIX+colKey, val != null ? ColorHelper.color2html(val, true) : null);
927 }
928
929 /**
930 * Gets an integer preference
931 * @param key The preference key
932 * @param def The default value to use
933 * @return The integer
934 * @see IntegerProperty#get()
935 * @deprecated use {@link IPreferences#getInt(String, int)}
936 */
937 @Deprecated
938 public synchronized int getInteger(String key, int def) {
939 String v = get(key, Integer.toString(def));
940 if (v.isEmpty())
941 return def;
942
943 try {
944 return Integer.parseInt(v);
945 } catch (NumberFormatException e) {
946 // fall out
947 Logging.trace(e);
948 }
949 return def;
950 }
951
952 /**
953 * Gets an integer that may be specialized
954 * @param key The basic key
955 * @param specName The sub-key to append to the key
956 * @param def The default value
957 * @return The integer value or the default value if it could not be parsed
958 */
959 public synchronized int getInteger(String key, String specName, int def) {
960 String v = get(key+'.'+specName);
961 if (v.isEmpty())
962 v = get(key, Integer.toString(def));
963 if (v.isEmpty())
964 return def;
965
966 try {
967 return Integer.parseInt(v);
968 } catch (NumberFormatException e) {
969 // fall out
970 Logging.trace(e);
971 }
972 return def;
973 }
974
975 /**
976 * Gets a long preference
977 * @param key The preference key
978 * @param def The default value to use
979 * @return The long value or the default value if it could not be parsed
980 * @see LongProperty#get()
981 */
982 public synchronized long getLong(String key, long def) {
983 String v = get(key, Long.toString(def));
984 if (null == v)
985 return def;
986
987 try {
988 return Long.parseLong(v);
989 } catch (NumberFormatException e) {
990 // fall out
991 Logging.trace(e);
992 }
993 return def;
994 }
995
996 /**
997 * Get a list of values for a certain key
998 * @param key the identifier for the setting
999 * @param def the default value.
1000 * @return the corresponding value if the property has been set before, {@code def} otherwise
1001 * @deprecated use {@link IPreferences#getList(java.lang.String, java.util.List)}
1002 */
1003 @Deprecated
1004 public Collection<String> getCollection(String key, Collection<String> def) {
1005 return getSetting(key, ListSetting.create(def), ListSetting.class).getValue();
1006 }
1007
1008 /**
1009 * Get a list of values for a certain key
1010 * @param key the identifier for the setting
1011 * @return the corresponding value if the property has been set before, an empty collection otherwise.
1012 * @deprecated use {@link IPreferences#getList(java.lang.String)}
1013 */
1014 @Deprecated
1015 public Collection<String> getCollection(String key) {
1016 Collection<String> val = getList(key, null);
1017 return val == null ? Collections.<String>emptyList() : val;
1018 }
1019
1020 /**
1021 * Removes a value from a given String collection
1022 * @param key The preference key the collection is stored with
1023 * @param value The value that should be removed in the collection
1024 * @see #getList(String)
1025 */
1026 public synchronized void removeFromCollection(String key, String value) {
1027 List<String> a = new ArrayList<>(getList(key, Collections.<String>emptyList()));
1028 a.remove(value);
1029 putList(key, a);
1030 }
1031
1032 /**
1033 * Set a value for a certain setting. The changed setting is saved to the preference file immediately.
1034 * Due to caching mechanisms on modern operating systems and hardware, this shouldn't be a performance problem.
1035 * @param key the unique identifier for the setting
1036 * @param setting the value of the setting. In case it is null, the key-value entry will be removed.
1037 * @return {@code true}, if something has changed (i.e. value is different than before)
1038 */
1039 @Override
1040 public boolean putSetting(final String key, Setting<?> setting) {
1041 CheckParameterUtil.ensureParameterNotNull(key);
1042 if (setting != null && setting.getValue() == null)
1043 throw new IllegalArgumentException("setting argument must not have null value");
1044 Setting<?> settingOld;
1045 Setting<?> settingCopy = null;
1046 synchronized (this) {
1047 if (setting == null) {
1048 settingOld = settingsMap.remove(key);
1049 if (settingOld == null)
1050 return false;
1051 } else {
1052 settingOld = settingsMap.get(key);
1053 if (setting.equals(settingOld))
1054 return false;
1055 if (settingOld == null && setting.equals(defaultsMap.get(key)))
1056 return false;
1057 settingCopy = setting.copy();
1058 settingsMap.put(key, settingCopy);
1059 }
1060 if (saveOnPut) {
1061 try {
1062 save();
1063 } catch (IOException e) {
1064 Logging.log(Logging.LEVEL_WARN, tr("Failed to persist preferences to ''{0}''", getPreferenceFile().getAbsoluteFile()), e);
1065 }
1066 }
1067 }
1068 // Call outside of synchronized section in case some listener wait for other thread that wait for preference lock
1069 firePreferenceChanged(key, settingOld, settingCopy);
1070 return true;
1071 }
1072
1073 /**
1074 * Get a setting of any type
1075 * @param key The key for the setting
1076 * @param def The default value to use if it was not found
1077 * @return The setting
1078 */
1079 public synchronized Setting<?> getSetting(String key, Setting<?> def) {
1080 return getSetting(key, def, Setting.class);
1081 }
1082
1083 /**
1084 * Get settings value for a certain key and provide default a value.
1085 * @param <T> the setting type
1086 * @param key the identifier for the setting
1087 * @param def the default value. For each call of getSetting() with a given key, the default value must be the same.
1088 * <code>def</code> must not be null, but the value of <code>def</code> can be null.
1089 * @param klass the setting type (same as T)
1090 * @return the corresponding value if the property has been set before, {@code def} otherwise
1091 */
1092 @SuppressWarnings("unchecked")
1093 @Override
1094 public synchronized <T extends Setting<?>> T getSetting(String key, T def, Class<T> klass) {
1095 CheckParameterUtil.ensureParameterNotNull(key);
1096 CheckParameterUtil.ensureParameterNotNull(def);
1097 Setting<?> oldDef = defaultsMap.get(key);
1098 if (oldDef != null && oldDef.isNew() && oldDef.getValue() != null && def.getValue() != null && !def.equals(oldDef)) {
1099 Logging.info("Defaults for " + key + " differ: " + def + " != " + defaultsMap.get(key));
1100 }
1101 if (def.getValue() != null || oldDef == null) {
1102 Setting<?> defCopy = def.copy();
1103 defCopy.setTime(System.currentTimeMillis() / 1000);
1104 defCopy.setNew(true);
1105 defaultsMap.put(key, defCopy);
1106 }
1107 Setting<?> prop = settingsMap.get(key);
1108 if (klass.isInstance(prop)) {
1109 return (T) prop;
1110 } else {
1111 return def;
1112 }
1113 }
1114
1115 /**
1116 * Put a collection.
1117 * @param key key
1118 * @param value value
1119 * @return {@code true}, if something has changed (i.e. value is different than before)
1120 * @deprecated use {@link IPreferences#putList(java.lang.String, java.util.List)}
1121 */
1122 @Deprecated
1123 public boolean putCollection(String key, Collection<String> value) {
1124 return putSetting(key, value == null ? null : ListSetting.create(value));
1125 }
1126
1127 /**
1128 * Saves at most {@code maxsize} items of collection {@code val}.
1129 * @param key key
1130 * @param maxsize max number of items to save
1131 * @param val value
1132 * @return {@code true}, if something has changed (i.e. value is different than before)
1133 */
1134 public boolean putCollectionBounded(String key, int maxsize, Collection<String> val) {
1135 List<String> newCollection = new ArrayList<>(Math.min(maxsize, val.size()));
1136 for (String i : val) {
1137 if (newCollection.size() >= maxsize) {
1138 break;
1139 }
1140 newCollection.add(i);
1141 }
1142 return putList(key, newCollection);
1143 }
1144
1145 /**
1146 * Used to read a 2-dimensional array of strings from the preference file.
1147 * If not a single entry could be found, <code>def</code> is returned.
1148 * @param key preference key
1149 * @param def default array value
1150 * @return array value
1151 */
1152 @SuppressWarnings({ "unchecked", "rawtypes" })
1153 public synchronized Collection<Collection<String>> getArray(String key, Collection<Collection<String>> def) {
1154 ListListSetting val = getSetting(key, ListListSetting.create(def), ListListSetting.class);
1155 return (Collection) val.getValue();
1156 }
1157
1158 /**
1159 * Gets a collection of string collections for the given key
1160 * @param key The key
1161 * @return The collection of string collections or an empty collection as default
1162 * @deprecated use {@link IPreferences#getListOfLists(java.lang.String)}
1163 */
1164 @Deprecated
1165 public Collection<Collection<String>> getArray(String key) {
1166 Collection<Collection<String>> res = getArray(key, null);
1167 return res == null ? Collections.<Collection<String>>emptyList() : res;
1168 }
1169
1170 /**
1171 * Put an array.
1172 * @param key key
1173 * @param value value
1174 * @return {@code true}, if something has changed (i.e. value is different than before)
1175 * @deprecated use {@link IPreferences#putListOfLists(java.lang.String, java.util.List)}
1176 */
1177 @Deprecated
1178 public boolean putArray(String key, Collection<Collection<String>> value) {
1179 return putSetting(key, value == null ? null : ListListSetting.create(value));
1180 }
1181
1182 /**
1183 * Gets a collection of key/value maps.
1184 * @param key The key to search at
1185 * @param def The default value to use
1186 * @return The stored value or the default one if it could not be parsed
1187 * @deprecated use {@link IPreferences#getListOfMaps(java.lang.String, java.util.List)}
1188 */
1189 @Deprecated
1190 public Collection<Map<String, String>> getListOfStructs(String key, Collection<Map<String, String>> def) {
1191 return getSetting(key, new MapListSetting(def == null ? null : new ArrayList<>(def)), MapListSetting.class).getValue();
1192 }
1193
1194 /**
1195 * Stores a list of structs
1196 * @param key The key to store the list in
1197 * @param value A list of key/value maps
1198 * @return <code>true</code> if the value was changed
1199 * @see #getListOfMaps(String, Collection)
1200 * @deprecated use {@link IPreferences#putListOfMaps(java.lang.String, java.util.List)}
1201 */
1202 @Deprecated
1203 public boolean putListOfStructs(String key, Collection<Map<String, String>> value) {
1204 return putSetting(key, value == null ? null : new MapListSetting(new ArrayList<>(value)));
1205 }
1206
1207 /**
1208 * Annotation used for converting objects to String Maps and vice versa.
1209 * Indicates that a certain field should be considered in the conversion process. Otherwise it is ignored.
1210 *
1211 * @see #serializeStruct(java.lang.Object, java.lang.Class)
1212 * @see #deserializeStruct(java.util.Map, java.lang.Class)
1213 */
1214 @Retention(RetentionPolicy.RUNTIME) // keep annotation at runtime
1215 public @interface pref { }
1216
1217 /**
1218 * Annotation used for converting objects to String Maps.
1219 * Indicates that a certain field should be written to the map, even if the value is the same as the default value.
1220 *
1221 * @see #serializeStruct(java.lang.Object, java.lang.Class)
1222 */
1223 @Retention(RetentionPolicy.RUNTIME) // keep annotation at runtime
1224 public @interface writeExplicitly { }
1225
1226 /**
1227 * Get a list of hashes which are represented by a struct-like class.
1228 * Possible properties are given by fields of the class klass that have the @pref annotation.
1229 * Default constructor is used to initialize the struct objects, properties then override some of these default values.
1230 * @param <T> klass type
1231 * @param key main preference key
1232 * @param klass The struct class
1233 * @return a list of objects of type T or an empty list if nothing was found
1234 */
1235 public <T> List<T> getListOfStructs(String key, Class<T> klass) {
1236 return Optional.ofNullable(getListOfStructs(key, null, klass)).orElseGet(Collections::emptyList);
1237 }
1238
1239 /**
1240 * same as above, but returns def if nothing was found
1241 * @param <T> klass type
1242 * @param key main preference key
1243 * @param def default value
1244 * @param klass The struct class
1245 * @return a list of objects of type T or {@code def} if nothing was found
1246 */
1247 public <T> List<T> getListOfStructs(String key, Collection<T> def, Class<T> klass) {
1248 List<Map<String, String>> prop =
1249 getListOfMaps(key, def == null ? null : serializeListOfStructs(def, klass));
1250 if (prop == null)
1251 return def == null ? null : new ArrayList<>(def);
1252 return prop.stream().map(p -> deserializeStruct(p, klass)).collect(Collectors.toList());
1253 }
1254
1255 /**
1256 * Convenience method that saves a MapListSetting which is provided as a collection of objects.
1257 *
1258 * Each object is converted to a <code>Map&lt;String, String&gt;</code> using the fields with {@link pref} annotation.
1259 * The field name is the key and the value will be converted to a string.
1260 *
1261 * Considers only fields that have the @pref annotation.
1262 * In addition it does not write fields with null values. (Thus they are cleared)
1263 * Default values are given by the field values after default constructor has been called.
1264 * Fields equal to the default value are not written unless the field has the @writeExplicitly annotation.
1265 * @param <T> the class,
1266 * @param key main preference key
1267 * @param val the list that is supposed to be saved
1268 * @param klass The struct class
1269 * @return true if something has changed
1270 */
1271 public <T> boolean putListOfStructs(String key, Collection<T> val, Class<T> klass) {
1272 return putListOfMaps(key, serializeListOfStructs(val, klass));
1273 }
1274
1275 private static <T> List<Map<String, String>> serializeListOfStructs(Collection<T> l, Class<T> klass) {
1276 if (l == null)
1277 return null;
1278 List<Map<String, String>> vals = new ArrayList<>();
1279 for (T struct : l) {
1280 if (struct != null) {
1281 vals.add(serializeStruct(struct, klass));
1282 }
1283 }
1284 return vals;
1285 }
1286
1287 @SuppressWarnings("rawtypes")
1288 private static String mapToJson(Map map) {
1289 StringWriter stringWriter = new StringWriter();
1290 try (JsonWriter writer = Json.createWriter(stringWriter)) {
1291 JsonObjectBuilder object = Json.createObjectBuilder();
1292 for (Object o: map.entrySet()) {
1293 Entry e = (Entry) o;
1294 Object evalue = e.getValue();
1295 object.add(e.getKey().toString(), evalue.toString());
1296 }
1297 writer.writeObject(object.build());
1298 }
1299 return stringWriter.toString();
1300 }
1301
1302 @SuppressWarnings({ "rawtypes", "unchecked" })
1303 private static Map mapFromJson(String s) {
1304 Map ret = null;
1305 try (JsonReader reader = Json.createReader(new StringReader(s))) {
1306 JsonObject object = reader.readObject();
1307 ret = new HashMap(object.size());
1308 for (Entry<String, JsonValue> e: object.entrySet()) {
1309 JsonValue value = e.getValue();
1310 if (value instanceof JsonString) {
1311 // in some cases, when JsonValue.toString() is called, then additional quotation marks are left in value
1312 ret.put(e.getKey(), ((JsonString) value).getString());
1313 } else {
1314 ret.put(e.getKey(), e.getValue().toString());
1315 }
1316 }
1317 }
1318 return ret;
1319 }
1320
1321 @SuppressWarnings("rawtypes")
1322 private static String multiMapToJson(MultiMap map) {
1323 StringWriter stringWriter = new StringWriter();
1324 try (JsonWriter writer = Json.createWriter(stringWriter)) {
1325 JsonObjectBuilder object = Json.createObjectBuilder();
1326 for (Object o: map.entrySet()) {
1327 Entry e = (Entry) o;
1328 Set evalue = (Set) e.getValue();
1329 JsonArrayBuilder a = Json.createArrayBuilder();
1330 for (Object evo: evalue) {
1331 a.add(evo.toString());
1332 }
1333 object.add(e.getKey().toString(), a.build());
1334 }
1335 writer.writeObject(object.build());
1336 }
1337 return stringWriter.toString();
1338 }
1339
1340 @SuppressWarnings({ "rawtypes", "unchecked" })
1341 private static MultiMap multiMapFromJson(String s) {
1342 MultiMap ret = null;
1343 try (JsonReader reader = Json.createReader(new StringReader(s))) {
1344 JsonObject object = reader.readObject();
1345 ret = new MultiMap(object.size());
1346 for (Entry<String, JsonValue> e: object.entrySet()) {
1347 JsonValue value = e.getValue();
1348 if (value instanceof JsonArray) {
1349 for (JsonString js: ((JsonArray) value).getValuesAs(JsonString.class)) {
1350 ret.put(e.getKey(), js.getString());
1351 }
1352 } else if (value instanceof JsonString) {
1353 // in some cases, when JsonValue.toString() is called, then additional quotation marks are left in value
1354 ret.put(e.getKey(), ((JsonString) value).getString());
1355 } else {
1356 ret.put(e.getKey(), e.getValue().toString());
1357 }
1358 }
1359 }
1360 return ret;
1361 }
1362
1363 /**
1364 * Convert an object to a String Map, by using field names and values as map key and value.
1365 *
1366 * The field value is converted to a String.
1367 *
1368 * Only fields with annotation {@link pref} are taken into account.
1369 *
1370 * Fields will not be written to the map if the value is null or unchanged
1371 * (compared to an object created with the no-arg-constructor).
1372 * The {@link writeExplicitly} annotation overrides this behavior, i.e. the default value will also be written.
1373 *
1374 * @param <T> the class of the object <code>struct</code>
1375 * @param struct the object to be converted
1376 * @param klass the class T
1377 * @return the resulting map (same data content as <code>struct</code>)
1378 */
1379 public static <T> Map<String, String> serializeStruct(T struct, Class<T> klass) {
1380 T structPrototype;
1381 try {
1382 structPrototype = klass.getConstructor().newInstance();
1383 } catch (ReflectiveOperationException ex) {
1384 throw new IllegalArgumentException(ex);
1385 }
1386
1387 Map<String, String> hash = new LinkedHashMap<>();
1388 for (Field f : klass.getDeclaredFields()) {
1389 if (f.getAnnotation(pref.class) == null) {
1390 continue;
1391 }
1392 Utils.setObjectsAccessible(f);
1393 try {
1394 Object fieldValue = f.get(struct);
1395 Object defaultFieldValue = f.get(structPrototype);
1396 if (fieldValue != null && (f.getAnnotation(writeExplicitly.class) != null || !Objects.equals(fieldValue, defaultFieldValue))) {
1397 String key = f.getName().replace('_', '-');
1398 if (fieldValue instanceof Map) {
1399 hash.put(key, mapToJson((Map<?, ?>) fieldValue));
1400 } else if (fieldValue instanceof MultiMap) {
1401 hash.put(key, multiMapToJson((MultiMap<?, ?>) fieldValue));
1402 } else {
1403 hash.put(key, fieldValue.toString());
1404 }
1405 }
1406 } catch (IllegalAccessException ex) {
1407 throw new JosmRuntimeException(ex);
1408 }
1409 }
1410 return hash;
1411 }
1412
1413 /**
1414 * Converts a String-Map to an object of a certain class, by comparing map keys to field names of the class and assigning
1415 * map values to the corresponding fields.
1416 *
1417 * The map value (a String) is converted to the field type. Supported types are: boolean, Boolean, int, Integer, double,
1418 * Double, String, Map&lt;String, String&gt; and Map&lt;String, List&lt;String&gt;&gt;.
1419 *
1420 * Only fields with annotation {@link pref} are taken into account.
1421 * @param <T> the class
1422 * @param hash the string map with initial values
1423 * @param klass the class T
1424 * @return an object of class T, initialized as described above
1425 */
1426 public static <T> T deserializeStruct(Map<String, String> hash, Class<T> klass) {
1427 T struct = null;
1428 try {
1429 struct = klass.getConstructor().newInstance();
1430 } catch (ReflectiveOperationException ex) {
1431 throw new IllegalArgumentException(ex);
1432 }
1433 for (Entry<String, String> keyValue : hash.entrySet()) {
1434 Object value;
1435 Field f;
1436 try {
1437 f = klass.getDeclaredField(keyValue.getKey().replace('-', '_'));
1438 } catch (NoSuchFieldException ex) {
1439 Logging.trace(ex);
1440 continue;
1441 }
1442 if (f.getAnnotation(pref.class) == null) {
1443 continue;
1444 }
1445 Utils.setObjectsAccessible(f);
1446 if (f.getType() == Boolean.class || f.getType() == boolean.class) {
1447 value = Boolean.valueOf(keyValue.getValue());
1448 } else if (f.getType() == Integer.class || f.getType() == int.class) {
1449 try {
1450 value = Integer.valueOf(keyValue.getValue());
1451 } catch (NumberFormatException nfe) {
1452 continue;
1453 }
1454 } else if (f.getType() == Double.class || f.getType() == double.class) {
1455 try {
1456 value = Double.valueOf(keyValue.getValue());
1457 } catch (NumberFormatException nfe) {
1458 continue;
1459 }
1460 } else if (f.getType() == String.class) {
1461 value = keyValue.getValue();
1462 } else if (f.getType().isAssignableFrom(Map.class)) {
1463 value = mapFromJson(keyValue.getValue());
1464 } else if (f.getType().isAssignableFrom(MultiMap.class)) {
1465 value = multiMapFromJson(keyValue.getValue());
1466 } else
1467 throw new JosmRuntimeException("unsupported preference primitive type");
1468
1469 try {
1470 f.set(struct, value);
1471 } catch (IllegalArgumentException ex) {
1472 throw new AssertionError(ex);
1473 } catch (IllegalAccessException ex) {
1474 throw new JosmRuntimeException(ex);
1475 }
1476 }
1477 return struct;
1478 }
1479
1480 /**
1481 * Gets a map of all settings that are currently stored
1482 * @return The settings
1483 */
1484 public Map<String, Setting<?>> getAllSettings() {
1485 return new TreeMap<>(settingsMap);
1486 }
1487
1488 /**
1489 * Gets a map of all currently known defaults
1490 * @return The map (key/setting)
1491 */
1492 public Map<String, Setting<?>> getAllDefaults() {
1493 return new TreeMap<>(defaultsMap);
1494 }
1495
1496 /**
1497 * Updates system properties with the current values in the preferences.
1498 */
1499 public void updateSystemProperties() {
1500 if ("true".equals(get("prefer.ipv6", "auto")) && !"true".equals(Utils.updateSystemProperty("java.net.preferIPv6Addresses", "true"))) {
1501 // never set this to false, only true!
1502 Logging.info(tr("Try enabling IPv6 network, prefering IPv6 over IPv4 (only works on early startup)."));
1503 }
1504 Utils.updateSystemProperty("http.agent", Version.getInstance().getAgentString());
1505 Utils.updateSystemProperty("user.language", get("language"));
1506 // Workaround to fix a Java bug. This ugly hack comes from Sun bug database: https://bugs.openjdk.java.net/browse/JDK-6292739
1507 // Force AWT toolkit to update its internal preferences (fix #6345).
1508 // Does not work anymore with Java 9, to remove with Java 9 migration
1509 if (Utils.getJavaVersion() < 9 && !GraphicsEnvironment.isHeadless()) {
1510 try {
1511 Field field = Toolkit.class.getDeclaredField("resources");
1512 Utils.setObjectsAccessible(field);
1513 field.set(null, ResourceBundle.getBundle("sun.awt.resources.awt"));
1514 } catch (ReflectiveOperationException | RuntimeException e) { // NOPMD
1515 // Catch RuntimeException in order to catch InaccessibleObjectException, new in Java 9
1516 Logging.warn(e);
1517 }
1518 }
1519 // Possibility to disable SNI (not by default) in case of misconfigured https servers
1520 // See #9875 + http://stackoverflow.com/a/14884941/2257172
1521 // then https://josm.openstreetmap.de/ticket/12152#comment:5 for details
1522 if (getBoolean("jdk.tls.disableSNIExtension", false)) {
1523 Utils.updateSystemProperty("jsse.enableSNIExtension", "false");
1524 }
1525 }
1526
1527 /**
1528 * Replies the collection of plugin site URLs from where plugin lists can be downloaded.
1529 * @return the collection of plugin site URLs
1530 * @see #getOnlinePluginSites
1531 */
1532 public Collection<String> getPluginSites() {
1533 return getList("pluginmanager.sites", Collections.singletonList(Main.getJOSMWebsite()+"/pluginicons%<?plugins=>"));
1534 }
1535
1536 /**
1537 * Returns the list of plugin sites available according to offline mode settings.
1538 * @return the list of available plugin sites
1539 * @since 8471
1540 */
1541 public Collection<String> getOnlinePluginSites() {
1542 Collection<String> pluginSites = new ArrayList<>(getPluginSites());
1543 for (Iterator<String> it = pluginSites.iterator(); it.hasNext();) {
1544 try {
1545 OnlineResource.JOSM_WEBSITE.checkOfflineAccess(it.next(), Main.getJOSMWebsite());
1546 } catch (OfflineAccessException ex) {
1547 Logging.log(Logging.LEVEL_WARN, ex);
1548 it.remove();
1549 }
1550 }
1551 return pluginSites;
1552 }
1553
1554 /**
1555 * Sets the collection of plugin site URLs.
1556 *
1557 * @param sites the site URLs
1558 */
1559 public void setPluginSites(Collection<String> sites) {
1560 putList("pluginmanager.sites", new ArrayList<>(sites));
1561 }
1562
1563 /**
1564 * Returns XML describing these preferences.
1565 * @param nopass if password must be excluded
1566 * @return XML
1567 */
1568 public String toXML(boolean nopass) {
1569 return toXML(settingsMap.entrySet(), nopass, false);
1570 }
1571
1572 /**
1573 * Returns XML describing the given preferences.
1574 * @param settings preferences settings
1575 * @param nopass if password must be excluded
1576 * @param defaults true, if default values are converted to XML, false for
1577 * regular preferences
1578 * @return XML
1579 */
1580 public String toXML(Collection<Entry<String, Setting<?>>> settings, boolean nopass, boolean defaults) {
1581 try (
1582 StringWriter sw = new StringWriter();
1583 PreferencesWriter prefWriter = new PreferencesWriter(new PrintWriter(sw), nopass, defaults)
1584 ) {
1585 prefWriter.write(settings);
1586 sw.flush();
1587 return sw.toString();
1588 } catch (IOException e) {
1589 Logging.error(e);
1590 return null;
1591 }
1592 }
1593
1594 /**
1595 * Removes obsolete preference settings. If you throw out a once-used preference
1596 * setting, add it to the list here with an expiry date (written as comment). If you
1597 * see something with an expiry date in the past, remove it from the list.
1598 * @param loadedVersion JOSM version when the preferences file was written
1599 */
1600 private void removeObsolete(int loadedVersion) {
1601 // drop in March 2017
1602 removeUrlFromEntries(loadedVersion, 10063,
1603 "validator.org.openstreetmap.josm.data.validation.tests.MapCSSTagChecker.entries",
1604 "resource://data/validator/power.mapcss");
1605 // drop in March 2017
1606 if (loadedVersion < 11058) {
1607 migrateOldColorKeys();
1608 }
1609 // drop in September 2017
1610 if (loadedVersion < 11424) {
1611 addNewerDefaultEntry(
1612 "validator.org.openstreetmap.josm.data.validation.tests.MapCSSTagChecker.entries",
1613 "resource://data/validator/territories.mapcss");
1614 }
1615
1616 for (String key : OBSOLETE_PREF_KEYS) {
1617 if (settingsMap.containsKey(key)) {
1618 settingsMap.remove(key);
1619 Logging.info(tr("Preference setting {0} has been removed since it is no longer used.", key));
1620 }
1621 }
1622 }
1623
1624 private void migrateOldColorKeys() {
1625 settingsMap.keySet().stream()
1626 .filter(key -> key.startsWith(COLOR_PREFIX))
1627 .flatMap(this::searchOldColorKey)
1628 .collect(Collectors.toList()) // to avoid ConcurrentModificationException
1629 .forEach(entry -> {
1630 final String oldKey = entry.getKey();
1631 final String newKey = entry.getValue();
1632 Logging.info("Migrating old color key {0} => {1}", oldKey, newKey);
1633 put(newKey, get(oldKey));
1634 put(oldKey, null);
1635 });
1636 }
1637
1638 private Stream<AbstractMap.SimpleImmutableEntry<String, String>> searchOldColorKey(String key) {
1639 final String newKey = ColorProperty.getColorKey(key.substring(COLOR_PREFIX.length()));
1640 return key.equals(newKey) || settingsMap.containsKey(newKey)
1641 ? Stream.empty()
1642 : Stream.of(new AbstractMap.SimpleImmutableEntry<>(key, newKey));
1643 }
1644
1645 private void removeUrlFromEntries(int loadedVersion, int versionMax, String key, String urlPart) {
1646 if (loadedVersion < versionMax) {
1647 Setting<?> setting = settingsMap.get(key);
1648 if (setting instanceof MapListSetting) {
1649 List<Map<String, String>> l = new LinkedList<>();
1650 boolean modified = false;
1651 for (Map<String, String> map: ((MapListSetting) setting).getValue()) {
1652 String url = map.get("url");
1653 if (url != null && url.contains(urlPart)) {
1654 modified = true;
1655 } else {
1656 l.add(map);
1657 }
1658 }
1659 if (modified) {
1660 putListOfMaps(key, l);
1661 }
1662 }
1663 }
1664 }
1665
1666 private void addNewerDefaultEntry(String key, final String url) {
1667 Setting<?> setting = settingsMap.get(key);
1668 if (setting instanceof MapListSetting) {
1669 List<Map<String, String>> l = new ArrayList<>(((MapListSetting) setting).getValue());
1670 if (l.stream().noneMatch(x -> x.containsValue(url))) {
1671 ValidatorPrefHelper helper = ValidatorPrefHelper.INSTANCE;
1672 Optional<ExtendedSourceEntry> val = helper.getDefault().stream().filter(x -> url.equals(x.url)).findFirst();
1673 if (val.isPresent()) {
1674 l.add(helper.serialize(val.get()));
1675 }
1676 putListOfMaps(key, l);
1677 }
1678 }
1679 }
1680
1681 /**
1682 * Enables or not the preferences file auto-save mechanism (save each time a setting is changed).
1683 * This behaviour is enabled by default.
1684 * @param enable if {@code true}, makes JOSM save preferences file each time a setting is changed
1685 * @since 7085
1686 */
1687 public final void enableSaveOnPut(boolean enable) {
1688 synchronized (this) {
1689 saveOnPut = enable;
1690 }
1691 }
1692}
Note: See TracBrowser for help on using the repository browser.