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

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

fix compilation warnings with JDK8 - equals() and hashcode() must be overriden in pairs

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