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

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

see #9875 - implement fallback via advanced preference jdk.tls.enableSNIExtension to re-enable SNI if needed

  • Property svn:eol-style set to native
File size: 61.5 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<String, Setting>();
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<String, Setting>();
102 // maps color keys to human readable color name
103 protected final SortedMap<String, String> colornames = new TreeMap<String, String>();
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<String>(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<List<String>>(value.size());
279 for (Collection<String> lst : value) {
280 valueList.add(new ArrayList<String>(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<List<String>>(value.size());
301 for (Collection<String> lst : value) {
302 List<String> lstCopy = new ArrayList<String>(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<Map<String, String>>(value.size());
362 for (Map<String, String> map : value) {
363 Map<String, String> mapCopy = new LinkedHashMap<String,String>(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<PreferenceChangedListener>();
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<String>();
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 synchronized public 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 synchronized public String get(final String key, final String def) {
592 return getSetting(key, new StringSetting(def), StringSetting.class).getValue();
593 }
594
595 synchronized public Map<String, String> getAllPrefix(final String prefix) {
596 final Map<String,String> all = new TreeMap<String,String>();
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 synchronized public List<String> getAllPrefixCollectionKeys(final String prefix) {
606 final List<String> all = new LinkedList<String>();
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 synchronized public Map<String, String> getAllColors() {
616 final Map<String,String> all = new TreeMap<String,String>();
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 synchronized public boolean getBoolean(final String key) {
634 String s = get(key, null);
635 return s == null ? false : Boolean.parseBoolean(s);
636 }
637
638 synchronized public boolean getBoolean(final String key, final boolean def) {
639 return Boolean.parseBoolean(get(key, Boolean.toString(def)));
640 }
641
642 synchronized public 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 synchronized public Color getColor(String colName, Color def) {
826 return getColor(colName, null, def);
827 }
828
829 synchronized public Color getUIColor(String colName) {
830 return UIManager.getColor(colName);
831 }
832
833 /* only for preferences */
834 synchronized public 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 synchronized public 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 synchronized public 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 synchronized public boolean putColor(String colKey, Color val) {
894 return put("color."+colKey, val != null ? ColorHelper.color2html(val, true) : null);
895 }
896
897 synchronized public 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 synchronized public 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 synchronized public 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 synchronized public 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 synchronized public void removeFromCollection(String key, String value) {
974 List<String> a = new ArrayList<String>(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 synchronized public 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 synchronized public <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<String>(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 synchronized public 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<Map<String, String>>(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<Map<String, String>>(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<T>(def);
1127 List<T> lst = new ArrayList<T>();
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<Map<String,String>>();
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 ex) {
1170 throw new RuntimeException(ex);
1171 } catch (IllegalAccessException ex) {
1172 throw new RuntimeException(ex);
1173 }
1174
1175 Map<String,String> hash = new LinkedHashMap<String,String>();
1176 for (Field f : klass.getDeclaredFields()) {
1177 if (f.getAnnotation(pref.class) == null) {
1178 continue;
1179 }
1180 f.setAccessible(true);
1181 try {
1182 Object fieldValue = f.get(struct);
1183 Object defaultFieldValue = f.get(structPrototype);
1184 if (fieldValue != null) {
1185 if (f.getAnnotation(writeExplicitly.class) != null || !Utils.equal(fieldValue, defaultFieldValue)) {
1186 hash.put(f.getName().replace("_", "-"), fieldValue.toString());
1187 }
1188 }
1189 } catch (IllegalArgumentException ex) {
1190 throw new RuntimeException(ex);
1191 } catch (IllegalAccessException ex) {
1192 throw new RuntimeException(ex);
1193 }
1194 }
1195 return hash;
1196 }
1197
1198 public static <T> T deserializeStruct(Map<String,String> hash, Class<T> klass) {
1199 T struct = null;
1200 try {
1201 struct = klass.newInstance();
1202 } catch (InstantiationException ex) {
1203 throw new RuntimeException(ex);
1204 } catch (IllegalAccessException ex) {
1205 throw new RuntimeException(ex);
1206 }
1207 for (Entry<String,String> key_value : hash.entrySet()) {
1208 Object value = null;
1209 Field f;
1210 try {
1211 f = klass.getDeclaredField(key_value.getKey().replace("-", "_"));
1212 } catch (NoSuchFieldException ex) {
1213 continue;
1214 } catch (SecurityException ex) {
1215 throw new RuntimeException(ex);
1216 }
1217 if (f.getAnnotation(pref.class) == null) {
1218 continue;
1219 }
1220 f.setAccessible(true);
1221 if (f.getType() == Boolean.class || f.getType() == boolean.class) {
1222 value = Boolean.parseBoolean(key_value.getValue());
1223 } else if (f.getType() == Integer.class || f.getType() == int.class) {
1224 try {
1225 value = Integer.parseInt(key_value.getValue());
1226 } catch (NumberFormatException nfe) {
1227 continue;
1228 }
1229 } else if (f.getType() == Double.class || f.getType() == double.class) {
1230 try {
1231 value = Double.parseDouble(key_value.getValue());
1232 } catch (NumberFormatException nfe) {
1233 continue;
1234 }
1235 } else if (f.getType() == String.class) {
1236 value = key_value.getValue();
1237 } else
1238 throw new RuntimeException("unsupported preference primitive type");
1239
1240 try {
1241 f.set(struct, value);
1242 } catch (IllegalArgumentException ex) {
1243 throw new AssertionError(ex);
1244 } catch (IllegalAccessException ex) {
1245 throw new RuntimeException(ex);
1246 }
1247 }
1248 return struct;
1249 }
1250
1251 public Map<String, Setting> getAllSettings() {
1252 return new TreeMap<String, Setting>(settingsMap);
1253 }
1254
1255 public Map<String, Setting> getAllDefaults() {
1256 return new TreeMap<String, Setting>(defaultsMap);
1257 }
1258
1259 /**
1260 * Updates system properties with the current values in the preferences.
1261 *
1262 */
1263 public void updateSystemProperties() {
1264 if(getBoolean("prefer.ipv6", false)) {
1265 // never set this to false, only true!
1266 updateSystemProperty("java.net.preferIPv6Addresses", "true");
1267 }
1268 updateSystemProperty("http.agent", Version.getInstance().getAgentString());
1269 updateSystemProperty("user.language", get("language"));
1270 // Workaround to fix a Java bug.
1271 // Force AWT toolkit to update its internal preferences (fix #3645).
1272 // This ugly hack comes from Sun bug database: https://bugs.openjdk.java.net/browse/JDK-6292739
1273 try {
1274 Field field = Toolkit.class.getDeclaredField("resources");
1275 field.setAccessible(true);
1276 field.set(null, ResourceBundle.getBundle("sun.awt.resources.awt"));
1277 } catch (Exception e) {
1278 // Ignore all exceptions
1279 }
1280 // Workaround to fix a Java "feature"
1281 // See http://stackoverflow.com/q/7615645/2257172 and #9875
1282 if (getBoolean("jdk.tls.disableSNIExtension", true)) {
1283 updateSystemProperty("jsse.enableSNIExtension", "false");
1284 }
1285 // Workaround to fix another Java bug
1286 // Force Java 7 to use old sorting algorithm of Arrays.sort (fix #8712).
1287 // See Oracle bug database: https://bugs.openjdk.java.net/browse/JDK-7075600
1288 // and https://bugs.openjdk.java.net/browse/JDK-6923200
1289 if (getBoolean("jdk.Arrays.useLegacyMergeSort", !Version.getInstance().isLocalBuild())) {
1290 updateSystemProperty("java.util.Arrays.useLegacyMergeSort", "true");
1291 }
1292 }
1293
1294 /**
1295 * Updates a given system property.
1296 * @param key The property key
1297 * @param value The property value
1298 * @return the previous value of the system property, or {@code null} if it did not have one.
1299 * @since 6851
1300 */
1301 public static String updateSystemProperty(String key, String value) {
1302 if (value != null) {
1303 String old = System.setProperty(key, value);
1304 if (!key.toLowerCase().contains("password")) {
1305 Main.debug("System property '"+key+"' set to '"+value+"'. Old value was '"+old+"'");
1306 } else {
1307 Main.debug("System property '"+key+"' changed.");
1308 }
1309 return old;
1310 }
1311 return null;
1312 }
1313
1314 /**
1315 * Replies the collection of plugin site URLs from where plugin lists can be downloaded.
1316 * @return the collection of plugin site URLs
1317 */
1318 public Collection<String> getPluginSites() {
1319 return getCollection("pluginmanager.sites", Collections.singleton(Main.getJOSMWebsite()+"/plugin%<?plugins=>"));
1320 }
1321
1322 /**
1323 * Sets the collection of plugin site URLs.
1324 *
1325 * @param sites the site URLs
1326 */
1327 public void setPluginSites(Collection<String> sites) {
1328 putCollection("pluginmanager.sites", sites);
1329 }
1330
1331 protected XMLStreamReader parser;
1332
1333 public void validateXML(Reader in) throws Exception {
1334 SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
1335 Schema schema = factory.newSchema(new StreamSource(new MirroredInputStream("resource://data/preferences.xsd")));
1336 Validator validator = schema.newValidator();
1337 validator.validate(new StreamSource(in));
1338 }
1339
1340 public void fromXML(Reader in) throws XMLStreamException {
1341 XMLStreamReader parser = XMLInputFactory.newInstance().createXMLStreamReader(in);
1342 this.parser = parser;
1343 parse();
1344 }
1345
1346 public void parse() throws XMLStreamException {
1347 int event = parser.getEventType();
1348 while (true) {
1349 if (event == XMLStreamConstants.START_ELEMENT) {
1350 parseRoot();
1351 } else if (event == XMLStreamConstants.END_ELEMENT) {
1352 return;
1353 }
1354 if (parser.hasNext()) {
1355 event = parser.next();
1356 } else {
1357 break;
1358 }
1359 }
1360 parser.close();
1361 }
1362
1363 public void parseRoot() throws XMLStreamException {
1364 while (true) {
1365 int event = parser.next();
1366 if (event == XMLStreamConstants.START_ELEMENT) {
1367 if (parser.getLocalName().equals("tag")) {
1368 settingsMap.put(parser.getAttributeValue(null, "key"), new StringSetting(parser.getAttributeValue(null, "value")));
1369 jumpToEnd();
1370 } else if (parser.getLocalName().equals("list") ||
1371 parser.getLocalName().equals("collection") ||
1372 parser.getLocalName().equals("lists") ||
1373 parser.getLocalName().equals("maps")
1374 ) {
1375 parseToplevelList();
1376 } else {
1377 throwException("Unexpected element: "+parser.getLocalName());
1378 }
1379 } else if (event == XMLStreamConstants.END_ELEMENT) {
1380 return;
1381 }
1382 }
1383 }
1384
1385 private void jumpToEnd() throws XMLStreamException {
1386 while (true) {
1387 int event = parser.next();
1388 if (event == XMLStreamConstants.START_ELEMENT) {
1389 jumpToEnd();
1390 } else if (event == XMLStreamConstants.END_ELEMENT) {
1391 return;
1392 }
1393 }
1394 }
1395
1396 protected void parseToplevelList() throws XMLStreamException {
1397 String key = parser.getAttributeValue(null, "key");
1398 String name = parser.getLocalName();
1399
1400 List<String> entries = null;
1401 List<List<String>> lists = null;
1402 List<Map<String, String>> maps = null;
1403 while (true) {
1404 int event = parser.next();
1405 if (event == XMLStreamConstants.START_ELEMENT) {
1406 if (parser.getLocalName().equals("entry")) {
1407 if (entries == null) {
1408 entries = new ArrayList<String>();
1409 }
1410 entries.add(parser.getAttributeValue(null, "value"));
1411 jumpToEnd();
1412 } else if (parser.getLocalName().equals("list")) {
1413 if (lists == null) {
1414 lists = new ArrayList<List<String>>();
1415 }
1416 lists.add(parseInnerList());
1417 } else if (parser.getLocalName().equals("map")) {
1418 if (maps == null) {
1419 maps = new ArrayList<Map<String, String>>();
1420 }
1421 maps.add(parseMap());
1422 } else {
1423 throwException("Unexpected element: "+parser.getLocalName());
1424 }
1425 } else if (event == XMLStreamConstants.END_ELEMENT) {
1426 break;
1427 }
1428 }
1429 if (entries != null) {
1430 settingsMap.put(key, new ListSetting(Collections.unmodifiableList(entries)));
1431 } else if (lists != null) {
1432 settingsMap.put(key, new ListListSetting(Collections.unmodifiableList(lists)));
1433 } else if (maps != null) {
1434 settingsMap.put(key, new MapListSetting(Collections.unmodifiableList(maps)));
1435 } else {
1436 if (name.equals("lists")) {
1437 settingsMap.put(key, new ListListSetting(Collections.<List<String>>emptyList()));
1438 } else if (name.equals("maps")) {
1439 settingsMap.put(key, new MapListSetting(Collections.<Map<String, String>>emptyList()));
1440 } else {
1441 settingsMap.put(key, new ListSetting(Collections.<String>emptyList()));
1442 }
1443 }
1444 }
1445
1446 protected List<String> parseInnerList() throws XMLStreamException {
1447 List<String> entries = new ArrayList<String>();
1448 while (true) {
1449 int event = parser.next();
1450 if (event == XMLStreamConstants.START_ELEMENT) {
1451 if (parser.getLocalName().equals("entry")) {
1452 entries.add(parser.getAttributeValue(null, "value"));
1453 jumpToEnd();
1454 } else {
1455 throwException("Unexpected element: "+parser.getLocalName());
1456 }
1457 } else if (event == XMLStreamConstants.END_ELEMENT) {
1458 break;
1459 }
1460 }
1461 return Collections.unmodifiableList(entries);
1462 }
1463
1464 protected Map<String, String> parseMap() throws XMLStreamException {
1465 Map<String, String> map = new LinkedHashMap<String, String>();
1466 while (true) {
1467 int event = parser.next();
1468 if (event == XMLStreamConstants.START_ELEMENT) {
1469 if (parser.getLocalName().equals("tag")) {
1470 map.put(parser.getAttributeValue(null, "key"), parser.getAttributeValue(null, "value"));
1471 jumpToEnd();
1472 } else {
1473 throwException("Unexpected element: "+parser.getLocalName());
1474 }
1475 } else if (event == XMLStreamConstants.END_ELEMENT) {
1476 break;
1477 }
1478 }
1479 return Collections.unmodifiableMap(map);
1480 }
1481
1482 protected void throwException(String msg) {
1483 throw new RuntimeException(msg + tr(" (at line {0}, column {1})", parser.getLocation().getLineNumber(), parser.getLocation().getColumnNumber()));
1484 }
1485
1486 private class SettingToXml implements SettingVisitor {
1487 private StringBuilder b;
1488 private boolean noPassword;
1489 private String key;
1490
1491 public SettingToXml(StringBuilder b, boolean noPassword) {
1492 this.b = b;
1493 this.noPassword = noPassword;
1494 }
1495
1496 public void setKey(String key) {
1497 this.key = key;
1498 }
1499
1500 @Override
1501 public void visit(StringSetting setting) {
1502 if (noPassword && key.equals("osm-server.password"))
1503 return; // do not store plain password.
1504 /* don't save default values */
1505 if (setting.equals(defaultsMap.get(key)))
1506 return;
1507 b.append(" <tag key='");
1508 b.append(XmlWriter.encode(key));
1509 b.append("' value='");
1510 b.append(XmlWriter.encode(setting.getValue()));
1511 b.append("'/>\n");
1512 }
1513
1514 @Override
1515 public void visit(ListSetting setting) {
1516 /* don't save default values */
1517 if (setting.equals(defaultsMap.get(key)))
1518 return;
1519 b.append(" <list key='").append(XmlWriter.encode(key)).append("'>\n");
1520 for (String s : setting.getValue()) {
1521 b.append(" <entry value='").append(XmlWriter.encode(s)).append("'/>\n");
1522 }
1523 b.append(" </list>\n");
1524 }
1525
1526 @Override
1527 public void visit(ListListSetting setting) {
1528 /* don't save default values */
1529 if (setting.equals(defaultsMap.get(key)))
1530 return;
1531 b.append(" <lists key='").append(XmlWriter.encode(key)).append("'>\n");
1532 for (List<String> list : setting.getValue()) {
1533 b.append(" <list>\n");
1534 for (String s : list) {
1535 b.append(" <entry value='").append(XmlWriter.encode(s)).append("'/>\n");
1536 }
1537 b.append(" </list>\n");
1538 }
1539 b.append(" </lists>\n");
1540 }
1541
1542 @Override
1543 public void visit(MapListSetting setting) {
1544 b.append(" <maps key='").append(XmlWriter.encode(key)).append("'>\n");
1545 for (Map<String, String> struct : setting.getValue()) {
1546 b.append(" <map>\n");
1547 for (Entry<String, String> e : struct.entrySet()) {
1548 b.append(" <tag key='").append(XmlWriter.encode(e.getKey())).append("' value='").append(XmlWriter.encode(e.getValue())).append("'/>\n");
1549 }
1550 b.append(" </map>\n");
1551 }
1552 b.append(" </maps>\n");
1553 }
1554 }
1555
1556 public String toXML(boolean nopass) {
1557 StringBuilder b = new StringBuilder(
1558 "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
1559 "<preferences xmlns=\""+Main.getXMLBase()+"/preferences-1.0\" version=\""+
1560 Version.getInstance().getVersion() + "\">\n");
1561 SettingToXml toXml = new SettingToXml(b, nopass);
1562 for (Entry<String, Setting> e : settingsMap.entrySet()) {
1563 toXml.setKey(e.getKey());
1564 e.getValue().visit(toXml);
1565 }
1566 b.append("</preferences>\n");
1567 return b.toString();
1568 }
1569
1570 /**
1571 * Removes obsolete preference settings. If you throw out a once-used preference
1572 * setting, add it to the list here with an expiry date (written as comment). If you
1573 * see something with an expiry date in the past, remove it from the list.
1574 */
1575 public void removeObsolete() {
1576 /* update the data with old consumer key*/
1577 if(getInteger("josm.version", Version.getInstance().getVersion()) < 6076) {
1578 if(!get("oauth.access-token.key").isEmpty() && get("oauth.settings.consumer-key").isEmpty()) {
1579 put("oauth.settings.consumer-key", "AdCRxTpvnbmfV8aPqrTLyA");
1580 put("oauth.settings.consumer-secret", "XmYOiGY9hApytcBC3xCec3e28QBqOWz5g6DSb5UpE");
1581 }
1582 }
1583
1584 String[] obsolete = {
1585 "downloadAlong.downloadAlongTrack.distance", // 07/2013 - can be removed mid-2014. Replaced by downloadAlongWay.distance
1586 "downloadAlong.downloadAlongTrack.area", // 07/2013 - can be removed mid-2014. Replaced by downloadAlongWay.area
1587 "gpxLayer.downloadAlongTrack.distance", // 07/2013 - can be removed mid-2014. Replaced by downloadAlongTrack.distance
1588 "gpxLayer.downloadAlongTrack.area", // 07/2013 - can be removed mid-2014. Replaced by downloadAlongTrack.area
1589 "gpxLayer.downloadAlongTrack.near", // 07/2013 - can be removed mid-2014. Replaced by downloadAlongTrack.near
1590 "validator.tests", // 01/2014 - can be removed mid-2014. Replaced by validator.skip
1591 "validator.testsBeforeUpload", // 01/2014 - can be removed mid-2014. Replaced by validator.skipBeforeUpload
1592 "validator.TagChecker.sources", // 01/2014 - can be removed mid-2014. Replaced by validator.TagChecker.source
1593 "validator.TagChecker.usedatafile", // 01/2014 - can be removed mid-2014. Replaced by validator.TagChecker.source
1594 "validator.TagChecker.useignorefile", // 01/2014 - can be removed mid-2014. Replaced by validator.TagChecker.source
1595 "validator.TagChecker.usespellfile", // 01/2014 - can be removed mid-2014. Replaced by validator.TagChecker.source
1596 "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
1597 };
1598 for (String key : obsolete) {
1599 if (settingsMap.containsKey(key)) {
1600 settingsMap.remove(key);
1601 Main.info(tr("Preference setting {0} has been removed since it is no longer used.", key));
1602 }
1603 }
1604 }
1605
1606 public static boolean isEqual(Setting a, Setting b) {
1607 if (a == null) return b == null;
1608 return a.equals(b);
1609 }
1610
1611}
Note: See TracBrowser for help on using the repository browser.