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

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

SonarQube - fix minor code issues

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