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

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

Sonar/FindBugs - Loose coupling

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