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

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

Rework console output:

  • new log level "error"
  • Replace nearly all calls to system.out and system.err to Main.(error|warn|info|debug)
  • Remove some unnecessary debug output
  • Some messages are modified (removal of "Info", "Warning", "Error" from the message itself -> notable i18n impact but limited to console error messages not seen by the majority of users, so that's ok)
  • Property svn:eol-style set to native
File size: 64.8 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 TreeMap<String, String> getAllColors() {
479 final TreeMap<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 {
742 Matcher m = Pattern.compile("mappaint\\.(.+?)\\.(.+)").matcher(o);
743 m.matches();
744 return tr("Paint style {0}: {1}", tr(m.group(1)), tr(m.group(2)));
745 }
746 catch (Exception e) {}
747 try
748 {
749 Matcher m = Pattern.compile("layer (.+)").matcher(o);
750 m.matches();
751 return tr("Layer: {0}", tr(m.group(1)));
752 }
753 catch (Exception e) {}
754 return tr(colornames.containsKey(o) ? colornames.get(o) : o);
755 }
756
757 public Color getColor(ColorKey key) {
758 return getColor(key.getColorName(), key.getSpecialName(), key.getDefaultValue());
759 }
760
761 /**
762 * Convenience method for accessing colour preferences.
763 *
764 * @param colName name of the colour
765 * @param specName name of the special colour settings
766 * @param def default value
767 * @return a Color object for the configured colour, or the default value if none configured.
768 */
769 synchronized public Color getColor(String colName, String specName, Color def) {
770 String colKey = ColorProperty.getColorKey(colName);
771 if(!colKey.equals(colName)) {
772 colornames.put(colKey, colName);
773 }
774 putDefault("color."+colKey, ColorHelper.color2html(def));
775 String colStr = specName != null ? get("color."+specName) : "";
776 if(colStr.isEmpty()) {
777 colStr = get("color."+colKey);
778 }
779 return colStr.isEmpty() ? def : ColorHelper.html2color(colStr);
780 }
781
782 synchronized public Color getDefaultColor(String colKey) {
783 String colStr = defaults.get("color."+colKey);
784 return colStr == null || colStr.isEmpty() ? null : ColorHelper.html2color(colStr);
785 }
786
787 synchronized public boolean putColor(String colKey, Color val) {
788 return put("color."+colKey, val != null ? ColorHelper.color2html(val) : null);
789 }
790
791 synchronized public int getInteger(String key, int def) {
792 putDefault(key, Integer.toString(def));
793 String v = get(key);
794 if(v.isEmpty())
795 return def;
796
797 try {
798 return Integer.parseInt(v);
799 } catch(NumberFormatException e) {
800 // fall out
801 }
802 return def;
803 }
804
805 synchronized public int getInteger(String key, String specName, int def) {
806 putDefault(key, Integer.toString(def));
807 String v = get(key+"."+specName);
808 if(v.isEmpty())
809 v = get(key);
810 if(v.isEmpty())
811 return def;
812
813 try {
814 return Integer.parseInt(v);
815 } catch(NumberFormatException e) {
816 // fall out
817 }
818 return def;
819 }
820
821 synchronized public long getLong(String key, long def) {
822 putDefault(key, Long.toString(def));
823 String v = get(key);
824 if(null == v)
825 return def;
826
827 try {
828 return Long.parseLong(v);
829 } catch(NumberFormatException e) {
830 // fall out
831 }
832 return def;
833 }
834
835 synchronized public double getDouble(String key, double def) {
836 putDefault(key, Double.toString(def));
837 String v = get(key);
838 if(null == v)
839 return def;
840
841 try {
842 return Double.parseDouble(v);
843 } catch(NumberFormatException e) {
844 // fall out
845 }
846 return def;
847 }
848
849 /**
850 * Get a list of values for a certain key
851 * @param key the identifier for the setting
852 * @param def the default value.
853 * @return the corresponding value if the property has been set before,
854 * def otherwise
855 */
856 public Collection<String> getCollection(String key, Collection<String> def) {
857 putCollectionDefault(key, def == null ? null : new ArrayList<String>(def));
858 Collection<String> prop = collectionProperties.get(key);
859 if (prop != null)
860 return prop;
861 else
862 return def;
863 }
864
865 /**
866 * Get a list of values for a certain key
867 * @param key the identifier for the setting
868 * @return the corresponding value if the property has been set before,
869 * an empty Collection otherwise.
870 */
871 public Collection<String> getCollection(String key) {
872 putCollectionDefault(key, null);
873 Collection<String> prop = collectionProperties.get(key);
874 if (prop != null)
875 return prop;
876 else
877 return Collections.emptyList();
878 }
879
880 synchronized public void removeFromCollection(String key, String value) {
881 List<String> a = new ArrayList<String>(getCollection(key, Collections.<String>emptyList()));
882 a.remove(value);
883 putCollection(key, a);
884 }
885
886 public boolean putCollection(String key, Collection<String> value) {
887 List<String> oldValue = null;
888 List<String> valueCopy = null;
889
890 synchronized (this) {
891 if (value == null) {
892 oldValue = collectionProperties.remove(key);
893 boolean changed = oldValue != null;
894 changed |= properties.remove(key) != null;
895 if (!changed) return false;
896 } else {
897 oldValue = collectionProperties.get(key);
898 if (equalCollection(value, oldValue)) return false;
899 Collection<String> defValue = collectionDefaults.get(key);
900 if (oldValue == null && equalCollection(value, defValue)) return false;
901
902 valueCopy = new ArrayList<String>(value);
903 if (valueCopy.contains(null)) throw new RuntimeException("Error: Null as list element in preference setting (key '"+key+"')");
904 collectionProperties.put(key, Collections.unmodifiableList(valueCopy));
905 }
906 try {
907 save();
908 } catch (IOException e){
909 Main.warn(tr("Failed to persist preferences to ''{0}''", getPreferenceFile().getAbsoluteFile()));
910 }
911 }
912 // Call outside of synchronized section in case some listener wait for other thread that wait for preference lock
913 firePreferenceChanged(key, new ListSetting(oldValue), new ListSetting(valueCopy));
914 return true;
915 }
916
917 public static boolean equalCollection(Collection<String> a, Collection<String> b) {
918 if (a == null) return b == null;
919 if (b == null) return false;
920 if (a.size() != b.size()) return false;
921 Iterator<String> itA = a.iterator();
922 Iterator<String> itB = b.iterator();
923 while (itA.hasNext()) {
924 String aStr = itA.next();
925 String bStr = itB.next();
926 if (!Utils.equal(aStr,bStr)) return false;
927 }
928 return true;
929 }
930
931 /**
932 * Saves at most {@code maxsize} items of collection {@code val}.
933 */
934 public boolean putCollectionBounded(String key, int maxsize, Collection<String> val) {
935 Collection<String> newCollection = new ArrayList<String>(Math.min(maxsize, val.size()));
936 for (String i : val) {
937 if (newCollection.size() >= maxsize) {
938 break;
939 }
940 newCollection.add(i);
941 }
942 return putCollection(key, newCollection);
943 }
944
945 synchronized private void putCollectionDefault(String key, List<String> val) {
946 collectionDefaults.put(key, val);
947 }
948
949 /**
950 * Used to read a 2-dimensional array of strings from the preference file.
951 * If not a single entry could be found, def is returned.
952 */
953 synchronized public Collection<Collection<String>> getArray(String key, Collection<Collection<String>> def) {
954 if (def != null) {
955 List<List<String>> defCopy = new ArrayList<List<String>>(def.size());
956 for (Collection<String> lst : def) {
957 defCopy.add(Collections.unmodifiableList(new ArrayList<String>(lst)));
958 }
959 putArrayDefault(key, Collections.unmodifiableList(defCopy));
960 } else {
961 putArrayDefault(key, null);
962 }
963 List<List<String>> prop = arrayProperties.get(key);
964 if (prop != null) {
965 @SuppressWarnings({ "unchecked", "rawtypes" })
966 Collection<Collection<String>> prop_cast = (Collection) prop;
967 return prop_cast;
968 } else
969 return def;
970 }
971
972 public Collection<Collection<String>> getArray(String key) {
973 putArrayDefault(key, null);
974 List<List<String>> prop = arrayProperties.get(key);
975 if (prop != null) {
976 @SuppressWarnings({ "unchecked", "rawtypes" })
977 Collection<Collection<String>> prop_cast = (Collection) prop;
978 return prop_cast;
979 } else
980 return Collections.emptyList();
981 }
982
983 public boolean putArray(String key, Collection<Collection<String>> value) {
984 List<List<String>> oldValue = null;
985 List<List<String>> valueCopy = null;
986
987 synchronized (this) {
988 oldValue = arrayProperties.get(key);
989 if (value == null) {
990 if (arrayProperties.remove(key) != null) return false;
991 } else {
992 if (equalArray(value, oldValue)) return false;
993
994 List<List<String>> defValue = arrayDefaults.get(key);
995 if (oldValue == null && equalArray(value, defValue)) return false;
996
997 valueCopy = new ArrayList<List<String>>(value.size());
998 if (valueCopy.contains(null)) throw new RuntimeException("Error: Null as list element in preference setting (key '"+key+"')");
999 for (Collection<String> lst : value) {
1000 List<String> lstCopy = new ArrayList<String>(lst);
1001 if (lstCopy.contains(null)) throw new RuntimeException("Error: Null as inner list element in preference setting (key '"+key+"')");
1002 valueCopy.add(Collections.unmodifiableList(lstCopy));
1003 }
1004 arrayProperties.put(key, Collections.unmodifiableList(valueCopy));
1005 }
1006 try {
1007 save();
1008 } catch (IOException e){
1009 Main.warn(tr("Failed to persist preferences to ''{0}''", getPreferenceFile().getAbsoluteFile()));
1010 }
1011 }
1012 // Call outside of synchronized section in case some listener wait for other thread that wait for preference lock
1013 firePreferenceChanged(key, new ListListSetting(oldValue), new ListListSetting(valueCopy));
1014 return true;
1015 }
1016
1017 public static boolean equalArray(Collection<Collection<String>> a, Collection<List<String>> b) {
1018 if (a == null) return b == null;
1019 if (b == null) return false;
1020 if (a.size() != b.size()) return false;
1021 Iterator<Collection<String>> itA = a.iterator();
1022 Iterator<List<String>> itB = b.iterator();
1023 while (itA.hasNext()) {
1024 if (!equalCollection(itA.next(), itB.next())) return false;
1025 }
1026 return true;
1027 }
1028
1029 synchronized private void putArrayDefault(String key, List<List<String>> val) {
1030 arrayDefaults.put(key, val);
1031 }
1032
1033 public Collection<Map<String, String>> getListOfStructs(String key, Collection<Map<String, String>> def) {
1034 if (def != null) {
1035 List<Map<String, String>> defCopy = new ArrayList<Map<String, String>>(def.size());
1036 for (Map<String, String> map : def) {
1037 defCopy.add(Collections.unmodifiableMap(new LinkedHashMap<String,String>(map)));
1038 }
1039 putListOfStructsDefault(key, Collections.unmodifiableList(defCopy));
1040 } else {
1041 putListOfStructsDefault(key, null);
1042 }
1043 Collection<Map<String, String>> prop = listOfStructsProperties.get(key);
1044 if (prop != null)
1045 return prop;
1046 else
1047 return def;
1048 }
1049
1050 public boolean putListOfStructs(String key, Collection<Map<String, String>> value) {
1051
1052 List<Map<String, String>> oldValue;
1053 List<Map<String, String>> valueCopy = null;
1054
1055 synchronized (this) {
1056 oldValue = listOfStructsProperties.get(key);
1057 if (value == null) {
1058 if (listOfStructsProperties.remove(key) != null) return false;
1059 } else {
1060 if (equalListOfStructs(oldValue, value)) return false;
1061
1062 List<Map<String, String>> defValue = listOfStructsDefaults.get(key);
1063 if (oldValue == null && equalListOfStructs(value, defValue)) return false;
1064
1065 valueCopy = new ArrayList<Map<String, String>>(value.size());
1066 if (valueCopy.contains(null)) throw new RuntimeException("Error: Null as list element in preference setting (key '"+key+"')");
1067 for (Map<String, String> map : value) {
1068 Map<String, String> mapCopy = new LinkedHashMap<String,String>(map);
1069 if (mapCopy.keySet().contains(null)) throw new RuntimeException("Error: Null as map key in preference setting (key '"+key+"')");
1070 if (mapCopy.values().contains(null)) throw new RuntimeException("Error: Null as map value in preference setting (key '"+key+"')");
1071 valueCopy.add(Collections.unmodifiableMap(mapCopy));
1072 }
1073 listOfStructsProperties.put(key, Collections.unmodifiableList(valueCopy));
1074 }
1075 try {
1076 save();
1077 } catch (IOException e) {
1078 Main.warn(tr("Failed to persist preferences to ''{0}''", getPreferenceFile().getAbsoluteFile()));
1079 }
1080 }
1081 // Call outside of synchronized section in case some listener wait for other thread that wait for preference lock
1082 firePreferenceChanged(key, new MapListSetting(oldValue), new MapListSetting(valueCopy));
1083 return true;
1084 }
1085
1086 public static boolean equalListOfStructs(Collection<Map<String, String>> a, Collection<Map<String, String>> b) {
1087 if (a == null) return b == null;
1088 if (b == null) return false;
1089 if (a.size() != b.size()) return false;
1090 Iterator<Map<String, String>> itA = a.iterator();
1091 Iterator<Map<String, String>> itB = b.iterator();
1092 while (itA.hasNext()) {
1093 if (!equalMap(itA.next(), itB.next())) return false;
1094 }
1095 return true;
1096 }
1097
1098 private static boolean equalMap(Map<String, String> a, Map<String, String> b) {
1099 if (a == null) return b == null;
1100 if (b == null) return false;
1101 if (a.size() != b.size()) return false;
1102 for (Entry<String, String> e : a.entrySet()) {
1103 if (!Utils.equal(e.getValue(), b.get(e.getKey()))) return false;
1104 }
1105 return true;
1106 }
1107
1108 synchronized private void putListOfStructsDefault(String key, List<Map<String, String>> val) {
1109 listOfStructsDefaults.put(key, val);
1110 }
1111
1112 @Retention(RetentionPolicy.RUNTIME) public @interface pref { }
1113 @Retention(RetentionPolicy.RUNTIME) public @interface writeExplicitly { }
1114
1115 /**
1116 * Get a list of hashes which are represented by a struct-like class.
1117 * Possible properties are given by fields of the class klass that have
1118 * the @pref annotation.
1119 * Default constructor is used to initialize the struct objects, properties
1120 * then override some of these default values.
1121 * @param key main preference key
1122 * @param klass The struct class
1123 * @return a list of objects of type T or an empty list if nothing was found
1124 */
1125 public <T> List<T> getListOfStructs(String key, Class<T> klass) {
1126 List<T> r = getListOfStructs(key, null, klass);
1127 if (r == null)
1128 return Collections.emptyList();
1129 else
1130 return r;
1131 }
1132
1133 /**
1134 * same as above, but returns def if nothing was found
1135 */
1136 public <T> List<T> getListOfStructs(String key, Collection<T> def, Class<T> klass) {
1137 Collection<Map<String,String>> prop =
1138 getListOfStructs(key, def == null ? null : serializeListOfStructs(def, klass));
1139 if (prop == null)
1140 return def == null ? null : new ArrayList<T>(def);
1141 List<T> lst = new ArrayList<T>();
1142 for (Map<String,String> entries : prop) {
1143 T struct = deserializeStruct(entries, klass);
1144 lst.add(struct);
1145 }
1146 return lst;
1147 }
1148
1149 /**
1150 * Save a list of hashes represented by a struct-like class.
1151 * Considers only fields that have the @pref annotation.
1152 * In addition it does not write fields with null values. (Thus they are cleared)
1153 * Default values are given by the field values after default constructor has
1154 * been called.
1155 * Fields equal to the default value are not written unless the field has
1156 * the @writeExplicitly annotation.
1157 * @param key main preference key
1158 * @param val the list that is supposed to be saved
1159 * @param klass The struct class
1160 * @return true if something has changed
1161 */
1162 public <T> boolean putListOfStructs(String key, Collection<T> val, Class<T> klass) {
1163 return putListOfStructs(key, serializeListOfStructs(val, klass));
1164 }
1165
1166 private <T> Collection<Map<String,String>> serializeListOfStructs(Collection<T> l, Class<T> klass) {
1167 if (l == null)
1168 return null;
1169 Collection<Map<String,String>> vals = new ArrayList<Map<String,String>>();
1170 for (T struct : l) {
1171 if (struct == null) {
1172 continue;
1173 }
1174 vals.add(serializeStruct(struct, klass));
1175 }
1176 return vals;
1177 }
1178
1179 public static <T> Map<String,String> serializeStruct(T struct, Class<T> klass) {
1180 T structPrototype;
1181 try {
1182 structPrototype = klass.newInstance();
1183 } catch (InstantiationException ex) {
1184 throw new RuntimeException(ex);
1185 } catch (IllegalAccessException ex) {
1186 throw new RuntimeException(ex);
1187 }
1188
1189 Map<String,String> hash = new LinkedHashMap<String,String>();
1190 for (Field f : klass.getDeclaredFields()) {
1191 if (f.getAnnotation(pref.class) == null) {
1192 continue;
1193 }
1194 f.setAccessible(true);
1195 try {
1196 Object fieldValue = f.get(struct);
1197 Object defaultFieldValue = f.get(structPrototype);
1198 if (fieldValue != null) {
1199 if (f.getAnnotation(writeExplicitly.class) != null || !Utils.equal(fieldValue, defaultFieldValue)) {
1200 hash.put(f.getName().replace("_", "-"), fieldValue.toString());
1201 }
1202 }
1203 } catch (IllegalArgumentException ex) {
1204 throw new RuntimeException();
1205 } catch (IllegalAccessException ex) {
1206 throw new RuntimeException();
1207 }
1208 }
1209 return hash;
1210 }
1211
1212 public static <T> T deserializeStruct(Map<String,String> hash, Class<T> klass) {
1213 T struct = null;
1214 try {
1215 struct = klass.newInstance();
1216 } catch (InstantiationException ex) {
1217 throw new RuntimeException();
1218 } catch (IllegalAccessException ex) {
1219 throw new RuntimeException();
1220 }
1221 for (Entry<String,String> key_value : hash.entrySet()) {
1222 Object value = null;
1223 Field f;
1224 try {
1225 f = klass.getDeclaredField(key_value.getKey().replace("-", "_"));
1226 } catch (NoSuchFieldException ex) {
1227 continue;
1228 } catch (SecurityException ex) {
1229 throw new RuntimeException();
1230 }
1231 if (f.getAnnotation(pref.class) == null) {
1232 continue;
1233 }
1234 f.setAccessible(true);
1235 if (f.getType() == Boolean.class || f.getType() == boolean.class) {
1236 value = Boolean.parseBoolean(key_value.getValue());
1237 } else if (f.getType() == Integer.class || f.getType() == int.class) {
1238 try {
1239 value = Integer.parseInt(key_value.getValue());
1240 } catch (NumberFormatException nfe) {
1241 continue;
1242 }
1243 } else if (f.getType() == Double.class || f.getType() == double.class) {
1244 try {
1245 value = Double.parseDouble(key_value.getValue());
1246 } catch (NumberFormatException nfe) {
1247 continue;
1248 }
1249 } else if (f.getType() == String.class) {
1250 value = key_value.getValue();
1251 } else
1252 throw new RuntimeException("unsupported preference primitive type");
1253
1254 try {
1255 f.set(struct, value);
1256 } catch (IllegalArgumentException ex) {
1257 throw new AssertionError();
1258 } catch (IllegalAccessException ex) {
1259 throw new RuntimeException();
1260 }
1261 }
1262 return struct;
1263 }
1264
1265 public boolean putSetting(final String key, Setting value) {
1266 if (value == null) return false;
1267 class PutVisitor implements SettingVisitor {
1268 public boolean changed;
1269 @Override
1270 public void visit(StringSetting setting) {
1271 changed = put(key, setting.getValue());
1272 }
1273 @Override
1274 public void visit(ListSetting setting) {
1275 changed = putCollection(key, setting.getValue());
1276 }
1277 @Override
1278 public void visit(ListListSetting setting) {
1279 @SuppressWarnings("unchecked")
1280 boolean changed = putArray(key, (Collection) setting.getValue());
1281 this.changed = changed;
1282 }
1283 @Override
1284 public void visit(MapListSetting setting) {
1285 changed = putListOfStructs(key, setting.getValue());
1286 }
1287 }
1288 PutVisitor putVisitor = new PutVisitor();
1289 value.visit(putVisitor);
1290 return putVisitor.changed;
1291 }
1292
1293 public Map<String, Setting> getAllSettings() {
1294 Map<String, Setting> settings = new TreeMap<String, Setting>();
1295
1296 for (Entry<String, String> e : properties.entrySet()) {
1297 settings.put(e.getKey(), new StringSetting(e.getValue()));
1298 }
1299 for (Entry<String, List<String>> e : collectionProperties.entrySet()) {
1300 settings.put(e.getKey(), new ListSetting(e.getValue()));
1301 }
1302 for (Entry<String, List<List<String>>> e : arrayProperties.entrySet()) {
1303 settings.put(e.getKey(), new ListListSetting(e.getValue()));
1304 }
1305 for (Entry<String, List<Map<String, String>>> e : listOfStructsProperties.entrySet()) {
1306 settings.put(e.getKey(), new MapListSetting(e.getValue()));
1307 }
1308 return settings;
1309 }
1310
1311 public Map<String, Setting> getAllDefaults() {
1312 Map<String, Setting> allDefaults = new TreeMap<String, Setting>();
1313
1314 for (Entry<String, String> e : defaults.entrySet()) {
1315 allDefaults.put(e.getKey(), new StringSetting(e.getValue()));
1316 }
1317 for (Entry<String, List<String>> e : collectionDefaults.entrySet()) {
1318 allDefaults.put(e.getKey(), new ListSetting(e.getValue()));
1319 }
1320 for (Entry<String, List<List<String>>> e : arrayDefaults.entrySet()) {
1321 allDefaults.put(e.getKey(), new ListListSetting(e.getValue()));
1322 }
1323 for (Entry<String, List<Map<String, String>>> e : listOfStructsDefaults.entrySet()) {
1324 allDefaults.put(e.getKey(), new MapListSetting(e.getValue()));
1325 }
1326 return allDefaults;
1327 }
1328
1329 /**
1330 * Updates system properties with the current values in the preferences.
1331 *
1332 */
1333 public void updateSystemProperties() {
1334 if(getBoolean("prefer.ipv6", false)) {
1335 // never set this to false, only true!
1336 updateSystemProperty("java.net.preferIPv6Addresses", "true");
1337 }
1338 updateSystemProperty("http.agent", Version.getInstance().getAgentString());
1339 updateSystemProperty("user.language", get("language"));
1340 // Workaround to fix a Java bug.
1341 // Force AWT toolkit to update its internal preferences (fix #3645).
1342 // This ugly hack comes from Sun bug database: http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6292739
1343 try {
1344 Field field = Toolkit.class.getDeclaredField("resources");
1345 field.setAccessible(true);
1346 field.set(null, ResourceBundle.getBundle("sun.awt.resources.awt"));
1347 } catch (Exception e) {
1348 // Ignore all exceptions
1349 }
1350 // Workaround to fix another Java bug
1351 // Force Java 7 to use old sorting algorithm of Arrays.sort (fix #8712).
1352 // See Oracle bug database: http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=7075600
1353 // and http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6923200
1354 if (Main.pref.getBoolean("jdk.Arrays.useLegacyMergeSort", !Version.getInstance().isLocalBuild())) {
1355 updateSystemProperty("java.util.Arrays.useLegacyMergeSort", "true");
1356 }
1357 }
1358
1359 private void updateSystemProperty(String key, String value) {
1360 if (value != null) {
1361 System.setProperty(key, value);
1362 }
1363 }
1364
1365 /**
1366 * The default plugin site
1367 */
1368 private final static String[] DEFAULT_PLUGIN_SITE = {
1369 Main.JOSM_WEBSITE+"/plugin%<?plugins=>"};
1370
1371 /**
1372 * Replies the collection of plugin site URLs from where plugin lists can be downloaded
1373 */
1374 public Collection<String> getPluginSites() {
1375 return getCollection("pluginmanager.sites", Arrays.asList(DEFAULT_PLUGIN_SITE));
1376 }
1377
1378 /**
1379 * Sets the collection of plugin site URLs.
1380 *
1381 * @param sites the site URLs
1382 */
1383 public void setPluginSites(Collection<String> sites) {
1384 putCollection("pluginmanager.sites", sites);
1385 }
1386
1387 protected XMLStreamReader parser;
1388
1389 public void validateXML(Reader in) throws Exception {
1390 SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
1391 Schema schema = factory.newSchema(new StreamSource(new MirroredInputStream("resource://data/preferences.xsd")));
1392 Validator validator = schema.newValidator();
1393 validator.validate(new StreamSource(in));
1394 }
1395
1396 public void fromXML(Reader in) throws XMLStreamException {
1397 XMLStreamReader parser = XMLInputFactory.newInstance().createXMLStreamReader(in);
1398 this.parser = parser;
1399 parse();
1400 }
1401
1402 public void parse() throws XMLStreamException {
1403 int event = parser.getEventType();
1404 while (true) {
1405 if (event == XMLStreamConstants.START_ELEMENT) {
1406 parseRoot();
1407 } else if (event == XMLStreamConstants.END_ELEMENT) {
1408 return;
1409 }
1410 if (parser.hasNext()) {
1411 event = parser.next();
1412 } else {
1413 break;
1414 }
1415 }
1416 parser.close();
1417 }
1418
1419 public void parseRoot() throws XMLStreamException {
1420 while (true) {
1421 int event = parser.next();
1422 if (event == XMLStreamConstants.START_ELEMENT) {
1423 if (parser.getLocalName().equals("tag")) {
1424 properties.put(parser.getAttributeValue(null, "key"), parser.getAttributeValue(null, "value"));
1425 jumpToEnd();
1426 } else if (parser.getLocalName().equals("list") ||
1427 parser.getLocalName().equals("collection") ||
1428 parser.getLocalName().equals("lists") ||
1429 parser.getLocalName().equals("maps")
1430 ) {
1431 parseToplevelList();
1432 } else {
1433 throwException("Unexpected element: "+parser.getLocalName());
1434 }
1435 } else if (event == XMLStreamConstants.END_ELEMENT) {
1436 return;
1437 }
1438 }
1439 }
1440
1441 private void jumpToEnd() throws XMLStreamException {
1442 while (true) {
1443 int event = parser.next();
1444 if (event == XMLStreamConstants.START_ELEMENT) {
1445 jumpToEnd();
1446 } else if (event == XMLStreamConstants.END_ELEMENT) {
1447 return;
1448 }
1449 }
1450 }
1451
1452 protected void parseToplevelList() throws XMLStreamException {
1453 String key = parser.getAttributeValue(null, "key");
1454 String name = parser.getLocalName();
1455
1456 List<String> entries = null;
1457 List<List<String>> lists = null;
1458 List<Map<String, String>> maps = null;
1459 while (true) {
1460 int event = parser.next();
1461 if (event == XMLStreamConstants.START_ELEMENT) {
1462 if (parser.getLocalName().equals("entry")) {
1463 if (entries == null) {
1464 entries = new ArrayList<String>();
1465 }
1466 entries.add(parser.getAttributeValue(null, "value"));
1467 jumpToEnd();
1468 } else if (parser.getLocalName().equals("list")) {
1469 if (lists == null) {
1470 lists = new ArrayList<List<String>>();
1471 }
1472 lists.add(parseInnerList());
1473 } else if (parser.getLocalName().equals("map")) {
1474 if (maps == null) {
1475 maps = new ArrayList<Map<String, String>>();
1476 }
1477 maps.add(parseMap());
1478 } else {
1479 throwException("Unexpected element: "+parser.getLocalName());
1480 }
1481 } else if (event == XMLStreamConstants.END_ELEMENT) {
1482 break;
1483 }
1484 }
1485 if (entries != null) {
1486 collectionProperties.put(key, Collections.unmodifiableList(entries));
1487 } else if (lists != null) {
1488 arrayProperties.put(key, Collections.unmodifiableList(lists));
1489 } else if (maps != null) {
1490 listOfStructsProperties.put(key, Collections.unmodifiableList(maps));
1491 } else {
1492 if (name.equals("lists")) {
1493 arrayProperties.put(key, Collections.<List<String>>emptyList());
1494 } else if (name.equals("maps")) {
1495 listOfStructsProperties.put(key, Collections.<Map<String, String>>emptyList());
1496 } else {
1497 collectionProperties.put(key, Collections.<String>emptyList());
1498 }
1499 }
1500 }
1501
1502 protected List<String> parseInnerList() throws XMLStreamException {
1503 List<String> entries = new ArrayList<String>();
1504 while (true) {
1505 int event = parser.next();
1506 if (event == XMLStreamConstants.START_ELEMENT) {
1507 if (parser.getLocalName().equals("entry")) {
1508 entries.add(parser.getAttributeValue(null, "value"));
1509 jumpToEnd();
1510 } else {
1511 throwException("Unexpected element: "+parser.getLocalName());
1512 }
1513 } else if (event == XMLStreamConstants.END_ELEMENT) {
1514 break;
1515 }
1516 }
1517 return Collections.unmodifiableList(entries);
1518 }
1519
1520 protected Map<String, String> parseMap() throws XMLStreamException {
1521 Map<String, String> map = new LinkedHashMap<String, String>();
1522 while (true) {
1523 int event = parser.next();
1524 if (event == XMLStreamConstants.START_ELEMENT) {
1525 if (parser.getLocalName().equals("tag")) {
1526 map.put(parser.getAttributeValue(null, "key"), parser.getAttributeValue(null, "value"));
1527 jumpToEnd();
1528 } else {
1529 throwException("Unexpected element: "+parser.getLocalName());
1530 }
1531 } else if (event == XMLStreamConstants.END_ELEMENT) {
1532 break;
1533 }
1534 }
1535 return Collections.unmodifiableMap(map);
1536 }
1537
1538 protected void throwException(String msg) {
1539 throw new RuntimeException(msg + tr(" (at line {0}, column {1})", parser.getLocation().getLineNumber(), parser.getLocation().getColumnNumber()));
1540 }
1541
1542 private class SettingToXml implements SettingVisitor {
1543 private StringBuilder b;
1544 private boolean noPassword;
1545 private String key;
1546
1547 public SettingToXml(StringBuilder b, boolean noPassword) {
1548 this.b = b;
1549 this.noPassword = noPassword;
1550 }
1551
1552 public void setKey(String key) {
1553 this.key = key;
1554 }
1555
1556 @Override
1557 public void visit(StringSetting setting) {
1558 if (noPassword && key.equals("osm-server.password"))
1559 return; // do not store plain password.
1560 String r = setting.getValue();
1561 String s = defaults.get(key);
1562 /* don't save default values */
1563 if(s == null || !s.equals(r)) {
1564 b.append(" <tag key='");
1565 b.append(XmlWriter.encode(key));
1566 b.append("' value='");
1567 b.append(XmlWriter.encode(setting.getValue()));
1568 b.append("'/>\n");
1569 }
1570 }
1571
1572 @Override
1573 public void visit(ListSetting setting) {
1574 b.append(" <list key='").append(XmlWriter.encode(key)).append("'>\n");
1575 for (String s : setting.getValue()) {
1576 b.append(" <entry value='").append(XmlWriter.encode(s)).append("'/>\n");
1577 }
1578 b.append(" </list>\n");
1579 }
1580
1581 @Override
1582 public void visit(ListListSetting setting) {
1583 b.append(" <lists key='").append(XmlWriter.encode(key)).append("'>\n");
1584 for (List<String> list : setting.getValue()) {
1585 b.append(" <list>\n");
1586 for (String s : list) {
1587 b.append(" <entry value='").append(XmlWriter.encode(s)).append("'/>\n");
1588 }
1589 b.append(" </list>\n");
1590 }
1591 b.append(" </lists>\n");
1592 }
1593
1594 @Override
1595 public void visit(MapListSetting setting) {
1596 b.append(" <maps key='").append(XmlWriter.encode(key)).append("'>\n");
1597 for (Map<String, String> struct : setting.getValue()) {
1598 b.append(" <map>\n");
1599 for (Entry<String, String> e : struct.entrySet()) {
1600 b.append(" <tag key='").append(XmlWriter.encode(e.getKey())).append("' value='").append(XmlWriter.encode(e.getValue())).append("'/>\n");
1601 }
1602 b.append(" </map>\n");
1603 }
1604 b.append(" </maps>\n");
1605 }
1606 }
1607
1608 public String toXML(boolean nopass) {
1609 StringBuilder b = new StringBuilder(
1610 "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
1611 "<preferences xmlns=\""+Main.JOSM_WEBSITE+"/preferences-1.0\" version=\""+
1612 Version.getInstance().getVersion() + "\">\n");
1613 SettingToXml toXml = new SettingToXml(b, nopass);
1614 Map<String, Setting<?>> settings = new TreeMap<String, Setting<?>>();
1615
1616 for (Entry<String, String> e : properties.entrySet()) {
1617 settings.put(e.getKey(), new StringSetting(e.getValue()));
1618 }
1619 for (Entry<String, List<String>> e : collectionProperties.entrySet()) {
1620 settings.put(e.getKey(), new ListSetting(e.getValue()));
1621 }
1622 for (Entry<String, List<List<String>>> e : arrayProperties.entrySet()) {
1623 settings.put(e.getKey(), new ListListSetting(e.getValue()));
1624 }
1625 for (Entry<String, List<Map<String, String>>> e : listOfStructsProperties.entrySet()) {
1626 settings.put(e.getKey(), new MapListSetting(e.getValue()));
1627 }
1628 for (Entry<String, Setting<?>> e : settings.entrySet()) {
1629 toXml.setKey(e.getKey());
1630 e.getValue().visit(toXml);
1631 }
1632 b.append("</preferences>\n");
1633 return b.toString();
1634 }
1635
1636 /**
1637 * Removes obsolete preference settings. If you throw out a once-used preference
1638 * setting, add it to the list here with an expiry date (written as comment). If you
1639 * see something with an expiry date in the past, remove it from the list.
1640 */
1641 public void removeObsolete() {
1642 /* update the data with old consumer key*/
1643 if(getInteger("josm.version", Version.getInstance().getVersion()) < 6076) {
1644 if(!get("oauth.access-token.key").isEmpty() && get("oauth.settings.consumer-key").isEmpty()) {
1645 put("oauth.settings.consumer-key", "AdCRxTpvnbmfV8aPqrTLyA");
1646 put("oauth.settings.consumer-secret", "XmYOiGY9hApytcBC3xCec3e28QBqOWz5g6DSb5UpE");
1647 }
1648 }
1649
1650 String[] obsolete = {
1651 "downloadAlong.downloadAlongTrack.distance", // 07/2013 - can be removed mid-2014. Replaced by downloadAlongWay.distance
1652 "downloadAlong.downloadAlongTrack.area", // 07/2013 - can be removed mid-2014. Replaced by downloadAlongWay.area
1653 "gpxLayer.downloadAlongTrack.distance", // 07/2013 - can be removed mid-2014. Replaced by downloadAlongTrack.distance
1654 "gpxLayer.downloadAlongTrack.area", // 07/2013 - can be removed mid-2014. Replaced by downloadAlongTrack.area
1655 "gpxLayer.downloadAlongTrack.near", // 07/2013 - can be removed mid-2014. Replaced by downloadAlongTrack.near
1656 };
1657 for (String key : obsolete) {
1658 boolean removed = false;
1659 if (properties.containsKey(key)) { properties.remove(key); removed = true; }
1660 if (collectionProperties.containsKey(key)) { collectionProperties.remove(key); removed = true; }
1661 if (arrayProperties.containsKey(key)) { arrayProperties.remove(key); removed = true; }
1662 if (listOfStructsProperties.containsKey(key)) { listOfStructsProperties.remove(key); removed = true; }
1663 if (removed) {
1664 Main.info(tr("Preference setting {0} has been removed since it is no longer used.", key));
1665 }
1666 }
1667 }
1668
1669 public static boolean isEqual(Setting<?> a, Setting<?> b) {
1670 if (a==null && b==null) return true;
1671 if (a==null) return false;
1672 if (b==null) return false;
1673 if (a==b) return true;
1674
1675 if (a instanceof StringSetting)
1676 return (a.getValue().equals(b.getValue()));
1677 if (a instanceof ListSetting) {
1678 @SuppressWarnings("unchecked") Collection<String> aValue = (Collection<String>) a.getValue();
1679 @SuppressWarnings("unchecked") Collection<String> bValue = (Collection<String>) b.getValue();
1680 return equalCollection(aValue, bValue);
1681 }
1682 if (a instanceof ListListSetting) {
1683 @SuppressWarnings("unchecked") Collection<Collection<String>> aValue = (Collection<Collection<String>>) a.getValue();
1684 @SuppressWarnings("unchecked") Collection<List<String>> bValue = (Collection<List<String>>) b.getValue();
1685 return equalArray(aValue, bValue);
1686 }
1687 if (a instanceof MapListSetting) {
1688 @SuppressWarnings("unchecked") Collection<Map<String, String>> aValue = (Collection<Map<String, String>>) a.getValue();
1689 @SuppressWarnings("unchecked") Collection<Map<String, String>> bValue = (Collection<Map<String, String>>) b.getValue();
1690 return equalListOfStructs(aValue, bValue);
1691 }
1692 return a.equals(b);
1693 }
1694
1695}
Note: See TracBrowser for help on using the repository browser.