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

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

see #8465 - use String switch/case where applicable

  • Property svn:eol-style set to native
File size: 60.9 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.data;
3
4import static org.openstreetmap.josm.tools.I18n.tr;
5
6import java.awt.Color;
7import java.awt.Toolkit;
8import java.io.BufferedReader;
9import java.io.File;
10import java.io.FileInputStream;
11import java.io.FileOutputStream;
12import java.io.IOException;
13import java.io.InputStreamReader;
14import java.io.OutputStreamWriter;
15import java.io.PrintWriter;
16import java.io.Reader;
17import java.lang.annotation.Retention;
18import java.lang.annotation.RetentionPolicy;
19import java.lang.reflect.Field;
20import java.util.ArrayList;
21import java.util.Collection;
22import java.util.Collections;
23import java.util.Iterator;
24import java.util.LinkedHashMap;
25import java.util.LinkedList;
26import java.util.List;
27import java.util.Map;
28import java.util.Map.Entry;
29import java.util.ResourceBundle;
30import java.util.SortedMap;
31import java.util.TreeMap;
32import java.util.concurrent.CopyOnWriteArrayList;
33import java.util.regex.Matcher;
34import java.util.regex.Pattern;
35
36import javax.swing.JOptionPane;
37import javax.swing.UIManager;
38import javax.xml.XMLConstants;
39import javax.xml.stream.XMLInputFactory;
40import javax.xml.stream.XMLStreamConstants;
41import javax.xml.stream.XMLStreamException;
42import javax.xml.stream.XMLStreamReader;
43import javax.xml.transform.stream.StreamSource;
44import javax.xml.validation.Schema;
45import javax.xml.validation.SchemaFactory;
46import javax.xml.validation.Validator;
47
48import org.openstreetmap.josm.Main;
49import org.openstreetmap.josm.data.preferences.ColorProperty;
50import org.openstreetmap.josm.io.MirroredInputStream;
51import org.openstreetmap.josm.io.XmlWriter;
52import org.openstreetmap.josm.tools.CheckParameterUtil;
53import org.openstreetmap.josm.tools.ColorHelper;
54import org.openstreetmap.josm.tools.I18n;
55import org.openstreetmap.josm.tools.Utils;
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 */
78public class Preferences {
79 /**
80 * Internal storage for the preference directory.
81 * Do not access this variable directly!
82 * @see #getPreferencesDirFile()
83 */
84 private File preferencesDirFile = null;
85 /**
86 * Internal storage for the cache directory.
87 */
88 private File cacheDirFile = null;
89
90 /**
91 * Map the setting name to the current value of the setting.
92 * The map must not contain null as key or value. The mapped setting objects
93 * must not have a null value.
94 */
95 protected final SortedMap<String, Setting> settingsMap = new TreeMap<>();
96 /**
97 * Map the setting name to the default value of the setting.
98 * The map must not contain null as key or value. The value of the mapped
99 * setting objects can be null.
100 */
101 protected final SortedMap<String, Setting> defaultsMap = new TreeMap<>();
102 // maps color keys to human readable color name
103 protected final SortedMap<String, String> colornames = new TreeMap<>();
104
105 /**
106 * Interface for a preference value.
107 *
108 * Implementations must provide a proper <code>equals</code> method.
109 *
110 * @param <T> the data type for the value
111 */
112 public interface Setting<T> {
113 /**
114 * Returns the value of this setting.
115 *
116 * @return the value of this setting
117 */
118 T getValue();
119
120 /**
121 * Check if the value of this Setting object is equal to the given value.
122 * @param otherVal the other value
123 * @return true if the values are equal
124 */
125 boolean equalVal(T otherVal);
126
127 /**
128 * Clone the current object.
129 * @return an identical copy of the current object
130 */
131 Setting<T> copy();
132
133 /**
134 * Enable usage of the visitor pattern.
135 *
136 * @param visitor the visitor
137 */
138 void visit(SettingVisitor visitor);
139
140 /**
141 * Returns a setting whose value is null.
142 *
143 * Cannot be static, because there is no static inheritance.
144 * @return a Setting object that isn't null itself, but returns null
145 * for {@link #getValue()}
146 */
147 Setting<T> getNullInstance();
148 }
149
150 /**
151 * Base abstract class of all settings, holding the setting value.
152 *
153 * @param <T> The setting type
154 */
155 public abstract static class AbstractSetting<T> implements Setting<T> {
156 protected final T value;
157 /**
158 * Constructs a new {@code AbstractSetting} with the given value
159 * @param value The setting value
160 */
161 public AbstractSetting(T value) {
162 this.value = value;
163 }
164 @Override public T getValue() {
165 return value;
166 }
167 @Override public String toString() {
168 return value != null ? value.toString() : "null";
169 }
170 }
171
172 /**
173 * Setting containing a {@link String} value.
174 */
175 public static class StringSetting extends AbstractSetting<String> {
176 /**
177 * Constructs a new {@code StringSetting} with the given value
178 * @param value The setting value
179 */
180 public StringSetting(String value) {
181 super(value);
182 }
183 @Override public boolean equalVal(String otherVal) {
184 if (value == null) return otherVal == null;
185 return value.equals(otherVal);
186 }
187 @Override public StringSetting copy() {
188 return new StringSetting(value);
189 }
190 @Override public void visit(SettingVisitor visitor) {
191 visitor.visit(this);
192 }
193 @Override public StringSetting getNullInstance() {
194 return new StringSetting(null);
195 }
196 @Override
197 public boolean equals(Object other) {
198 if (!(other instanceof StringSetting)) return false;
199 return equalVal(((StringSetting) other).getValue());
200 }
201 }
202
203 /**
204 * Setting containing a {@link List} of {@link String} values.
205 */
206 public static class ListSetting extends AbstractSetting<List<String>> {
207 /**
208 * Constructs a new {@code ListSetting} with the given value
209 * @param value The setting value
210 */
211 public ListSetting(List<String> value) {
212 super(value);
213 consistencyTest();
214 }
215 /**
216 * Convenience factory method.
217 * @param value the value
218 * @return a corresponding ListSetting object
219 */
220 public static ListSetting create(Collection<String> value) {
221 return new ListSetting(value == null ? null : Collections.unmodifiableList(new ArrayList<>(value)));
222 }
223 @Override public boolean equalVal(List<String> otherVal) {
224 return equalCollection(value, otherVal);
225 }
226 public static boolean equalCollection(Collection<String> a, Collection<String> b) {
227 if (a == null) return b == null;
228 if (b == null) return false;
229 if (a.size() != b.size()) return false;
230 Iterator<String> itA = a.iterator();
231 Iterator<String> itB = b.iterator();
232 while (itA.hasNext()) {
233 String aStr = itA.next();
234 String bStr = itB.next();
235 if (!Utils.equal(aStr,bStr)) return false;
236 }
237 return true;
238 }
239 @Override public ListSetting copy() {
240 return ListSetting.create(value);
241 }
242 private void consistencyTest() {
243 if (value != null && value.contains(null))
244 throw new RuntimeException("Error: Null as list element in preference setting");
245 }
246 @Override public void visit(SettingVisitor visitor) {
247 visitor.visit(this);
248 }
249 @Override public ListSetting getNullInstance() {
250 return new ListSetting(null);
251 }
252 @Override
253 public boolean equals(Object other) {
254 if (!(other instanceof ListSetting)) return false;
255 return equalVal(((ListSetting) other).getValue());
256 }
257 }
258
259 /**
260 * Setting containing a {@link List} of {@code List}s of {@link String} values.
261 */
262 public static class ListListSetting extends AbstractSetting<List<List<String>>> {
263 /**
264 * Constructs a new {@code ListListSetting} with the given value
265 * @param value The setting value
266 */
267 public ListListSetting(List<List<String>> value) {
268 super(value);
269 consistencyTest();
270 }
271 /**
272 * Convenience factory method.
273 * @param value the value
274 * @return a corresponding ListListSetting object
275 */
276 public static ListListSetting create(Collection<Collection<String>> value) {
277 if (value != null) {
278 List<List<String>> valueList = new ArrayList<>(value.size());
279 for (Collection<String> lst : value) {
280 valueList.add(new ArrayList<>(lst));
281 }
282 return new ListListSetting(valueList);
283 }
284 return new ListListSetting(null);
285 }
286 @Override public boolean equalVal(List<List<String>> otherVal) {
287 if (value == null) return otherVal == null;
288 if (otherVal == null) return false;
289 if (value.size() != otherVal.size()) return false;
290 Iterator<List<String>> itA = value.iterator();
291 Iterator<List<String>> itB = otherVal.iterator();
292 while (itA.hasNext()) {
293 if (!ListSetting.equalCollection(itA.next(), itB.next())) return false;
294 }
295 return true;
296 }
297 @Override public ListListSetting copy() {
298 if (value == null) return new ListListSetting(null);
299
300 List<List<String>> copy = new ArrayList<>(value.size());
301 for (Collection<String> lst : value) {
302 List<String> lstCopy = new ArrayList<>(lst);
303 copy.add(Collections.unmodifiableList(lstCopy));
304 }
305 return new ListListSetting(Collections.unmodifiableList(copy));
306 }
307 private void consistencyTest() {
308 if (value == null) return;
309 if (value.contains(null)) throw new RuntimeException("Error: Null as list element in preference setting");
310 for (Collection<String> lst : value) {
311 if (lst.contains(null)) throw new RuntimeException("Error: Null as inner list element in preference setting");
312 }
313 }
314 @Override public void visit(SettingVisitor visitor) {
315 visitor.visit(this);
316 }
317 @Override public ListListSetting getNullInstance() {
318 return new ListListSetting(null);
319 }
320 @Override
321 public boolean equals(Object other) {
322 if (!(other instanceof ListListSetting)) return false;
323 return equalVal(((ListListSetting) other).getValue());
324 }
325 }
326
327 /**
328 * Setting containing a {@link List} of {@link Map}s of {@link String} values.
329 */
330 public static class MapListSetting extends AbstractSetting<List<Map<String, String>>> {
331 /**
332 * Constructs a new {@code MapListSetting} with the given value
333 * @param value The setting value
334 */
335 public MapListSetting(List<Map<String, String>> value) {
336 super(value);
337 consistencyTest();
338 }
339 @Override public boolean equalVal(List<Map<String, String>> otherVal) {
340 if (value == null) return otherVal == null;
341 if (otherVal == null) return false;
342 if (value.size() != otherVal.size()) return false;
343 Iterator<Map<String, String>> itA = value.iterator();
344 Iterator<Map<String, String>> itB = otherVal.iterator();
345 while (itA.hasNext()) {
346 if (!equalMap(itA.next(), itB.next())) return false;
347 }
348 return true;
349 }
350 private static boolean equalMap(Map<String, String> a, Map<String, String> b) {
351 if (a == null) return b == null;
352 if (b == null) return false;
353 if (a.size() != b.size()) return false;
354 for (Entry<String, String> e : a.entrySet()) {
355 if (!Utils.equal(e.getValue(), b.get(e.getKey()))) return false;
356 }
357 return true;
358 }
359 @Override public MapListSetting copy() {
360 if (value == null) return new MapListSetting(null);
361 List<Map<String, String>> copy = new ArrayList<>(value.size());
362 for (Map<String, String> map : value) {
363 Map<String, String> mapCopy = new LinkedHashMap<>(map);
364 copy.add(Collections.unmodifiableMap(mapCopy));
365 }
366 return new MapListSetting(Collections.unmodifiableList(copy));
367 }
368 private void consistencyTest() {
369 if (value == null) return;
370 if (value.contains(null)) throw new RuntimeException("Error: Null as list element in preference setting");
371 for (Map<String, String> map : value) {
372 if (map.keySet().contains(null)) throw new RuntimeException("Error: Null as map key in preference setting");
373 if (map.values().contains(null)) throw new RuntimeException("Error: Null as map value in preference setting");
374 }
375 }
376 @Override public void visit(SettingVisitor visitor) {
377 visitor.visit(this);
378 }
379 @Override public MapListSetting getNullInstance() {
380 return new MapListSetting(null);
381 }
382 @Override
383 public boolean equals(Object other) {
384 if (!(other instanceof MapListSetting)) return false;
385 return equalVal(((MapListSetting) other).getValue());
386 }
387 }
388
389 public interface SettingVisitor {
390 void visit(StringSetting setting);
391 void visit(ListSetting value);
392 void visit(ListListSetting value);
393 void visit(MapListSetting value);
394 }
395
396 public interface PreferenceChangeEvent {
397 String getKey();
398 Setting getOldValue();
399 Setting getNewValue();
400 }
401
402 public interface PreferenceChangedListener {
403 void preferenceChanged(PreferenceChangeEvent e);
404 }
405
406 private static class DefaultPreferenceChangeEvent implements PreferenceChangeEvent {
407 private final String key;
408 private final Setting oldValue;
409 private final Setting newValue;
410
411 public DefaultPreferenceChangeEvent(String key, Setting oldValue, Setting newValue) {
412 this.key = key;
413 this.oldValue = oldValue;
414 this.newValue = newValue;
415 }
416
417 @Override
418 public String getKey() {
419 return key;
420 }
421 @Override
422 public Setting getOldValue() {
423 return oldValue;
424 }
425 @Override
426 public Setting getNewValue() {
427 return newValue;
428 }
429 }
430
431 public interface ColorKey {
432 String getColorName();
433 String getSpecialName();
434 Color getDefaultValue();
435 }
436
437 private final CopyOnWriteArrayList<PreferenceChangedListener> listeners = new CopyOnWriteArrayList<>();
438
439 public void addPreferenceChangeListener(PreferenceChangedListener listener) {
440 if (listener != null) {
441 listeners.addIfAbsent(listener);
442 }
443 }
444
445 public void removePreferenceChangeListener(PreferenceChangedListener listener) {
446 listeners.remove(listener);
447 }
448
449 protected void firePreferenceChanged(String key, Setting oldValue, Setting newValue) {
450 PreferenceChangeEvent evt = new DefaultPreferenceChangeEvent(key, oldValue, newValue);
451 for (PreferenceChangedListener l : listeners) {
452 l.preferenceChanged(evt);
453 }
454 }
455
456 /**
457 * Returns the location of the user defined preferences directory
458 * @return The location of the user defined preferences directory
459 */
460 public String getPreferencesDir() {
461 final String path = getPreferencesDirFile().getPath();
462 if (path.endsWith(File.separator))
463 return path;
464 return path + File.separator;
465 }
466
467 /**
468 * Returns the user defined preferences directory
469 * @return The user defined preferences directory
470 */
471 public File getPreferencesDirFile() {
472 if (preferencesDirFile != null)
473 return preferencesDirFile;
474 String path;
475 path = System.getProperty("josm.home");
476 if (path != null) {
477 preferencesDirFile = new File(path).getAbsoluteFile();
478 } else {
479 path = System.getenv("APPDATA");
480 if (path != null) {
481 preferencesDirFile = new File(path, "JOSM");
482 } else {
483 preferencesDirFile = new File(System.getProperty("user.home"), ".josm");
484 }
485 }
486 return preferencesDirFile;
487 }
488
489 /**
490 * Returns the user preferences file
491 * @return The user preferences file
492 */
493 public File getPreferenceFile() {
494 return new File(getPreferencesDirFile(), "preferences.xml");
495 }
496
497 /**
498 * Returns the user plugin directory
499 * @return The user plugin directory
500 */
501 public File getPluginsDirectory() {
502 return new File(getPreferencesDirFile(), "plugins");
503 }
504
505 /**
506 * Get the directory where cached content of any kind should be stored.
507 *
508 * If the directory doesn't exist on the file system, it will be created
509 * by this method.
510 *
511 * @return the cache directory
512 */
513 public File getCacheDirectory() {
514 if (cacheDirFile != null)
515 return cacheDirFile;
516 String path = System.getProperty("josm.cache");
517 if (path != null) {
518 cacheDirFile = new File(path).getAbsoluteFile();
519 } else {
520 path = get("cache.folder", null);
521 if (path != null) {
522 cacheDirFile = new File(path);
523 } else {
524 cacheDirFile = new File(getPreferencesDirFile(), "cache");
525 }
526 }
527 if (!cacheDirFile.exists() && !cacheDirFile.mkdirs()) {
528 Main.warn(tr("Failed to create missing cache directory: {0}", cacheDirFile.getAbsoluteFile()));
529 JOptionPane.showMessageDialog(
530 Main.parent,
531 tr("<html>Failed to create missing cache directory: {0}</html>", cacheDirFile.getAbsoluteFile()),
532 tr("Error"),
533 JOptionPane.ERROR_MESSAGE
534 );
535 }
536 return cacheDirFile;
537 }
538
539 /**
540 * @return A list of all existing directories where resources could be stored.
541 */
542 public Collection<String> getAllPossiblePreferenceDirs() {
543 LinkedList<String> locations = new LinkedList<>();
544 locations.add(getPreferencesDir());
545 String s;
546 if ((s = System.getenv("JOSM_RESOURCES")) != null) {
547 if (!s.endsWith(File.separator)) {
548 s = s + File.separator;
549 }
550 locations.add(s);
551 }
552 if ((s = System.getProperty("josm.resources")) != null) {
553 if (!s.endsWith(File.separator)) {
554 s = s + File.separator;
555 }
556 locations.add(s);
557 }
558 String appdata = System.getenv("APPDATA");
559 if (System.getenv("ALLUSERSPROFILE") != null && appdata != null
560 && appdata.lastIndexOf(File.separator) != -1) {
561 appdata = appdata.substring(appdata.lastIndexOf(File.separator));
562 locations.add(new File(new File(System.getenv("ALLUSERSPROFILE"),
563 appdata), "JOSM").getPath());
564 }
565 locations.add("/usr/local/share/josm/");
566 locations.add("/usr/local/lib/josm/");
567 locations.add("/usr/share/josm/");
568 locations.add("/usr/lib/josm/");
569 return locations;
570 }
571
572 /**
573 * Get settings value for a certain key.
574 * @param key the identifier for the setting
575 * @return "" if there is nothing set for the preference key,
576 * the corresponding value otherwise. The result is not null.
577 */
578 public synchronized String get(final String key) {
579 String value = get(key, null);
580 return value == null ? "" : value;
581 }
582
583 /**
584 * Get settings value for a certain key and provide default a value.
585 * @param key the identifier for the setting
586 * @param def the default value. For each call of get() with a given key, the
587 * default value must be the same.
588 * @return the corresponding value if the property has been set before,
589 * def otherwise
590 */
591 public synchronized String get(final String key, final String def) {
592 return getSetting(key, new StringSetting(def), StringSetting.class).getValue();
593 }
594
595 public synchronized Map<String, String> getAllPrefix(final String prefix) {
596 final Map<String,String> all = new TreeMap<>();
597 for (final Entry<String,Setting> e : settingsMap.entrySet()) {
598 if (e.getKey().startsWith(prefix) && (e.getValue() instanceof StringSetting)) {
599 all.put(e.getKey(), ((StringSetting) e.getValue()).getValue());
600 }
601 }
602 return all;
603 }
604
605 public synchronized List<String> getAllPrefixCollectionKeys(final String prefix) {
606 final List<String> all = new LinkedList<>();
607 for (Map.Entry<String, Setting> entry : settingsMap.entrySet()) {
608 if (entry.getKey().startsWith(prefix) && entry.getValue() instanceof ListSetting) {
609 all.add(entry.getKey());
610 }
611 }
612 return all;
613 }
614
615 public synchronized Map<String, String> getAllColors() {
616 final Map<String,String> all = new TreeMap<>();
617 for (final Entry<String,Setting> e : defaultsMap.entrySet()) {
618 if (e.getKey().startsWith("color.") && e.getValue() instanceof StringSetting) {
619 StringSetting d = (StringSetting) e.getValue();
620 if (d.getValue() != null) {
621 all.put(e.getKey().substring(6), d.getValue());
622 }
623 }
624 }
625 for (final Entry<String,Setting> e : settingsMap.entrySet()) {
626 if (e.getKey().startsWith("color.") && (e.getValue() instanceof StringSetting)) {
627 all.put(e.getKey().substring(6), ((StringSetting) e.getValue()).getValue());
628 }
629 }
630 return all;
631 }
632
633 public synchronized boolean getBoolean(final String key) {
634 String s = get(key, null);
635 return s == null ? false : Boolean.parseBoolean(s);
636 }
637
638 public synchronized boolean getBoolean(final String key, final boolean def) {
639 return Boolean.parseBoolean(get(key, Boolean.toString(def)));
640 }
641
642 public synchronized boolean getBoolean(final String key, final String specName, final boolean def) {
643 boolean generic = getBoolean(key, def);
644 String skey = key+"."+specName;
645 Setting prop = settingsMap.get(skey);
646 if (prop instanceof StringSetting)
647 return Boolean.parseBoolean(((StringSetting)prop).getValue());
648 else
649 return generic;
650 }
651
652 /**
653 * Set a value for a certain setting.
654 * @param key the unique identifier for the setting
655 * @param value the value of the setting. Can be null or "" which both removes
656 * the key-value entry.
657 * @return true, if something has changed (i.e. value is different than before)
658 */
659 public boolean put(final String key, String value) {
660 if(value != null && value.length() == 0) {
661 value = null;
662 }
663 return putSetting(key, value == null ? null : new StringSetting(value));
664 }
665
666 public boolean put(final String key, final boolean value) {
667 return put(key, Boolean.toString(value));
668 }
669
670 public boolean putInteger(final String key, final Integer value) {
671 return put(key, Integer.toString(value));
672 }
673
674 public boolean putDouble(final String key, final Double value) {
675 return put(key, Double.toString(value));
676 }
677
678 public boolean putLong(final String key, final Long value) {
679 return put(key, Long.toString(value));
680 }
681
682 /**
683 * Called after every put. In case of a problem, do nothing but output the error
684 * in log.
685 */
686 public void save() throws IOException {
687 /* currently unused, but may help to fix configuration issues in future */
688 putInteger("josm.version", Version.getInstance().getVersion());
689
690 updateSystemProperties();
691 if(Main.applet)
692 return;
693
694 File prefFile = getPreferenceFile();
695 File backupFile = new File(prefFile + "_backup");
696
697 // Backup old preferences if there are old preferences
698 if (prefFile.exists()) {
699 Utils.copyFile(prefFile, backupFile);
700 }
701
702 final PrintWriter out = new PrintWriter(new OutputStreamWriter(
703 new FileOutputStream(prefFile + "_tmp"), Utils.UTF_8), false);
704 out.print(toXML(false));
705 Utils.close(out);
706
707 File tmpFile = new File(prefFile + "_tmp");
708 Utils.copyFile(tmpFile, prefFile);
709 tmpFile.delete();
710
711 setCorrectPermissions(prefFile);
712 setCorrectPermissions(backupFile);
713 }
714
715
716 private void setCorrectPermissions(File file) {
717 file.setReadable(false, false);
718 file.setWritable(false, false);
719 file.setExecutable(false, false);
720 file.setReadable(true, true);
721 file.setWritable(true, true);
722 }
723
724 public void load() throws Exception {
725 settingsMap.clear();
726 if (!Main.applet) {
727 File pref = getPreferenceFile();
728 BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(pref), Utils.UTF_8));
729 try {
730 validateXML(in);
731 Utils.close(in);
732 in = new BufferedReader(new InputStreamReader(new FileInputStream(pref), Utils.UTF_8));
733 fromXML(in);
734 } finally {
735 Utils.close(in);
736 }
737 }
738 updateSystemProperties();
739 removeObsolete();
740 }
741
742 public void init(boolean reset){
743 if(Main.applet)
744 return;
745 // get the preferences.
746 File prefDir = getPreferencesDirFile();
747 if (prefDir.exists()) {
748 if(!prefDir.isDirectory()) {
749 Main.warn(tr("Failed to initialize preferences. Preference directory ''{0}'' is not a directory.", prefDir.getAbsoluteFile()));
750 JOptionPane.showMessageDialog(
751 Main.parent,
752 tr("<html>Failed to initialize preferences.<br>Preference directory ''{0}'' is not a directory.</html>", prefDir.getAbsoluteFile()),
753 tr("Error"),
754 JOptionPane.ERROR_MESSAGE
755 );
756 return;
757 }
758 } else {
759 if (! prefDir.mkdirs()) {
760 Main.warn(tr("Failed to initialize preferences. Failed to create missing preference directory: {0}", prefDir.getAbsoluteFile()));
761 JOptionPane.showMessageDialog(
762 Main.parent,
763 tr("<html>Failed to initialize preferences.<br>Failed to create missing preference directory: {0}</html>",prefDir.getAbsoluteFile()),
764 tr("Error"),
765 JOptionPane.ERROR_MESSAGE
766 );
767 return;
768 }
769 }
770
771 File preferenceFile = getPreferenceFile();
772 try {
773 if (!preferenceFile.exists()) {
774 Main.info(tr("Missing preference file ''{0}''. Creating a default preference file.", preferenceFile.getAbsoluteFile()));
775 resetToDefault();
776 save();
777 } else if (reset) {
778 Main.warn(tr("Replacing existing preference file ''{0}'' with default preference file.", preferenceFile.getAbsoluteFile()));
779 resetToDefault();
780 save();
781 }
782 } catch(IOException e) {
783 Main.error(e);
784 JOptionPane.showMessageDialog(
785 Main.parent,
786 tr("<html>Failed to initialize preferences.<br>Failed to reset preference file to default: {0}</html>",getPreferenceFile().getAbsoluteFile()),
787 tr("Error"),
788 JOptionPane.ERROR_MESSAGE
789 );
790 return;
791 }
792 try {
793 load();
794 } catch (Exception e) {
795 Main.error(e);
796 File backupFile = new File(prefDir,"preferences.xml.bak");
797 JOptionPane.showMessageDialog(
798 Main.parent,
799 tr("<html>Preferences file had errors.<br> Making backup of old one to <br>{0}<br> and creating a new default preference file.</html>", backupFile.getAbsoluteFile()),
800 tr("Error"),
801 JOptionPane.ERROR_MESSAGE
802 );
803 Main.platform.rename(preferenceFile, backupFile);
804 try {
805 resetToDefault();
806 save();
807 } catch(IOException e1) {
808 Main.error(e1);
809 Main.warn(tr("Failed to initialize preferences. Failed to reset preference file to default: {0}", getPreferenceFile()));
810 }
811 }
812 }
813
814 public final void resetToDefault(){
815 settingsMap.clear();
816 }
817
818 /**
819 * Convenience method for accessing colour preferences.
820 *
821 * @param colName name of the colour
822 * @param def default value
823 * @return a Color object for the configured colour, or the default value if none configured.
824 */
825 public synchronized Color getColor(String colName, Color def) {
826 return getColor(colName, null, def);
827 }
828
829 public synchronized Color getUIColor(String colName) {
830 return UIManager.getColor(colName);
831 }
832
833 /* only for preferences */
834 public synchronized String getColorName(String o) {
835 try {
836 Matcher m = Pattern.compile("mappaint\\.(.+?)\\.(.+)").matcher(o);
837 if (m.matches()) {
838 return tr("Paint style {0}: {1}", tr(I18n.escape(m.group(1))), tr(I18n.escape(m.group(2))));
839 }
840 } catch (Exception e) {
841 Main.warn(e);
842 }
843 try {
844 Matcher m = Pattern.compile("layer (.+)").matcher(o);
845 if (m.matches()) {
846 return tr("Layer: {0}", tr(I18n.escape(m.group(1))));
847 }
848 } catch (Exception e) {
849 Main.warn(e);
850 }
851 return tr(I18n.escape(colornames.containsKey(o) ? colornames.get(o) : o));
852 }
853
854 /**
855 * Returns the color for the given key.
856 * @param key The color key
857 * @return the color
858 */
859 public Color getColor(ColorKey key) {
860 return getColor(key.getColorName(), key.getSpecialName(), key.getDefaultValue());
861 }
862
863 /**
864 * Convenience method for accessing colour preferences.
865 *
866 * @param colName name of the colour
867 * @param specName name of the special colour settings
868 * @param def default value
869 * @return a Color object for the configured colour, or the default value if none configured.
870 */
871 public synchronized Color getColor(String colName, String specName, Color def) {
872 String colKey = ColorProperty.getColorKey(colName);
873 if(!colKey.equals(colName)) {
874 colornames.put(colKey, colName);
875 }
876 String colStr = specName != null ? get("color."+specName) : "";
877 if (colStr.isEmpty()) {
878 colStr = get("color." + colKey, ColorHelper.color2html(def, true));
879 }
880 if (colStr != null && !colStr.isEmpty()) {
881 return ColorHelper.html2color(colStr);
882 } else {
883 return def;
884 }
885 }
886
887 public synchronized Color getDefaultColor(String colKey) {
888 StringSetting col = Utils.cast(defaultsMap.get("color."+colKey), StringSetting.class);
889 String colStr = col == null ? null : col.getValue();
890 return colStr == null || colStr.isEmpty() ? null : ColorHelper.html2color(colStr);
891 }
892
893 public synchronized boolean putColor(String colKey, Color val) {
894 return put("color."+colKey, val != null ? ColorHelper.color2html(val, true) : null);
895 }
896
897 public synchronized int getInteger(String key, int def) {
898 String v = get(key, Integer.toString(def));
899 if(v.isEmpty())
900 return def;
901
902 try {
903 return Integer.parseInt(v);
904 } catch(NumberFormatException e) {
905 // fall out
906 }
907 return def;
908 }
909
910 public synchronized int getInteger(String key, String specName, int def) {
911 String v = get(key+"."+specName);
912 if(v.isEmpty())
913 v = get(key,Integer.toString(def));
914 if(v.isEmpty())
915 return def;
916
917 try {
918 return Integer.parseInt(v);
919 } catch(NumberFormatException e) {
920 // fall out
921 }
922 return def;
923 }
924
925 public synchronized long getLong(String key, long def) {
926 String v = get(key, Long.toString(def));
927 if(null == v)
928 return def;
929
930 try {
931 return Long.parseLong(v);
932 } catch(NumberFormatException e) {
933 // fall out
934 }
935 return def;
936 }
937
938 public synchronized double getDouble(String key, double def) {
939 String v = get(key, Double.toString(def));
940 if(null == v)
941 return def;
942
943 try {
944 return Double.parseDouble(v);
945 } catch(NumberFormatException e) {
946 // fall out
947 }
948 return def;
949 }
950
951 /**
952 * Get a list of values for a certain key
953 * @param key the identifier for the setting
954 * @param def the default value.
955 * @return the corresponding value if the property has been set before,
956 * def otherwise
957 */
958 public Collection<String> getCollection(String key, Collection<String> def) {
959 return getSetting(key, ListSetting.create(def), ListSetting.class).getValue();
960 }
961
962 /**
963 * Get a list of values for a certain key
964 * @param key the identifier for the setting
965 * @return the corresponding value if the property has been set before,
966 * an empty Collection otherwise.
967 */
968 public Collection<String> getCollection(String key) {
969 Collection<String> val = getCollection(key, null);
970 return val == null ? Collections.<String>emptyList() : val;
971 }
972
973 public synchronized void removeFromCollection(String key, String value) {
974 List<String> a = new ArrayList<>(getCollection(key, Collections.<String>emptyList()));
975 a.remove(value);
976 putCollection(key, a);
977 }
978
979 /**
980 * Set a value for a certain setting. The changed setting is saved
981 * to the preference file immediately. Due to caching mechanisms on modern
982 * operating systems and hardware, this shouldn't be a performance problem.
983 * @param key the unique identifier for the setting
984 * @param setting the value of the setting. In case it is null, the key-value
985 * entry will be removed.
986 * @return true, if something has changed (i.e. value is different than before)
987 */
988 public boolean putSetting(final String key, Setting setting) {
989 CheckParameterUtil.ensureParameterNotNull(key);
990 if (setting != null && setting.getValue() == null)
991 throw new IllegalArgumentException("setting argument must not have null value");
992 Setting settingOld;
993 Setting settingCopy = null;
994 synchronized (this) {
995 if (setting == null) {
996 settingOld = settingsMap.remove(key);
997 if (settingOld == null)
998 return false;
999 } else {
1000 settingOld = settingsMap.get(key);
1001 if (setting.equals(settingOld))
1002 return false;
1003 if (settingOld == null && setting.equals(defaultsMap.get(key)))
1004 return false;
1005 settingCopy = setting.copy();
1006 settingsMap.put(key, settingCopy);
1007 }
1008 try {
1009 save();
1010 } catch (IOException e){
1011 Main.warn(tr("Failed to persist preferences to ''{0}''", getPreferenceFile().getAbsoluteFile()));
1012 }
1013 }
1014 // Call outside of synchronized section in case some listener wait for other thread that wait for preference lock
1015 firePreferenceChanged(key, settingOld, settingCopy);
1016 return true;
1017 }
1018
1019 public synchronized Setting getSetting(String key, Setting def) {
1020 return getSetting(key, def, Setting.class);
1021 }
1022
1023 /**
1024 * Get settings value for a certain key and provide default a value.
1025 * @param <T> the setting type
1026 * @param key the identifier for the setting
1027 * @param def the default value. For each call of getSetting() with a given
1028 * key, the default value must be the same. <code>def</code> must not be
1029 * null, but the value of <code>def</code> can be null.
1030 * @param klass the setting type (same as T)
1031 * @return the corresponding value if the property has been set before,
1032 * def otherwise
1033 */
1034 @SuppressWarnings("unchecked")
1035 public synchronized <T extends Setting> T getSetting(String key, T def, Class<T> klass) {
1036 CheckParameterUtil.ensureParameterNotNull(key);
1037 CheckParameterUtil.ensureParameterNotNull(def);
1038 Setting oldDef = defaultsMap.get(key);
1039 if (oldDef != null && oldDef.getValue() != null && def.getValue() != null && !def.equals(oldDef)) {
1040 Main.info("Defaults for " + key + " differ: " + def + " != " + defaultsMap.get(key));
1041 }
1042 if (def.getValue() != null || oldDef == null) {
1043 defaultsMap.put(key, def.copy());
1044 }
1045 Setting prop = settingsMap.get(key);
1046 if (klass.isInstance(prop)) {
1047 return (T) prop;
1048 } else {
1049 return def;
1050 }
1051 }
1052
1053 public boolean putCollection(String key, Collection<String> value) {
1054 return putSetting(key, value == null ? null : ListSetting.create(value));
1055 }
1056
1057 /**
1058 * Saves at most {@code maxsize} items of collection {@code val}.
1059 */
1060 public boolean putCollectionBounded(String key, int maxsize, Collection<String> val) {
1061 Collection<String> newCollection = new ArrayList<>(Math.min(maxsize, val.size()));
1062 for (String i : val) {
1063 if (newCollection.size() >= maxsize) {
1064 break;
1065 }
1066 newCollection.add(i);
1067 }
1068 return putCollection(key, newCollection);
1069 }
1070
1071 /**
1072 * Used to read a 2-dimensional array of strings from the preference file.
1073 * If not a single entry could be found, <code>def</code> is returned.
1074 */
1075 @SuppressWarnings({ "unchecked", "rawtypes" })
1076 public synchronized Collection<Collection<String>> getArray(String key, Collection<Collection<String>> def) {
1077 ListListSetting val = getSetting(key, ListListSetting.create(def), ListListSetting.class);
1078 return (Collection) val.getValue();
1079 }
1080
1081 public Collection<Collection<String>> getArray(String key) {
1082 Collection<Collection<String>> res = getArray(key, null);
1083 return res == null ? Collections.<Collection<String>>emptyList() : res;
1084 }
1085
1086 public boolean putArray(String key, Collection<Collection<String>> value) {
1087 return putSetting(key, value == null ? null : ListListSetting.create(value));
1088 }
1089
1090 public Collection<Map<String, String>> getListOfStructs(String key, Collection<Map<String, String>> def) {
1091 return getSetting(key, new MapListSetting(def == null ? null : new ArrayList<>(def)), MapListSetting.class).getValue();
1092 }
1093
1094 public boolean putListOfStructs(String key, Collection<Map<String, String>> value) {
1095 return putSetting(key, value == null ? null : new MapListSetting(new ArrayList<>(value)));
1096 }
1097
1098 @Retention(RetentionPolicy.RUNTIME) public @interface pref { }
1099 @Retention(RetentionPolicy.RUNTIME) public @interface writeExplicitly { }
1100
1101 /**
1102 * Get a list of hashes which are represented by a struct-like class.
1103 * Possible properties are given by fields of the class klass that have
1104 * the @pref annotation.
1105 * Default constructor is used to initialize the struct objects, properties
1106 * then override some of these default values.
1107 * @param key main preference key
1108 * @param klass The struct class
1109 * @return a list of objects of type T or an empty list if nothing was found
1110 */
1111 public <T> List<T> getListOfStructs(String key, Class<T> klass) {
1112 List<T> r = getListOfStructs(key, null, klass);
1113 if (r == null)
1114 return Collections.emptyList();
1115 else
1116 return r;
1117 }
1118
1119 /**
1120 * same as above, but returns def if nothing was found
1121 */
1122 public <T> List<T> getListOfStructs(String key, Collection<T> def, Class<T> klass) {
1123 Collection<Map<String,String>> prop =
1124 getListOfStructs(key, def == null ? null : serializeListOfStructs(def, klass));
1125 if (prop == null)
1126 return def == null ? null : new ArrayList<>(def);
1127 List<T> lst = new ArrayList<>();
1128 for (Map<String,String> entries : prop) {
1129 T struct = deserializeStruct(entries, klass);
1130 lst.add(struct);
1131 }
1132 return lst;
1133 }
1134
1135 /**
1136 * Save a list of hashes represented by a struct-like class.
1137 * Considers only fields that have the @pref annotation.
1138 * In addition it does not write fields with null values. (Thus they are cleared)
1139 * Default values are given by the field values after default constructor has
1140 * been called.
1141 * Fields equal to the default value are not written unless the field has
1142 * the @writeExplicitly annotation.
1143 * @param key main preference key
1144 * @param val the list that is supposed to be saved
1145 * @param klass The struct class
1146 * @return true if something has changed
1147 */
1148 public <T> boolean putListOfStructs(String key, Collection<T> val, Class<T> klass) {
1149 return putListOfStructs(key, serializeListOfStructs(val, klass));
1150 }
1151
1152 private <T> Collection<Map<String,String>> serializeListOfStructs(Collection<T> l, Class<T> klass) {
1153 if (l == null)
1154 return null;
1155 Collection<Map<String,String>> vals = new ArrayList<>();
1156 for (T struct : l) {
1157 if (struct == null) {
1158 continue;
1159 }
1160 vals.add(serializeStruct(struct, klass));
1161 }
1162 return vals;
1163 }
1164
1165 public static <T> Map<String,String> serializeStruct(T struct, Class<T> klass) {
1166 T structPrototype;
1167 try {
1168 structPrototype = klass.newInstance();
1169 } catch (InstantiationException | IllegalAccessException ex) {
1170 throw new RuntimeException(ex);
1171 }
1172
1173 Map<String,String> hash = new LinkedHashMap<>();
1174 for (Field f : klass.getDeclaredFields()) {
1175 if (f.getAnnotation(pref.class) == null) {
1176 continue;
1177 }
1178 f.setAccessible(true);
1179 try {
1180 Object fieldValue = f.get(struct);
1181 Object defaultFieldValue = f.get(structPrototype);
1182 if (fieldValue != null) {
1183 if (f.getAnnotation(writeExplicitly.class) != null || !Utils.equal(fieldValue, defaultFieldValue)) {
1184 hash.put(f.getName().replace("_", "-"), fieldValue.toString());
1185 }
1186 }
1187 } catch (IllegalArgumentException | IllegalAccessException ex) {
1188 throw new RuntimeException(ex);
1189 }
1190 }
1191 return hash;
1192 }
1193
1194 public static <T> T deserializeStruct(Map<String,String> hash, Class<T> klass) {
1195 T struct = null;
1196 try {
1197 struct = klass.newInstance();
1198 } catch (InstantiationException | IllegalAccessException ex) {
1199 throw new RuntimeException(ex);
1200 }
1201 for (Entry<String,String> key_value : hash.entrySet()) {
1202 Object value = null;
1203 Field f;
1204 try {
1205 f = klass.getDeclaredField(key_value.getKey().replace("-", "_"));
1206 } catch (NoSuchFieldException ex) {
1207 continue;
1208 } catch (SecurityException ex) {
1209 throw new RuntimeException(ex);
1210 }
1211 if (f.getAnnotation(pref.class) == null) {
1212 continue;
1213 }
1214 f.setAccessible(true);
1215 if (f.getType() == Boolean.class || f.getType() == boolean.class) {
1216 value = Boolean.parseBoolean(key_value.getValue());
1217 } else if (f.getType() == Integer.class || f.getType() == int.class) {
1218 try {
1219 value = Integer.parseInt(key_value.getValue());
1220 } catch (NumberFormatException nfe) {
1221 continue;
1222 }
1223 } else if (f.getType() == Double.class || f.getType() == double.class) {
1224 try {
1225 value = Double.parseDouble(key_value.getValue());
1226 } catch (NumberFormatException nfe) {
1227 continue;
1228 }
1229 } else if (f.getType() == String.class) {
1230 value = key_value.getValue();
1231 } else
1232 throw new RuntimeException("unsupported preference primitive type");
1233
1234 try {
1235 f.set(struct, value);
1236 } catch (IllegalArgumentException ex) {
1237 throw new AssertionError(ex);
1238 } catch (IllegalAccessException ex) {
1239 throw new RuntimeException(ex);
1240 }
1241 }
1242 return struct;
1243 }
1244
1245 public Map<String, Setting> getAllSettings() {
1246 return new TreeMap<>(settingsMap);
1247 }
1248
1249 public Map<String, Setting> getAllDefaults() {
1250 return new TreeMap<>(defaultsMap);
1251 }
1252
1253 /**
1254 * Updates system properties with the current values in the preferences.
1255 *
1256 */
1257 public void updateSystemProperties() {
1258 if(getBoolean("prefer.ipv6", false)) {
1259 // never set this to false, only true!
1260 updateSystemProperty("java.net.preferIPv6Addresses", "true");
1261 }
1262 updateSystemProperty("http.agent", Version.getInstance().getAgentString());
1263 updateSystemProperty("user.language", get("language"));
1264 // Workaround to fix a Java bug.
1265 // Force AWT toolkit to update its internal preferences (fix #3645).
1266 // This ugly hack comes from Sun bug database: https://bugs.openjdk.java.net/browse/JDK-6292739
1267 try {
1268 Field field = Toolkit.class.getDeclaredField("resources");
1269 field.setAccessible(true);
1270 field.set(null, ResourceBundle.getBundle("sun.awt.resources.awt"));
1271 } catch (Exception e) {
1272 // Ignore all exceptions
1273 }
1274 // Workaround to fix a Java "feature"
1275 // See http://stackoverflow.com/q/7615645/2257172 and #9875
1276 if (getBoolean("jdk.tls.disableSNIExtension", true)) {
1277 updateSystemProperty("jsse.enableSNIExtension", "false");
1278 }
1279 // Workaround to fix another Java bug
1280 // Force Java 7 to use old sorting algorithm of Arrays.sort (fix #8712).
1281 // See Oracle bug database: https://bugs.openjdk.java.net/browse/JDK-7075600
1282 // and https://bugs.openjdk.java.net/browse/JDK-6923200
1283 if (getBoolean("jdk.Arrays.useLegacyMergeSort", !Version.getInstance().isLocalBuild())) {
1284 updateSystemProperty("java.util.Arrays.useLegacyMergeSort", "true");
1285 }
1286 }
1287
1288 /**
1289 * Updates a given system property.
1290 * @param key The property key
1291 * @param value The property value
1292 * @return the previous value of the system property, or {@code null} if it did not have one.
1293 * @since 6851
1294 */
1295 public static String updateSystemProperty(String key, String value) {
1296 if (value != null) {
1297 String old = System.setProperty(key, value);
1298 if (!key.toLowerCase().contains("password")) {
1299 Main.debug("System property '"+key+"' set to '"+value+"'. Old value was '"+old+"'");
1300 } else {
1301 Main.debug("System property '"+key+"' changed.");
1302 }
1303 return old;
1304 }
1305 return null;
1306 }
1307
1308 /**
1309 * Replies the collection of plugin site URLs from where plugin lists can be downloaded.
1310 * @return the collection of plugin site URLs
1311 */
1312 public Collection<String> getPluginSites() {
1313 return getCollection("pluginmanager.sites", Collections.singleton(Main.getJOSMWebsite()+"/plugin%<?plugins=>"));
1314 }
1315
1316 /**
1317 * Sets the collection of plugin site URLs.
1318 *
1319 * @param sites the site URLs
1320 */
1321 public void setPluginSites(Collection<String> sites) {
1322 putCollection("pluginmanager.sites", sites);
1323 }
1324
1325 protected XMLStreamReader parser;
1326
1327 public void validateXML(Reader in) throws Exception {
1328 SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
1329 Schema schema = factory.newSchema(new StreamSource(new MirroredInputStream("resource://data/preferences.xsd")));
1330 Validator validator = schema.newValidator();
1331 validator.validate(new StreamSource(in));
1332 }
1333
1334 public void fromXML(Reader in) throws XMLStreamException {
1335 XMLStreamReader parser = XMLInputFactory.newInstance().createXMLStreamReader(in);
1336 this.parser = parser;
1337 parse();
1338 }
1339
1340 public void parse() throws XMLStreamException {
1341 int event = parser.getEventType();
1342 while (true) {
1343 if (event == XMLStreamConstants.START_ELEMENT) {
1344 parseRoot();
1345 } else if (event == XMLStreamConstants.END_ELEMENT) {
1346 return;
1347 }
1348 if (parser.hasNext()) {
1349 event = parser.next();
1350 } else {
1351 break;
1352 }
1353 }
1354 parser.close();
1355 }
1356
1357 public void parseRoot() throws XMLStreamException {
1358 while (true) {
1359 int event = parser.next();
1360 if (event == XMLStreamConstants.START_ELEMENT) {
1361 String localName = parser.getLocalName();
1362 switch(localName) {
1363 case "tag":
1364 settingsMap.put(parser.getAttributeValue(null, "key"), new StringSetting(parser.getAttributeValue(null, "value")));
1365 jumpToEnd();
1366 break;
1367 case "list":
1368 case "collection":
1369 case "lists":
1370 case "maps":
1371 parseToplevelList();
1372 break;
1373 default:
1374 throwException("Unexpected element: "+localName);
1375 }
1376 } else if (event == XMLStreamConstants.END_ELEMENT) {
1377 return;
1378 }
1379 }
1380 }
1381
1382 private void jumpToEnd() throws XMLStreamException {
1383 while (true) {
1384 int event = parser.next();
1385 if (event == XMLStreamConstants.START_ELEMENT) {
1386 jumpToEnd();
1387 } else if (event == XMLStreamConstants.END_ELEMENT) {
1388 return;
1389 }
1390 }
1391 }
1392
1393 protected void parseToplevelList() throws XMLStreamException {
1394 String key = parser.getAttributeValue(null, "key");
1395 String name = parser.getLocalName();
1396
1397 List<String> entries = null;
1398 List<List<String>> lists = null;
1399 List<Map<String, String>> maps = null;
1400 while (true) {
1401 int event = parser.next();
1402 if (event == XMLStreamConstants.START_ELEMENT) {
1403 String localName = parser.getLocalName();
1404 switch(localName) {
1405 case "entry":
1406 if (entries == null) {
1407 entries = new ArrayList<>();
1408 }
1409 entries.add(parser.getAttributeValue(null, "value"));
1410 jumpToEnd();
1411 break;
1412 case "list":
1413 if (lists == null) {
1414 lists = new ArrayList<>();
1415 }
1416 lists.add(parseInnerList());
1417 break;
1418 case "map":
1419 if (maps == null) {
1420 maps = new ArrayList<>();
1421 }
1422 maps.add(parseMap());
1423 break;
1424 default:
1425 throwException("Unexpected element: "+localName);
1426 }
1427 } else if (event == XMLStreamConstants.END_ELEMENT) {
1428 break;
1429 }
1430 }
1431 if (entries != null) {
1432 settingsMap.put(key, new ListSetting(Collections.unmodifiableList(entries)));
1433 } else if (lists != null) {
1434 settingsMap.put(key, new ListListSetting(Collections.unmodifiableList(lists)));
1435 } else if (maps != null) {
1436 settingsMap.put(key, new MapListSetting(Collections.unmodifiableList(maps)));
1437 } else {
1438 if ("lists".equals(name)) {
1439 settingsMap.put(key, new ListListSetting(Collections.<List<String>>emptyList()));
1440 } else if ("maps".equals(name)) {
1441 settingsMap.put(key, new MapListSetting(Collections.<Map<String, String>>emptyList()));
1442 } else {
1443 settingsMap.put(key, new ListSetting(Collections.<String>emptyList()));
1444 }
1445 }
1446 }
1447
1448 protected List<String> parseInnerList() throws XMLStreamException {
1449 List<String> entries = new ArrayList<>();
1450 while (true) {
1451 int event = parser.next();
1452 if (event == XMLStreamConstants.START_ELEMENT) {
1453 if ("entry".equals(parser.getLocalName())) {
1454 entries.add(parser.getAttributeValue(null, "value"));
1455 jumpToEnd();
1456 } else {
1457 throwException("Unexpected element: "+parser.getLocalName());
1458 }
1459 } else if (event == XMLStreamConstants.END_ELEMENT) {
1460 break;
1461 }
1462 }
1463 return Collections.unmodifiableList(entries);
1464 }
1465
1466 protected Map<String, String> parseMap() throws XMLStreamException {
1467 Map<String, String> map = new LinkedHashMap<>();
1468 while (true) {
1469 int event = parser.next();
1470 if (event == XMLStreamConstants.START_ELEMENT) {
1471 if ("tag".equals(parser.getLocalName())) {
1472 map.put(parser.getAttributeValue(null, "key"), parser.getAttributeValue(null, "value"));
1473 jumpToEnd();
1474 } else {
1475 throwException("Unexpected element: "+parser.getLocalName());
1476 }
1477 } else if (event == XMLStreamConstants.END_ELEMENT) {
1478 break;
1479 }
1480 }
1481 return Collections.unmodifiableMap(map);
1482 }
1483
1484 protected void throwException(String msg) {
1485 throw new RuntimeException(msg + tr(" (at line {0}, column {1})", parser.getLocation().getLineNumber(), parser.getLocation().getColumnNumber()));
1486 }
1487
1488 private class SettingToXml implements SettingVisitor {
1489 private StringBuilder b;
1490 private boolean noPassword;
1491 private String key;
1492
1493 public SettingToXml(StringBuilder b, boolean noPassword) {
1494 this.b = b;
1495 this.noPassword = noPassword;
1496 }
1497
1498 public void setKey(String key) {
1499 this.key = key;
1500 }
1501
1502 @Override
1503 public void visit(StringSetting setting) {
1504 if (noPassword && "osm-server.password".equals(key))
1505 return; // do not store plain password.
1506 /* don't save default values */
1507 if (setting.equals(defaultsMap.get(key)))
1508 return;
1509 b.append(" <tag key='");
1510 b.append(XmlWriter.encode(key));
1511 b.append("' value='");
1512 b.append(XmlWriter.encode(setting.getValue()));
1513 b.append("'/>\n");
1514 }
1515
1516 @Override
1517 public void visit(ListSetting setting) {
1518 /* don't save default values */
1519 if (setting.equals(defaultsMap.get(key)))
1520 return;
1521 b.append(" <list key='").append(XmlWriter.encode(key)).append("'>\n");
1522 for (String s : setting.getValue()) {
1523 b.append(" <entry value='").append(XmlWriter.encode(s)).append("'/>\n");
1524 }
1525 b.append(" </list>\n");
1526 }
1527
1528 @Override
1529 public void visit(ListListSetting setting) {
1530 /* don't save default values */
1531 if (setting.equals(defaultsMap.get(key)))
1532 return;
1533 b.append(" <lists key='").append(XmlWriter.encode(key)).append("'>\n");
1534 for (List<String> list : setting.getValue()) {
1535 b.append(" <list>\n");
1536 for (String s : list) {
1537 b.append(" <entry value='").append(XmlWriter.encode(s)).append("'/>\n");
1538 }
1539 b.append(" </list>\n");
1540 }
1541 b.append(" </lists>\n");
1542 }
1543
1544 @Override
1545 public void visit(MapListSetting setting) {
1546 b.append(" <maps key='").append(XmlWriter.encode(key)).append("'>\n");
1547 for (Map<String, String> struct : setting.getValue()) {
1548 b.append(" <map>\n");
1549 for (Entry<String, String> e : struct.entrySet()) {
1550 b.append(" <tag key='").append(XmlWriter.encode(e.getKey())).append("' value='").append(XmlWriter.encode(e.getValue())).append("'/>\n");
1551 }
1552 b.append(" </map>\n");
1553 }
1554 b.append(" </maps>\n");
1555 }
1556 }
1557
1558 public String toXML(boolean nopass) {
1559 StringBuilder b = new StringBuilder(
1560 "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
1561 "<preferences xmlns=\""+Main.getXMLBase()+"/preferences-1.0\" version=\""+
1562 Version.getInstance().getVersion() + "\">\n");
1563 SettingToXml toXml = new SettingToXml(b, nopass);
1564 for (Entry<String, Setting> e : settingsMap.entrySet()) {
1565 toXml.setKey(e.getKey());
1566 e.getValue().visit(toXml);
1567 }
1568 b.append("</preferences>\n");
1569 return b.toString();
1570 }
1571
1572 /**
1573 * Removes obsolete preference settings. If you throw out a once-used preference
1574 * setting, add it to the list here with an expiry date (written as comment). If you
1575 * see something with an expiry date in the past, remove it from the list.
1576 */
1577 public void removeObsolete() {
1578 /* update the data with old consumer key*/
1579 if(getInteger("josm.version", Version.getInstance().getVersion()) < 6076) {
1580 if(!get("oauth.access-token.key").isEmpty() && get("oauth.settings.consumer-key").isEmpty()) {
1581 put("oauth.settings.consumer-key", "AdCRxTpvnbmfV8aPqrTLyA");
1582 put("oauth.settings.consumer-secret", "XmYOiGY9hApytcBC3xCec3e28QBqOWz5g6DSb5UpE");
1583 }
1584 }
1585
1586 String[] obsolete = {
1587 "downloadAlong.downloadAlongTrack.distance", // 07/2013 - can be removed mid-2014. Replaced by downloadAlongWay.distance
1588 "downloadAlong.downloadAlongTrack.area", // 07/2013 - can be removed mid-2014. Replaced by downloadAlongWay.area
1589 "gpxLayer.downloadAlongTrack.distance", // 07/2013 - can be removed mid-2014. Replaced by downloadAlongTrack.distance
1590 "gpxLayer.downloadAlongTrack.area", // 07/2013 - can be removed mid-2014. Replaced by downloadAlongTrack.area
1591 "gpxLayer.downloadAlongTrack.near", // 07/2013 - can be removed mid-2014. Replaced by downloadAlongTrack.near
1592 "validator.tests", // 01/2014 - can be removed mid-2014. Replaced by validator.skip
1593 "validator.testsBeforeUpload", // 01/2014 - can be removed mid-2014. Replaced by validator.skipBeforeUpload
1594 "validator.TagChecker.sources", // 01/2014 - can be removed mid-2014. Replaced by validator.TagChecker.source
1595 "validator.TagChecker.usedatafile", // 01/2014 - can be removed mid-2014. Replaced by validator.TagChecker.source
1596 "validator.TagChecker.useignorefile", // 01/2014 - can be removed mid-2014. Replaced by validator.TagChecker.source
1597 "validator.TagChecker.usespellfile", // 01/2014 - can be removed mid-2014. Replaced by validator.TagChecker.source
1598 "validator.org.openstreetmap.josm.data.validation.tests.MapCSSTagChecker.sources" // 01/2014 - can be removed mid-2014. Replaced by validator.org.openstreetmap.josm.data.validation.tests.MapCSSTagChecker.entries
1599 };
1600 for (String key : obsolete) {
1601 if (settingsMap.containsKey(key)) {
1602 settingsMap.remove(key);
1603 Main.info(tr("Preference setting {0} has been removed since it is no longer used.", key));
1604 }
1605 }
1606 }
1607
1608 public static boolean isEqual(Setting a, Setting b) {
1609 if (a == null) return b == null;
1610 return a.equals(b);
1611 }
1612
1613}
Note: See TracBrowser for help on using the repository browser.