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

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

checkstyle

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