source: josm/trunk/src/org/openstreetmap/josm/data/CustomConfigurator.java@ 8332

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

fix potential NPEs and Sonar issues related to serialization

  • Property svn:eol-style set to native
File size: 49.6 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.data;
3
4import static org.openstreetmap.josm.tools.I18n.tr;
5
6import java.io.BufferedInputStream;
7import java.io.ByteArrayInputStream;
8import java.io.CharArrayReader;
9import java.io.CharArrayWriter;
10import java.io.File;
11import java.io.FileInputStream;
12import java.io.InputStream;
13import java.nio.charset.StandardCharsets;
14import java.util.ArrayList;
15import java.util.Collection;
16import java.util.Collections;
17import java.util.HashMap;
18import java.util.HashSet;
19import java.util.Iterator;
20import java.util.List;
21import java.util.Map;
22import java.util.Map.Entry;
23import java.util.SortedMap;
24import java.util.TreeMap;
25import java.util.regex.Matcher;
26import java.util.regex.Pattern;
27
28import javax.script.ScriptEngine;
29import javax.script.ScriptEngineManager;
30import javax.script.ScriptException;
31import javax.swing.JOptionPane;
32import javax.swing.SwingUtilities;
33import javax.xml.parsers.DocumentBuilder;
34import javax.xml.parsers.DocumentBuilderFactory;
35import javax.xml.transform.OutputKeys;
36import javax.xml.transform.Transformer;
37import javax.xml.transform.TransformerFactory;
38import javax.xml.transform.dom.DOMSource;
39import javax.xml.transform.stream.StreamResult;
40
41import org.openstreetmap.josm.Main;
42import org.openstreetmap.josm.data.Preferences.ListListSetting;
43import org.openstreetmap.josm.data.Preferences.ListSetting;
44import org.openstreetmap.josm.data.Preferences.MapListSetting;
45import org.openstreetmap.josm.data.Preferences.Setting;
46import org.openstreetmap.josm.data.Preferences.StringSetting;
47import org.openstreetmap.josm.gui.io.DownloadFileTask;
48import org.openstreetmap.josm.plugins.PluginDownloadTask;
49import org.openstreetmap.josm.plugins.PluginInformation;
50import org.openstreetmap.josm.plugins.ReadLocalPluginInformationTask;
51import org.openstreetmap.josm.tools.LanguageInfo;
52import org.openstreetmap.josm.tools.Utils;
53import org.w3c.dom.Document;
54import org.w3c.dom.Element;
55import org.w3c.dom.Node;
56import org.w3c.dom.NodeList;
57
58/**
59 * Class to process configuration changes stored in XML
60 * can be used to modify preferences, store/delete files in .josm folders etc
61 */
62public final class CustomConfigurator {
63
64 private CustomConfigurator() {
65 // Hide default constructor for utils classes
66 }
67
68 private static StringBuilder summary = new StringBuilder();
69
70 public static void log(String fmt, Object... vars) {
71 summary.append(String.format(fmt, vars));
72 }
73
74 public static void log(String s) {
75 summary.append(s);
76 summary.append("\n");
77 }
78
79 public static String getLog() {
80 return summary.toString();
81 }
82
83 public static void readXML(String dir, String fileName) {
84 readXML(new File(dir, fileName));
85 }
86
87 /**
88 * Read configuration script from XML file, modifying given preferences object
89 * @param file - file to open for reading XML
90 * @param prefs - arbitrary Preferences object to modify by script
91 */
92 public static void readXML(final File file, final Preferences prefs) {
93 synchronized(CustomConfigurator.class) {
94 busy=true;
95 }
96 new XMLCommandProcessor(prefs).openAndReadXML(file);
97 synchronized(CustomConfigurator.class) {
98 CustomConfigurator.class.notifyAll();
99 busy=false;
100 }
101 }
102
103 /**
104 * Read configuration script from XML file, modifying main preferences
105 * @param file - file to open for reading XML
106 */
107 public static void readXML(File file) {
108 readXML(file, Main.pref);
109 }
110
111 /**
112 * Downloads file to one of JOSM standard folders
113 * @param address - URL to download
114 * @param path - file path relative to base where to put downloaded file
115 * @param base - only "prefs", "cache" and "plugins" allowed for standard folders
116 */
117 public static void downloadFile(String address, String path, String base) {
118 processDownloadOperation(address, path, getDirectoryByAbbr(base), true, false);
119 }
120
121 /**
122 * Downloads file to one of JOSM standard folders nad unpack it as ZIP/JAR file
123 * @param address - URL to download
124 * @param path - file path relative to base where to put downloaded file
125 * @param base - only "prefs", "cache" and "plugins" allowed for standard folders
126 */
127 public static void downloadAndUnpackFile(String address, String path, String base) {
128 processDownloadOperation(address, path, getDirectoryByAbbr(base), true, true);
129 }
130
131 /**
132 * Downloads file to arbitrary folder
133 * @param address - URL to download
134 * @param path - file path relative to parentDir where to put downloaded file
135 * @param parentDir - folder where to put file
136 * @param mkdir - if true, non-existing directories will be created
137 * @param unzip - if true file wil be unzipped and deleted after download
138 */
139 public static void processDownloadOperation(String address, String path, String parentDir, boolean mkdir, boolean unzip) {
140 String dir = parentDir;
141 if (path.contains("..") || path.startsWith("/") || path.contains(":")) {
142 return; // some basic protection
143 }
144 File fOut = new File(dir, path);
145 DownloadFileTask downloadFileTask = new DownloadFileTask(Main.parent, address, fOut, mkdir, unzip);
146
147 Main.worker.submit(downloadFileTask);
148 log("Info: downloading file from %s to %s in background ", parentDir, fOut.getAbsolutePath());
149 if (unzip) log("and unpacking it"); else log("");
150
151 }
152
153 /**
154 * Simple function to show messageBox, may be used from JS API and from other code
155 * @param type - 'i','w','e','q','p' for Information, Warning, Error, Question, Message
156 * @param text - message to display, HTML allowed
157 */
158 public static void messageBox(String type, String text) {
159 if (type==null || type.isEmpty()) type="plain";
160
161 switch (type.charAt(0)) {
162 case 'i': JOptionPane.showMessageDialog(Main.parent, text, tr("Information"), JOptionPane.INFORMATION_MESSAGE); break;
163 case 'w': JOptionPane.showMessageDialog(Main.parent, text, tr("Warning"), JOptionPane.WARNING_MESSAGE); break;
164 case 'e': JOptionPane.showMessageDialog(Main.parent, text, tr("Error"), JOptionPane.ERROR_MESSAGE); break;
165 case 'q': JOptionPane.showMessageDialog(Main.parent, text, tr("Question"), JOptionPane.QUESTION_MESSAGE); break;
166 case 'p': JOptionPane.showMessageDialog(Main.parent, text, tr("Message"), JOptionPane.PLAIN_MESSAGE); break;
167 }
168 }
169
170 /**
171 * Simple function for choose window, may be used from JS API and from other code
172 * @param text - message to show, HTML allowed
173 * @param opts -
174 * @return number of pressed button, -1 if cancelled
175 */
176 public static int askForOption(String text, String opts) {
177 Integer answer;
178 if (opts.length()>0) {
179 String[] options = opts.split(";");
180 answer = JOptionPane.showOptionDialog(Main.parent, text, "Question", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, 0);
181 } else {
182 answer = JOptionPane.showOptionDialog(Main.parent, text, "Question", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, null, 2);
183 }
184 if (answer==null) return -1; else return answer;
185 }
186
187 public static String askForText(String text) {
188 String s = JOptionPane.showInputDialog(Main.parent, text, tr("Enter text"), JOptionPane.QUESTION_MESSAGE);
189 if (s!=null && (s=s.trim()).length()>0) {
190 return s;
191 } else {
192 return "";
193 }
194 }
195
196 /**
197 * This function exports part of user preferences to specified file.
198 * Default values are not saved.
199 * @param filename - where to export
200 * @param append - if true, resulting file cause appending to exuisting preferences
201 * @param keys - which preferences keys you need to export ("imagery.entries", for example)
202 */
203 public static void exportPreferencesKeysToFile(String filename, boolean append, String... keys) {
204 HashSet<String> keySet = new HashSet<>();
205 Collections.addAll(keySet, keys);
206 exportPreferencesKeysToFile(filename, append, keySet);
207 }
208
209 /**
210 * This function exports part of user preferences to specified file.
211 * Default values are not saved.
212 * Preference keys matching specified pattern are saved
213 * @param fileName - where to export
214 * @param append - if true, resulting file cause appending to exuisting preferences
215 * @param pattern - Regexp pattern forh preferences keys you need to export (".*imagery.*", for example)
216 */
217 public static void exportPreferencesKeysByPatternToFile(String fileName, boolean append, String pattern) {
218 List<String> keySet = new ArrayList<>();
219 Map<String, Setting<?>> allSettings = Main.pref.getAllSettings();
220 for (String key: allSettings.keySet()) {
221 if (key.matches(pattern)) keySet.add(key);
222 }
223 exportPreferencesKeysToFile(fileName, append, keySet);
224 }
225
226 /**
227 * Export specified preferences keys to configuration file
228 * @param filename - name of file
229 * @param append - will the preferences be appended to existing ones when file is imported later. Elsewhere preferences from file will replace existing keys.
230 * @param keys - collection of preferences key names to save
231 */
232 public static void exportPreferencesKeysToFile(String filename, boolean append, Collection<String> keys) {
233 Element root = null;
234 Document document = null;
235 Document exportDocument = null;
236
237 try {
238 String toXML = Main.pref.toXML(true);
239 InputStream is = new ByteArrayInputStream(toXML.getBytes(StandardCharsets.UTF_8));
240 DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
241 builderFactory.setValidating(false);
242 builderFactory.setNamespaceAware(false);
243 DocumentBuilder builder = builderFactory.newDocumentBuilder();
244 document = builder.parse(is);
245 exportDocument = builder.newDocument();
246 root = document.getDocumentElement();
247 } catch (Exception ex) {
248 Main.warn("Error getting preferences to save:" +ex.getMessage());
249 }
250 if (root==null) return;
251 try {
252
253 Element newRoot = exportDocument.createElement("config");
254 exportDocument.appendChild(newRoot);
255
256 Element prefElem = exportDocument.createElement("preferences");
257 prefElem.setAttribute("operation", append?"append":"replace");
258 newRoot.appendChild(prefElem);
259
260 NodeList childNodes = root.getChildNodes();
261 int n = childNodes.getLength();
262 for (int i = 0; i < n ; i++) {
263 Node item = childNodes.item(i);
264 if (item.getNodeType() == Node.ELEMENT_NODE) {
265 String currentKey = ((Element) item).getAttribute("key");
266 if (keys.contains(currentKey)) {
267 Node imported = exportDocument.importNode(item, true);
268 prefElem.appendChild(imported);
269 }
270 }
271 }
272 File f = new File(filename);
273 Transformer ts = TransformerFactory.newInstance().newTransformer();
274 ts.setOutputProperty(OutputKeys.INDENT, "yes");
275 ts.transform(new DOMSource(exportDocument), new StreamResult(f.toURI().getPath()));
276 } catch (Exception ex) {
277 Main.warn("Error saving preferences part:");
278 Main.error(ex);
279 }
280 }
281
282
283 public static void deleteFile(String path, String base) {
284 String dir = getDirectoryByAbbr(base);
285 if (dir==null) {
286 log("Error: Can not find base, use base=cache, base=prefs or base=plugins attribute.");
287 return;
288 }
289 log("Delete file: %s\n", path);
290 if (path.contains("..") || path.startsWith("/") || path.contains(":")) {
291 return; // some basic protection
292 }
293 File fOut = new File(dir, path);
294 if (fOut.exists()) {
295 deleteFileOrDirectory(fOut);
296 }
297 }
298
299 public static void deleteFileOrDirectory(String path) {
300 deleteFileOrDirectory(new File(path));
301 }
302
303 public static void deleteFileOrDirectory(File f) {
304 if (f.isDirectory()) {
305 File[] files = f.listFiles();
306 if (files != null) {
307 for (File f1: files) {
308 deleteFileOrDirectory(f1);
309 }
310 }
311 }
312 try {
313 f.delete();
314 } catch (Exception e) {
315 log("Warning: Can not delete file "+f.getPath()+": "+e.getMessage());
316 }
317 }
318
319 private static boolean busy=false;
320
321
322 public static void pluginOperation(String install, String uninstall, String delete) {
323 final List<String> installList = new ArrayList<>();
324 final List<String> removeList = new ArrayList<>();
325 final List<String> deleteList = new ArrayList<>();
326 Collections.addAll(installList, install.toLowerCase().split(";"));
327 Collections.addAll(removeList, uninstall.toLowerCase().split(";"));
328 Collections.addAll(deleteList, delete.toLowerCase().split(";"));
329 installList.remove("");removeList.remove("");deleteList.remove("");
330
331 if (!installList.isEmpty()) {
332 log("Plugins install: "+installList);
333 }
334 if (!removeList.isEmpty()) {
335 log("Plugins turn off: "+removeList);
336 }
337 if (!deleteList.isEmpty()) {
338 log("Plugins delete: "+deleteList);
339 }
340
341 final ReadLocalPluginInformationTask task = new ReadLocalPluginInformationTask();
342 Runnable r = new Runnable() {
343 @Override
344 public void run() {
345 if (task.isCanceled()) return;
346 synchronized (CustomConfigurator.class) {
347 try { // proceed only after all other tasks were finished
348 while (busy) CustomConfigurator.class.wait();
349 } catch (InterruptedException ex) {
350 Main.warn("InterruptedException while reading local plugin information");
351 }
352
353 SwingUtilities.invokeLater(new Runnable() {
354 @Override
355 public void run() {
356 List<PluginInformation> availablePlugins = task.getAvailablePlugins();
357 List<PluginInformation> toInstallPlugins = new ArrayList<>();
358 List<PluginInformation> toRemovePlugins = new ArrayList<>();
359 List<PluginInformation> toDeletePlugins = new ArrayList<>();
360 for (PluginInformation pi: availablePlugins) {
361 String name = pi.name.toLowerCase();
362 if (installList.contains(name)) toInstallPlugins.add(pi);
363 if (removeList.contains(name)) toRemovePlugins.add(pi);
364 if (deleteList.contains(name)) toDeletePlugins.add(pi);
365 }
366 if (!installList.isEmpty()) {
367 PluginDownloadTask pluginDownloadTask = new PluginDownloadTask(Main.parent, toInstallPlugins, tr ("Installing plugins"));
368 Main.worker.submit(pluginDownloadTask);
369 }
370 Collection<String> pls = new ArrayList<>(Main.pref.getCollection("plugins"));
371 for (PluginInformation pi: toInstallPlugins) {
372 if (!pls.contains(pi.name)) {
373 pls.add(pi.name);
374 }
375 }
376 for (PluginInformation pi: toRemovePlugins) {
377 pls.remove(pi.name);
378 }
379 for (PluginInformation pi: toDeletePlugins) {
380 pls.remove(pi.name);
381 new File(Main.pref.getPluginsDirectory(), pi.name+".jar").deleteOnExit();
382 }
383 Main.pref.putCollection("plugins",pls);
384 }
385 });
386 }
387 }
388
389 };
390 Main.worker.submit(task);
391 Main.worker.submit(r);
392 }
393
394 private static String getDirectoryByAbbr(String base) {
395 String dir;
396 if ("prefs".equals(base) || base.isEmpty()) {
397 dir = Main.pref.getPreferencesDirectory().getAbsolutePath();
398 } else if ("cache".equals(base)) {
399 dir = Main.pref.getCacheDirectory().getAbsolutePath();
400 } else if ("plugins".equals(base)) {
401 dir = Main.pref.getPluginsDirectory().getAbsolutePath();
402 } else {
403 dir = null;
404 }
405 return dir;
406 }
407
408 public static Preferences clonePreferences(Preferences pref) {
409 Preferences tmp = new Preferences();
410 tmp.settingsMap.putAll(pref.settingsMap);
411 tmp.defaultsMap.putAll(pref.defaultsMap);
412 tmp.colornames.putAll( pref.colornames );
413
414 return tmp;
415 }
416
417
418 public static class XMLCommandProcessor {
419
420 private Preferences mainPrefs;
421 private Map<String,Element> tasksMap = new HashMap<>();
422
423 private boolean lastV; // last If condition result
424
425 private ScriptEngine engine;
426
427 public void openAndReadXML(File file) {
428 log("-- Reading custom preferences from " + file.getAbsolutePath() + " --");
429 try {
430 String fileDir = file.getParentFile().getAbsolutePath();
431 if (fileDir!=null) engine.eval("scriptDir='"+normalizeDirName(fileDir) +"';");
432 try (InputStream is = new BufferedInputStream(new FileInputStream(file))) {
433 openAndReadXML(is);
434 }
435 } catch (Exception ex) {
436 log("Error reading custom preferences: " + ex.getMessage());
437 }
438 }
439
440 public void openAndReadXML(InputStream is) {
441 try {
442 DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
443 builderFactory.setValidating(false);
444 builderFactory.setNamespaceAware(true);
445 DocumentBuilder builder = builderFactory.newDocumentBuilder();
446 Document document = builder.parse(is);
447 synchronized (CustomConfigurator.class) {
448 processXML(document);
449 }
450 } catch (Exception ex) {
451 log("Error reading custom preferences: "+ex.getMessage());
452 }
453 log("-- Reading complete --");
454 }
455
456 public XMLCommandProcessor(Preferences mainPrefs) {
457 try {
458 this.mainPrefs = mainPrefs;
459 CustomConfigurator.summary = new StringBuilder();
460 engine = new ScriptEngineManager().getEngineByName("rhino");
461 engine.eval("API={}; API.pref={}; API.fragments={};");
462
463 engine.eval("homeDir='"+normalizeDirName(Main.pref.getPreferencesDirectory().getAbsolutePath()) +"';");
464 engine.eval("josmVersion="+Version.getInstance().getVersion()+";");
465 String className = CustomConfigurator.class.getName();
466 engine.eval("API.messageBox="+className+".messageBox");
467 engine.eval("API.askText=function(text) { return String("+className+".askForText(text));}");
468 engine.eval("API.askOption="+className+".askForOption");
469 engine.eval("API.downloadFile="+className+".downloadFile");
470 engine.eval("API.downloadAndUnpackFile="+className+".downloadAndUnpackFile");
471 engine.eval("API.deleteFile="+className+".deleteFile");
472 engine.eval("API.plugin ="+className+".pluginOperation");
473 engine.eval("API.pluginInstall = function(names) { "+className+".pluginOperation(names,'','');}");
474 engine.eval("API.pluginUninstall = function(names) { "+className+".pluginOperation('',names,'');}");
475 engine.eval("API.pluginDelete = function(names) { "+className+".pluginOperation('','',names);}");
476 } catch (Exception ex) {
477 log("Error: initializing script engine: "+ex.getMessage());
478 }
479 }
480
481 private void processXML(Document document) {
482 Element root = document.getDocumentElement();
483 processXmlFragment(root);
484 }
485
486 private void processXmlFragment(Element root) {
487 NodeList childNodes = root.getChildNodes();
488 int nops = childNodes.getLength();
489 for (int i = 0; i < nops; i++) {
490 Node item = childNodes.item(i);
491 if (item.getNodeType() != Node.ELEMENT_NODE) continue;
492 String elementName = item.getNodeName();
493 Element elem = (Element) item;
494
495 switch(elementName) {
496 case "var":
497 setVar(elem.getAttribute("name"), evalVars(elem.getAttribute("value")));
498 break;
499 case "task":
500 tasksMap.put(elem.getAttribute("name"), elem);
501 break;
502 case "runtask":
503 if (processRunTaskElement(elem)) return;
504 break;
505 case "ask":
506 processAskElement(elem);
507 break;
508 case "if":
509 processIfElement(elem);
510 break;
511 case "else":
512 processElseElement(elem);
513 break;
514 case "break":
515 return;
516 case "plugin":
517 processPluginInstallElement(elem);
518 break;
519 case "messagebox":
520 processMsgBoxElement(elem);
521 break;
522 case "preferences":
523 processPreferencesElement(elem);
524 break;
525 case "download":
526 processDownloadElement(elem);
527 break;
528 case "delete":
529 processDeleteElement(elem);
530 break;
531 case "script":
532 processScriptElement(elem);
533 break;
534 default:
535 log("Error: Unknown element " + elementName);
536 }
537 }
538 }
539
540 private void processPreferencesElement(Element item) {
541 String oper = evalVars(item.getAttribute("operation"));
542 String id = evalVars(item.getAttribute("id"));
543
544 if ("delete-keys".equals(oper)) {
545 String pattern = evalVars(item.getAttribute("pattern"));
546 String key = evalVars(item.getAttribute("key"));
547 if (key != null) {
548 PreferencesUtils.deletePreferenceKey(key, mainPrefs);
549 }
550 if (pattern != null) {
551 PreferencesUtils.deletePreferenceKeyByPattern(pattern, mainPrefs);
552 }
553 return;
554 }
555
556 Preferences tmpPref = readPreferencesFromDOMElement(item);
557 PreferencesUtils.showPrefs(tmpPref);
558
559 if (id.length()>0) {
560 try {
561 String fragmentVar = "API.fragments['"+id+"']";
562 engine.eval(fragmentVar+"={};");
563 PreferencesUtils.loadPrefsToJS(engine, tmpPref, fragmentVar, false);
564 // we store this fragment as API.fragments['id']
565 } catch (ScriptException ex) {
566 log("Error: can not load preferences fragment : "+ex.getMessage());
567 }
568 }
569
570 if ("replace".equals(oper)) {
571 log("Preferences replace: %d keys: %s\n",
572 tmpPref.getAllSettings().size(), tmpPref.getAllSettings().keySet().toString());
573 PreferencesUtils.replacePreferences(tmpPref, mainPrefs);
574 } else if ("append".equals(oper)) {
575 log("Preferences append: %d keys: %s\n",
576 tmpPref.getAllSettings().size(), tmpPref.getAllSettings().keySet().toString());
577 PreferencesUtils.appendPreferences(tmpPref, mainPrefs);
578 } else if ("delete-values".equals(oper)) {
579 PreferencesUtils.deletePreferenceValues(tmpPref, mainPrefs);
580 }
581 }
582
583 private void processDeleteElement(Element item) {
584 String path = evalVars(item.getAttribute("path"));
585 String base = evalVars(item.getAttribute("base"));
586 deleteFile(base, path);
587 }
588
589 private void processDownloadElement(Element item) {
590 String address = evalVars(item.getAttribute("url"));
591 String path = evalVars(item.getAttribute("path"));
592 String unzip = evalVars(item.getAttribute("unzip"));
593 String mkdir = evalVars(item.getAttribute("mkdir"));
594
595 String base = evalVars(item.getAttribute("base"));
596 String dir = getDirectoryByAbbr(base);
597 if (dir==null) {
598 log("Error: Can not find directory to place file, use base=cache, base=prefs or base=plugins attribute.");
599 return;
600 }
601
602 if (path.contains("..") || path.startsWith("/") || path.contains(":")) {
603 return; // some basic protection
604 }
605 if (address == null || path == null || address.length() == 0 || path.length() == 0) {
606 log("Error: Please specify url=\"where to get file\" and path=\"where to place it\"");
607 return;
608 }
609 processDownloadOperation(address, path, dir, "true".equals(mkdir), "true".equals(unzip));
610 }
611
612 private void processPluginInstallElement(Element elem) {
613 String install = elem.getAttribute("install");
614 String uninstall = elem.getAttribute("remove");
615 String delete = elem.getAttribute("delete");
616 pluginOperation(install, uninstall, delete);
617 }
618
619 private void processMsgBoxElement(Element elem) {
620 String text = evalVars(elem.getAttribute("text"));
621 String locText = evalVars(elem.getAttribute(LanguageInfo.getJOSMLocaleCode()+".text"));
622 if (locText!=null && locText.length()>0) text=locText;
623
624 String type = evalVars(elem.getAttribute("type"));
625 messageBox(type, text);
626 }
627
628 private void processAskElement(Element elem) {
629 String text = evalVars(elem.getAttribute("text"));
630 String locText = evalVars(elem.getAttribute(LanguageInfo.getJOSMLocaleCode()+".text"));
631 if (locText.length()>0) text=locText;
632 String var = elem.getAttribute("var");
633 if (var.isEmpty()) var="result";
634
635 String input = evalVars(elem.getAttribute("input"));
636 if ("true".equals(input)) {
637 setVar(var, askForText(text));
638 } else {
639 String opts = evalVars(elem.getAttribute("options"));
640 String locOpts = evalVars(elem.getAttribute(LanguageInfo.getJOSMLocaleCode()+".options"));
641 if (locOpts.length()>0) opts=locOpts;
642 setVar(var, String.valueOf(askForOption(text, opts)));
643 }
644 }
645
646 public void setVar(String name, String value) {
647 try {
648 engine.eval(name+"='"+value+"';");
649 } catch (ScriptException ex) {
650 log("Error: Can not assign variable: %s=%s : %s\n", name, value, ex.getMessage());
651 }
652 }
653
654 private void processIfElement(Element elem) {
655 String realValue = evalVars(elem.getAttribute("test"));
656 boolean v=false;
657 if ("true".equals(realValue)) v=true; else
658 if ("fales".equals(realValue)) v=true; else
659 {
660 log("Error: Illegal test expression in if: %s=%s\n", elem.getAttribute("test"), realValue);
661 }
662
663 if (v) processXmlFragment(elem);
664 lastV = v;
665 }
666
667 private void processElseElement(Element elem) {
668 if (!lastV) {
669 processXmlFragment(elem);
670 }
671 }
672
673 private boolean processRunTaskElement(Element elem) {
674 String taskName = elem.getAttribute("name");
675 Element task = tasksMap.get(taskName);
676 if (task!=null) {
677 log("EXECUTING TASK "+taskName);
678 processXmlFragment(task); // process task recursively
679 } else {
680 log("Error: Can not execute task "+taskName);
681 return true;
682 }
683 return false;
684 }
685
686 private void processScriptElement(Element elem) {
687 String js = elem.getChildNodes().item(0).getTextContent();
688 log("Processing script...");
689 try {
690 PreferencesUtils.modifyPreferencesByScript(engine, mainPrefs, js);
691 } catch (ScriptException ex) {
692 messageBox("e", ex.getMessage());
693 log("JS error: "+ex.getMessage());
694 }
695 log("Script finished");
696 }
697
698 /**
699 * substitute ${expression} = expression evaluated by JavaScript
700 */
701 private String evalVars(String s) {
702 Pattern p = Pattern.compile("\\$\\{([^\\}]*)\\}");
703 Matcher mr = p.matcher(s);
704 StringBuffer sb = new StringBuffer();
705 while (mr.find()) {
706 try {
707 String result = engine.eval(mr.group(1)).toString();
708 mr.appendReplacement(sb, result);
709 } catch (ScriptException ex) {
710 log("Error: Can not evaluate expression %s : %s", mr.group(1), ex.getMessage());
711 }
712 }
713 mr.appendTail(sb);
714 return sb.toString();
715 }
716
717 private Preferences readPreferencesFromDOMElement(Element item) {
718 Preferences tmpPref = new Preferences();
719 try {
720 Transformer xformer = TransformerFactory.newInstance().newTransformer();
721 CharArrayWriter outputWriter = new CharArrayWriter(8192);
722 StreamResult out = new StreamResult(outputWriter);
723
724 xformer.transform(new DOMSource(item), out);
725
726 String fragmentWithReplacedVars= evalVars(outputWriter.toString());
727
728 CharArrayReader reader = new CharArrayReader(fragmentWithReplacedVars.toCharArray());
729 tmpPref.fromXML(reader);
730 } catch (Exception ex) {
731 log("Error: can not read XML fragment :" + ex.getMessage());
732 }
733
734 return tmpPref;
735 }
736
737 private String normalizeDirName(String dir) {
738 String s = dir.replace("\\", "/");
739 if (s.endsWith("/")) s=s.substring(0,s.length()-1);
740 return s;
741 }
742 }
743
744 /**
745 * Helper class to do specific Preferences operation - appending, replacing,
746 * deletion by key and by value
747 * Also contains functions that convert preferences object to JavaScript object and back
748 */
749 public static final class PreferencesUtils {
750
751 private PreferencesUtils() {
752 // Hide implicit public constructor for utility class
753 }
754
755 private static void replacePreferences(Preferences fragment, Preferences mainpref) {
756 for (Entry<String, Setting<?>> entry: fragment.settingsMap.entrySet()) {
757 mainpref.putSetting(entry.getKey(), entry.getValue());
758 }
759 }
760
761 private static void appendPreferences(Preferences fragment, Preferences mainpref) {
762 for (Entry<String, Setting<?>> entry: fragment.settingsMap.entrySet()) {
763 String key = entry.getKey();
764 if (entry.getValue() instanceof StringSetting) {
765 mainpref.putSetting(key, entry.getValue());
766 } else if (entry.getValue() instanceof ListSetting) {
767 ListSetting lSetting = (ListSetting) entry.getValue();
768 Collection<String> newItems = getCollection(mainpref, key, true);
769 if (newItems == null) continue;
770 for (String item : lSetting.getValue()) {
771 // add nonexisting elements to then list
772 if (!newItems.contains(item)) {
773 newItems.add(item);
774 }
775 }
776 mainpref.putCollection(key, newItems);
777 } else if (entry.getValue() instanceof ListListSetting) {
778 ListListSetting llSetting = (ListListSetting) entry.getValue();
779 Collection<Collection<String>> newLists = getArray(mainpref, key, true);
780 if (newLists == null) continue;
781
782 for (Collection<String> list : llSetting.getValue()) {
783 // add nonexisting list (equals comparison for lists is used implicitly)
784 if (!newLists.contains(list)) {
785 newLists.add(list);
786 }
787 }
788 mainpref.putArray(key, newLists);
789 } else if (entry.getValue() instanceof MapListSetting) {
790 MapListSetting mlSetting = (MapListSetting) entry.getValue();
791 List<Map<String, String>> newMaps = getListOfStructs(mainpref, key, true);
792 if (newMaps == null) continue;
793
794 // get existing properties as list of maps
795
796 for (Map<String, String> map : mlSetting.getValue()) {
797 // add nonexisting map (equals comparison for maps is used implicitly)
798 if (!newMaps.contains(map)) {
799 newMaps.add(map);
800 }
801 }
802 mainpref.putListOfStructs(entry.getKey(), newMaps);
803 }
804 }
805 }
806
807 /**
808 * Delete items from @param mainpref collections that match items from @param fragment collections
809 */
810 private static void deletePreferenceValues(Preferences fragment, Preferences mainpref) {
811
812 for (Entry<String, Setting<?>> entry : fragment.settingsMap.entrySet()) {
813 String key = entry.getKey();
814 if (entry.getValue() instanceof StringSetting) {
815 StringSetting sSetting = (StringSetting) entry.getValue();
816 // if mentioned value found, delete it
817 if (sSetting.equals(mainpref.settingsMap.get(key))) {
818 mainpref.put(key, null);
819 }
820 } else if (entry.getValue() instanceof ListSetting) {
821 ListSetting lSetting = (ListSetting) entry.getValue();
822 Collection<String> newItems = getCollection(mainpref, key, true);
823 if (newItems == null) continue;
824
825 // remove mentioned items from collection
826 for (String item : lSetting.getValue()) {
827 log("Deleting preferences: from list %s: %s\n", key, item);
828 newItems.remove(item);
829 }
830 mainpref.putCollection(entry.getKey(), newItems);
831 } else if (entry.getValue() instanceof ListListSetting) {
832 ListListSetting llSetting = (ListListSetting) entry.getValue();
833 Collection<Collection<String>> newLists = getArray(mainpref, key, true);
834 if (newLists == null) continue;
835
836 // if items are found in one of lists, remove that list!
837 Iterator<Collection<String>> listIterator = newLists.iterator();
838 while (listIterator.hasNext()) {
839 Collection<String> list = listIterator.next();
840 for (Collection<String> removeList : llSetting.getValue()) {
841 if (list.containsAll(removeList)) {
842 // remove current list, because it matches search criteria
843 log("Deleting preferences: list from lists %s: %s\n", key, list);
844 listIterator.remove();
845 }
846 }
847 }
848
849 mainpref.putArray(key, newLists);
850 } else if (entry.getValue() instanceof MapListSetting) {
851 MapListSetting mlSetting = (MapListSetting) entry.getValue();
852 List<Map<String, String>> newMaps = getListOfStructs(mainpref, key, true);
853 if (newMaps == null) continue;
854
855 Iterator<Map<String, String>> mapIterator = newMaps.iterator();
856 while (mapIterator.hasNext()) {
857 Map<String, String> map = mapIterator.next();
858 for (Map<String, String> removeMap : mlSetting.getValue()) {
859 if (map.entrySet().containsAll(removeMap.entrySet())) {
860 // the map contain all mentioned key-value pair, so it should be deleted from "maps"
861 log("Deleting preferences: deleting map from maps %s: %s\n", key, map);
862 mapIterator.remove();
863 }
864 }
865 }
866 mainpref.putListOfStructs(entry.getKey(), newMaps);
867 }
868 }
869 }
870
871 private static void deletePreferenceKeyByPattern(String pattern, Preferences pref) {
872 Map<String, Setting<?>> allSettings = pref.getAllSettings();
873 for (Entry<String, Setting<?>> entry : allSettings.entrySet()) {
874 String key = entry.getKey();
875 if (key.matches(pattern)) {
876 log("Deleting preferences: deleting key from preferences: " + key);
877 pref.putSetting(key, null);
878 }
879 }
880 }
881
882 private static void deletePreferenceKey(String key, Preferences pref) {
883 Map<String, Setting<?>> allSettings = pref.getAllSettings();
884 if (allSettings.containsKey(key)) {
885 log("Deleting preferences: deleting key from preferences: " + key);
886 pref.putSetting(key, null);
887 }
888 }
889
890 private static Collection<String> getCollection(Preferences mainpref, String key, boolean warnUnknownDefault) {
891 ListSetting existing = Utils.cast(mainpref.settingsMap.get(key), ListSetting.class);
892 ListSetting defaults = Utils.cast(mainpref.defaultsMap.get(key), ListSetting.class);
893 if (existing == null && defaults == null) {
894 if (warnUnknownDefault) defaultUnknownWarning(key);
895 return null;
896 }
897 if (existing != null)
898 return new ArrayList<>(existing.getValue());
899 else
900 return defaults.getValue() == null ? null : new ArrayList<>(defaults.getValue());
901 }
902
903 private static Collection<Collection<String>> getArray(Preferences mainpref, String key, boolean warnUnknownDefault) {
904 ListListSetting existing = Utils.cast(mainpref.settingsMap.get(key), ListListSetting.class);
905 ListListSetting defaults = Utils.cast(mainpref.defaultsMap.get(key), ListListSetting.class);
906
907 if (existing == null && defaults == null) {
908 if (warnUnknownDefault) defaultUnknownWarning(key);
909 return null;
910 }
911 if (existing != null)
912 return new ArrayList<Collection<String>>(existing.getValue());
913 else
914 return defaults.getValue() == null ? null : new ArrayList<Collection<String>>(defaults.getValue());
915 }
916
917 private static List<Map<String, String>> getListOfStructs(Preferences mainpref, String key, boolean warnUnknownDefault) {
918 MapListSetting existing = Utils.cast(mainpref.settingsMap.get(key), MapListSetting.class);
919 MapListSetting defaults = Utils.cast(mainpref.settingsMap.get(key), MapListSetting.class);
920
921 if (existing == null && defaults == null) {
922 if (warnUnknownDefault) defaultUnknownWarning(key);
923 return null;
924 }
925
926 if (existing != null)
927 return new ArrayList<>(existing.getValue());
928 else
929 return defaults.getValue() == null ? null : new ArrayList<>(defaults.getValue());
930 }
931
932 private static void defaultUnknownWarning(String key) {
933 log("Warning: Unknown default value of %s , skipped\n", key);
934 JOptionPane.showMessageDialog(
935 Main.parent,
936 tr("<html>Settings file asks to append preferences to <b>{0}</b>,<br/> but its default value is unknown at this moment.<br/> Please activate corresponding function manually and retry importing.", key),
937 tr("Warning"),
938 JOptionPane.WARNING_MESSAGE);
939 }
940
941 private static void showPrefs(Preferences tmpPref) {
942 Main.info("properties: " + tmpPref.settingsMap);
943 }
944
945 private static void modifyPreferencesByScript(ScriptEngine engine, Preferences tmpPref, String js) throws ScriptException {
946 loadPrefsToJS(engine, tmpPref, "API.pref", true);
947 engine.eval(js);
948 readPrefsFromJS(engine, tmpPref, "API.pref");
949 }
950
951 /**
952 * Convert JavaScript preferences object to preferences data structures
953 * @param engine - JS engine to put object
954 * @param tmpPref - preferences to fill from JS
955 * @param varInJS - JS variable name, where preferences are stored
956 * @throws ScriptException
957 */
958 public static void readPrefsFromJS(ScriptEngine engine, Preferences tmpPref, String varInJS) throws ScriptException {
959 String finish =
960 "stringMap = new java.util.TreeMap ;"+
961 "listMap = new java.util.TreeMap ;"+
962 "listlistMap = new java.util.TreeMap ;"+
963 "listmapMap = new java.util.TreeMap ;"+
964 "for (key in "+varInJS+") {"+
965 " val = "+varInJS+"[key];"+
966 " type = typeof val == 'string' ? 'string' : val.type;"+
967 " if (type == 'string') {"+
968 " stringMap.put(key, val);"+
969 " } else if (type == 'list') {"+
970 " l = new java.util.ArrayList;"+
971 " for (i=0; i<val.length; i++) {"+
972 " l.add(java.lang.String.valueOf(val[i]));"+
973 " }"+
974 " listMap.put(key, l);"+
975 " } else if (type == 'listlist') {"+
976 " l = new java.util.ArrayList;"+
977 " for (i=0; i<val.length; i++) {"+
978 " list=val[i];"+
979 " jlist=new java.util.ArrayList;"+
980 " for (j=0; j<list.length; j++) {"+
981 " jlist.add(java.lang.String.valueOf(list[j]));"+
982 " }"+
983 " l.add(jlist);"+
984 " }"+
985 " listlistMap.put(key, l);"+
986 " } else if (type == 'listmap') {"+
987 " l = new java.util.ArrayList;"+
988 " for (i=0; i<val.length; i++) {"+
989 " map=val[i];"+
990 " jmap=new java.util.TreeMap;"+
991 " for (var key2 in map) {"+
992 " jmap.put(key2,java.lang.String.valueOf(map[key2]));"+
993 " }"+
994 " l.add(jmap);"+
995 " }"+
996 " listmapMap.put(key, l);"+
997 " } else {" +
998 " org.openstreetmap.josm.data.CustomConfigurator.log('Unknown type:'+val.type+ '- use list, listlist or listmap'); }"+
999 " }";
1000 engine.eval(finish);
1001
1002 @SuppressWarnings("unchecked")
1003 Map<String, String> stringMap = (Map<String, String>) engine.get("stringMap");
1004 @SuppressWarnings("unchecked")
1005 Map<String, List<String>> listMap = (SortedMap<String, List<String>> ) engine.get("listMap");
1006 @SuppressWarnings("unchecked")
1007 Map<String, List<Collection<String>>> listlistMap = (SortedMap<String, List<Collection<String>>>) engine.get("listlistMap");
1008 @SuppressWarnings("unchecked")
1009 Map<String, List<Map<String, String>>> listmapMap = (SortedMap<String, List<Map<String,String>>>) engine.get("listmapMap");
1010
1011 tmpPref.settingsMap.clear();
1012
1013 Map<String, Setting<?>> tmp = new HashMap<>();
1014 for (Entry<String, String> e : stringMap.entrySet()) {
1015 tmp.put(e.getKey(), new StringSetting(e.getValue()));
1016 }
1017 for (Entry<String, List<String>> e : listMap.entrySet()) {
1018 tmp.put(e.getKey(), new ListSetting(e.getValue()));
1019 }
1020
1021 for (Entry<String, List<Collection<String>>> e : listlistMap.entrySet()) {
1022 @SuppressWarnings("unchecked")
1023 List<List<String>> value = (List)e.getValue();
1024 tmp.put(e.getKey(), new ListListSetting(value));
1025 }
1026 for (Entry<String, List<Map<String, String>>> e : listmapMap.entrySet()) {
1027 tmp.put(e.getKey(), new MapListSetting(e.getValue()));
1028 }
1029 for (Entry<String, Setting<?>> e : tmp.entrySet()) {
1030 if (e.getValue().equals(tmpPref.defaultsMap.get(e.getKey()))) continue;
1031 tmpPref.settingsMap.put(e.getKey(), e.getValue());
1032 }
1033 }
1034
1035 /**
1036 * Convert preferences data structures to JavaScript object
1037 * @param engine - JS engine to put object
1038 * @param tmpPref - preferences to convert
1039 * @param whereToPutInJS - variable name to store preferences in JS
1040 * @param includeDefaults - include known default values to JS objects
1041 * @throws ScriptException
1042 */
1043 public static void loadPrefsToJS(ScriptEngine engine, Preferences tmpPref, String whereToPutInJS, boolean includeDefaults) throws ScriptException {
1044 Map<String, String> stringMap = new TreeMap<>();
1045 Map<String, List<String>> listMap = new TreeMap<>();
1046 Map<String, List<List<String>>> listlistMap = new TreeMap<>();
1047 Map<String, List<Map<String, String>>> listmapMap = new TreeMap<>();
1048
1049 if (includeDefaults) {
1050 for (Map.Entry<String, Setting<?>> e: tmpPref.defaultsMap.entrySet()) {
1051 Setting<?> setting = e.getValue();
1052 if (setting instanceof StringSetting) {
1053 stringMap.put(e.getKey(), ((StringSetting) setting).getValue());
1054 } else if (setting instanceof ListSetting) {
1055 listMap.put(e.getKey(), ((ListSetting) setting).getValue());
1056 } else if (setting instanceof ListListSetting) {
1057 listlistMap.put(e.getKey(), ((ListListSetting) setting).getValue());
1058 } else if (setting instanceof MapListSetting) {
1059 listmapMap.put(e.getKey(), ((MapListSetting) setting).getValue());
1060 }
1061 }
1062 }
1063 Iterator<Map.Entry<String, Setting<?>>> it = tmpPref.settingsMap.entrySet().iterator();
1064 while (it.hasNext()) {
1065 Map.Entry<String, Setting<?>> e = it.next();
1066 if (e.getValue().getValue() == null) {
1067 it.remove();
1068 }
1069 }
1070
1071 for (Map.Entry<String, Setting<?>> e: tmpPref.settingsMap.entrySet()) {
1072 Setting<?> setting = e.getValue();
1073 if (setting instanceof StringSetting) {
1074 stringMap.put(e.getKey(), ((StringSetting) setting).getValue());
1075 } else if (setting instanceof ListSetting) {
1076 listMap.put(e.getKey(), ((ListSetting) setting).getValue());
1077 } else if (setting instanceof ListListSetting) {
1078 listlistMap.put(e.getKey(), ((ListListSetting) setting).getValue());
1079 } else if (setting instanceof MapListSetting) {
1080 listmapMap.put(e.getKey(), ((MapListSetting) setting).getValue());
1081 }
1082 }
1083
1084 engine.put("stringMap", stringMap);
1085 engine.put("listMap", listMap);
1086 engine.put("listlistMap", listlistMap);
1087 engine.put("listmapMap", listmapMap);
1088
1089 String init =
1090 "function getJSList( javaList ) {"+
1091 " var jsList; var i; "+
1092 " if (javaList == null) return null;"+
1093 "jsList = [];"+
1094 " for (i = 0; i < javaList.size(); i++) {"+
1095 " jsList.push(String(list.get(i)));"+
1096 " }"+
1097 "return jsList;"+
1098 "}"+
1099 "function getJSMap( javaMap ) {"+
1100 " var jsMap; var it; var e; "+
1101 " if (javaMap == null) return null;"+
1102 " jsMap = {};"+
1103 " for (it = javaMap.entrySet().iterator(); it.hasNext();) {"+
1104 " e = it.next();"+
1105 " jsMap[ String(e.getKey()) ] = String(e.getValue()); "+
1106 " }"+
1107 " return jsMap;"+
1108 "}"+
1109 "for (it = stringMap.entrySet().iterator(); it.hasNext();) {"+
1110 " e = it.next();"+
1111 whereToPutInJS+"[String(e.getKey())] = String(e.getValue());"+
1112 "}\n"+
1113 "for (it = listMap.entrySet().iterator(); it.hasNext();) {"+
1114 " e = it.next();"+
1115 " list = e.getValue();"+
1116 " jslist = getJSList(list);"+
1117 " jslist.type = 'list';"+
1118 whereToPutInJS+"[String(e.getKey())] = jslist;"+
1119 "}\n"+
1120 "for (it = listlistMap.entrySet().iterator(); it.hasNext(); ) {"+
1121 " e = it.next();"+
1122 " listlist = e.getValue();"+
1123 " jslistlist = [];"+
1124 " for (it2 = listlist.iterator(); it2.hasNext(); ) {"+
1125 " list = it2.next(); "+
1126 " jslistlist.push(getJSList(list));"+
1127 " }"+
1128 " jslistlist.type = 'listlist';"+
1129 whereToPutInJS+"[String(e.getKey())] = jslistlist;"+
1130 "}\n"+
1131 "for (it = listmapMap.entrySet().iterator(); it.hasNext();) {"+
1132 " e = it.next();"+
1133 " listmap = e.getValue();"+
1134 " jslistmap = [];"+
1135 " for (it2 = listmap.iterator(); it2.hasNext();) {"+
1136 " map = it2.next();"+
1137 " jslistmap.push(getJSMap(map));"+
1138 " }"+
1139 " jslistmap.type = 'listmap';"+
1140 whereToPutInJS+"[String(e.getKey())] = jslistmap;"+
1141 "}\n";
1142
1143 // Execute conversion script
1144 engine.eval(init);
1145 }
1146 }
1147}
Note: See TracBrowser for help on using the repository browser.