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

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

fix sonar squid:S2039 - Member variable visibility should be specified

  • Property svn:eol-style set to native
File size: 49.5 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 for (File f1: f.listFiles()) {
306 deleteFileOrDirectory(f1);
307 }
308 }
309 try {
310 f.delete();
311 } catch (Exception e) {
312 log("Warning: Can not delete file "+f.getPath());
313 }
314 }
315
316 private static boolean busy=false;
317
318
319 public static void pluginOperation(String install, String uninstall, String delete) {
320 final List<String> installList = new ArrayList<>();
321 final List<String> removeList = new ArrayList<>();
322 final List<String> deleteList = new ArrayList<>();
323 Collections.addAll(installList, install.toLowerCase().split(";"));
324 Collections.addAll(removeList, uninstall.toLowerCase().split(";"));
325 Collections.addAll(deleteList, delete.toLowerCase().split(";"));
326 installList.remove("");removeList.remove("");deleteList.remove("");
327
328 if (!installList.isEmpty()) {
329 log("Plugins install: "+installList);
330 }
331 if (!removeList.isEmpty()) {
332 log("Plugins turn off: "+removeList);
333 }
334 if (!deleteList.isEmpty()) {
335 log("Plugins delete: "+deleteList);
336 }
337
338 final ReadLocalPluginInformationTask task = new ReadLocalPluginInformationTask();
339 Runnable r = new Runnable() {
340 @Override
341 public void run() {
342 if (task.isCanceled()) return;
343 synchronized (CustomConfigurator.class) {
344 try { // proceed only after all other tasks were finished
345 while (busy) CustomConfigurator.class.wait();
346 } catch (InterruptedException ex) {
347 Main.warn("InterruptedException while reading local plugin information");
348 }
349
350 SwingUtilities.invokeLater(new Runnable() {
351 @Override
352 public void run() {
353 List<PluginInformation> availablePlugins = task.getAvailablePlugins();
354 List<PluginInformation> toInstallPlugins = new ArrayList<>();
355 List<PluginInformation> toRemovePlugins = new ArrayList<>();
356 List<PluginInformation> toDeletePlugins = new ArrayList<>();
357 for (PluginInformation pi: availablePlugins) {
358 String name = pi.name.toLowerCase();
359 if (installList.contains(name)) toInstallPlugins.add(pi);
360 if (removeList.contains(name)) toRemovePlugins.add(pi);
361 if (deleteList.contains(name)) toDeletePlugins.add(pi);
362 }
363 if (!installList.isEmpty()) {
364 PluginDownloadTask pluginDownloadTask = new PluginDownloadTask(Main.parent, toInstallPlugins, tr ("Installing plugins"));
365 Main.worker.submit(pluginDownloadTask);
366 }
367 Collection<String> pls = new ArrayList<>(Main.pref.getCollection("plugins"));
368 for (PluginInformation pi: toInstallPlugins) {
369 if (!pls.contains(pi.name)) {
370 pls.add(pi.name);
371 }
372 }
373 for (PluginInformation pi: toRemovePlugins) {
374 pls.remove(pi.name);
375 }
376 for (PluginInformation pi: toDeletePlugins) {
377 pls.remove(pi.name);
378 new File(Main.pref.getPluginsDirectory(), pi.name+".jar").deleteOnExit();
379 }
380 Main.pref.putCollection("plugins",pls);
381 }
382 });
383 }
384 }
385
386 };
387 Main.worker.submit(task);
388 Main.worker.submit(r);
389 }
390
391 private static String getDirectoryByAbbr(String base) {
392 String dir;
393 if ("prefs".equals(base) || base.isEmpty()) {
394 dir = Main.pref.getPreferencesDirectory().getAbsolutePath();
395 } else if ("cache".equals(base)) {
396 dir = Main.pref.getCacheDirectory().getAbsolutePath();
397 } else if ("plugins".equals(base)) {
398 dir = Main.pref.getPluginsDirectory().getAbsolutePath();
399 } else {
400 dir = null;
401 }
402 return dir;
403 }
404
405 public static Preferences clonePreferences(Preferences pref) {
406 Preferences tmp = new Preferences();
407 tmp.settingsMap.putAll(pref.settingsMap);
408 tmp.defaultsMap.putAll(pref.defaultsMap);
409 tmp.colornames.putAll( pref.colornames );
410
411 return tmp;
412 }
413
414
415 public static class XMLCommandProcessor {
416
417 private Preferences mainPrefs;
418 private Map<String,Element> tasksMap = new HashMap<>();
419
420 private boolean lastV; // last If condition result
421
422 private ScriptEngine engine;
423
424 public void openAndReadXML(File file) {
425 log("-- Reading custom preferences from " + file.getAbsolutePath() + " --");
426 try {
427 String fileDir = file.getParentFile().getAbsolutePath();
428 if (fileDir!=null) engine.eval("scriptDir='"+normalizeDirName(fileDir) +"';");
429 try (InputStream is = new BufferedInputStream(new FileInputStream(file))) {
430 openAndReadXML(is);
431 }
432 } catch (Exception ex) {
433 log("Error reading custom preferences: " + ex.getMessage());
434 }
435 }
436
437 public void openAndReadXML(InputStream is) {
438 try {
439 DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
440 builderFactory.setValidating(false);
441 builderFactory.setNamespaceAware(true);
442 DocumentBuilder builder = builderFactory.newDocumentBuilder();
443 Document document = builder.parse(is);
444 synchronized (CustomConfigurator.class) {
445 processXML(document);
446 }
447 } catch (Exception ex) {
448 log("Error reading custom preferences: "+ex.getMessage());
449 }
450 log("-- Reading complete --");
451 }
452
453 public XMLCommandProcessor(Preferences mainPrefs) {
454 try {
455 this.mainPrefs = mainPrefs;
456 CustomConfigurator.summary = new StringBuilder();
457 engine = new ScriptEngineManager().getEngineByName("rhino");
458 engine.eval("API={}; API.pref={}; API.fragments={};");
459
460 engine.eval("homeDir='"+normalizeDirName(Main.pref.getPreferencesDirectory().getAbsolutePath()) +"';");
461 engine.eval("josmVersion="+Version.getInstance().getVersion()+";");
462 String className = CustomConfigurator.class.getName();
463 engine.eval("API.messageBox="+className+".messageBox");
464 engine.eval("API.askText=function(text) { return String("+className+".askForText(text));}");
465 engine.eval("API.askOption="+className+".askForOption");
466 engine.eval("API.downloadFile="+className+".downloadFile");
467 engine.eval("API.downloadAndUnpackFile="+className+".downloadAndUnpackFile");
468 engine.eval("API.deleteFile="+className+".deleteFile");
469 engine.eval("API.plugin ="+className+".pluginOperation");
470 engine.eval("API.pluginInstall = function(names) { "+className+".pluginOperation(names,'','');}");
471 engine.eval("API.pluginUninstall = function(names) { "+className+".pluginOperation('',names,'');}");
472 engine.eval("API.pluginDelete = function(names) { "+className+".pluginOperation('','',names);}");
473 } catch (Exception ex) {
474 log("Error: initializing script engine: "+ex.getMessage());
475 }
476 }
477
478 private void processXML(Document document) {
479 Element root = document.getDocumentElement();
480 processXmlFragment(root);
481 }
482
483 private void processXmlFragment(Element root) {
484 NodeList childNodes = root.getChildNodes();
485 int nops = childNodes.getLength();
486 for (int i = 0; i < nops; i++) {
487 Node item = childNodes.item(i);
488 if (item.getNodeType() != Node.ELEMENT_NODE) continue;
489 String elementName = item.getNodeName();
490 Element elem = (Element) item;
491
492 switch(elementName) {
493 case "var":
494 setVar(elem.getAttribute("name"), evalVars(elem.getAttribute("value")));
495 break;
496 case "task":
497 tasksMap.put(elem.getAttribute("name"), elem);
498 break;
499 case "runtask":
500 if (processRunTaskElement(elem)) return;
501 break;
502 case "ask":
503 processAskElement(elem);
504 break;
505 case "if":
506 processIfElement(elem);
507 break;
508 case "else":
509 processElseElement(elem);
510 break;
511 case "break":
512 return;
513 case "plugin":
514 processPluginInstallElement(elem);
515 break;
516 case "messagebox":
517 processMsgBoxElement(elem);
518 break;
519 case "preferences":
520 processPreferencesElement(elem);
521 break;
522 case "download":
523 processDownloadElement(elem);
524 break;
525 case "delete":
526 processDeleteElement(elem);
527 break;
528 case "script":
529 processScriptElement(elem);
530 break;
531 default:
532 log("Error: Unknown element " + elementName);
533 }
534 }
535 }
536
537 private void processPreferencesElement(Element item) {
538 String oper = evalVars(item.getAttribute("operation"));
539 String id = evalVars(item.getAttribute("id"));
540
541 if ("delete-keys".equals(oper)) {
542 String pattern = evalVars(item.getAttribute("pattern"));
543 String key = evalVars(item.getAttribute("key"));
544 if (key != null) {
545 PreferencesUtils.deletePreferenceKey(key, mainPrefs);
546 }
547 if (pattern != null) {
548 PreferencesUtils.deletePreferenceKeyByPattern(pattern, mainPrefs);
549 }
550 return;
551 }
552
553 Preferences tmpPref = readPreferencesFromDOMElement(item);
554 PreferencesUtils.showPrefs(tmpPref);
555
556 if (id.length()>0) {
557 try {
558 String fragmentVar = "API.fragments['"+id+"']";
559 engine.eval(fragmentVar+"={};");
560 PreferencesUtils.loadPrefsToJS(engine, tmpPref, fragmentVar, false);
561 // we store this fragment as API.fragments['id']
562 } catch (ScriptException ex) {
563 log("Error: can not load preferences fragment : "+ex.getMessage());
564 }
565 }
566
567 if ("replace".equals(oper)) {
568 log("Preferences replace: %d keys: %s\n",
569 tmpPref.getAllSettings().size(), tmpPref.getAllSettings().keySet().toString());
570 PreferencesUtils.replacePreferences(tmpPref, mainPrefs);
571 } else if ("append".equals(oper)) {
572 log("Preferences append: %d keys: %s\n",
573 tmpPref.getAllSettings().size(), tmpPref.getAllSettings().keySet().toString());
574 PreferencesUtils.appendPreferences(tmpPref, mainPrefs);
575 } else if ("delete-values".equals(oper)) {
576 PreferencesUtils.deletePreferenceValues(tmpPref, mainPrefs);
577 }
578 }
579
580 private void processDeleteElement(Element item) {
581 String path = evalVars(item.getAttribute("path"));
582 String base = evalVars(item.getAttribute("base"));
583 deleteFile(base, path);
584 }
585
586 private void processDownloadElement(Element item) {
587 String address = evalVars(item.getAttribute("url"));
588 String path = evalVars(item.getAttribute("path"));
589 String unzip = evalVars(item.getAttribute("unzip"));
590 String mkdir = evalVars(item.getAttribute("mkdir"));
591
592 String base = evalVars(item.getAttribute("base"));
593 String dir = getDirectoryByAbbr(base);
594 if (dir==null) {
595 log("Error: Can not find directory to place file, use base=cache, base=prefs or base=plugins attribute.");
596 return;
597 }
598
599 if (path.contains("..") || path.startsWith("/") || path.contains(":")) {
600 return; // some basic protection
601 }
602 if (address == null || path == null || address.length() == 0 || path.length() == 0) {
603 log("Error: Please specify url=\"where to get file\" and path=\"where to place it\"");
604 return;
605 }
606 processDownloadOperation(address, path, dir, "true".equals(mkdir), "true".equals(unzip));
607 }
608
609 private void processPluginInstallElement(Element elem) {
610 String install = elem.getAttribute("install");
611 String uninstall = elem.getAttribute("remove");
612 String delete = elem.getAttribute("delete");
613 pluginOperation(install, uninstall, delete);
614 }
615
616 private void processMsgBoxElement(Element elem) {
617 String text = evalVars(elem.getAttribute("text"));
618 String locText = evalVars(elem.getAttribute(LanguageInfo.getJOSMLocaleCode()+".text"));
619 if (locText!=null && locText.length()>0) text=locText;
620
621 String type = evalVars(elem.getAttribute("type"));
622 messageBox(type, text);
623 }
624
625 private void processAskElement(Element elem) {
626 String text = evalVars(elem.getAttribute("text"));
627 String locText = evalVars(elem.getAttribute(LanguageInfo.getJOSMLocaleCode()+".text"));
628 if (locText.length()>0) text=locText;
629 String var = elem.getAttribute("var");
630 if (var.isEmpty()) var="result";
631
632 String input = evalVars(elem.getAttribute("input"));
633 if ("true".equals(input)) {
634 setVar(var, askForText(text));
635 } else {
636 String opts = evalVars(elem.getAttribute("options"));
637 String locOpts = evalVars(elem.getAttribute(LanguageInfo.getJOSMLocaleCode()+".options"));
638 if (locOpts.length()>0) opts=locOpts;
639 setVar(var, String.valueOf(askForOption(text, opts)));
640 }
641 }
642
643 public void setVar(String name, String value) {
644 try {
645 engine.eval(name+"='"+value+"';");
646 } catch (ScriptException ex) {
647 log("Error: Can not assign variable: %s=%s : %s\n", name, value, ex.getMessage());
648 }
649 }
650
651 private void processIfElement(Element elem) {
652 String realValue = evalVars(elem.getAttribute("test"));
653 boolean v=false;
654 if ("true".equals(realValue)) v=true; else
655 if ("fales".equals(realValue)) v=true; else
656 {
657 log("Error: Illegal test expression in if: %s=%s\n", elem.getAttribute("test"), realValue);
658 }
659
660 if (v) processXmlFragment(elem);
661 lastV = v;
662 }
663
664 private void processElseElement(Element elem) {
665 if (!lastV) {
666 processXmlFragment(elem);
667 }
668 }
669
670 private boolean processRunTaskElement(Element elem) {
671 String taskName = elem.getAttribute("name");
672 Element task = tasksMap.get(taskName);
673 if (task!=null) {
674 log("EXECUTING TASK "+taskName);
675 processXmlFragment(task); // process task recursively
676 } else {
677 log("Error: Can not execute task "+taskName);
678 return true;
679 }
680 return false;
681 }
682
683 private void processScriptElement(Element elem) {
684 String js = elem.getChildNodes().item(0).getTextContent();
685 log("Processing script...");
686 try {
687 PreferencesUtils.modifyPreferencesByScript(engine, mainPrefs, js);
688 } catch (ScriptException ex) {
689 messageBox("e", ex.getMessage());
690 log("JS error: "+ex.getMessage());
691 }
692 log("Script finished");
693 }
694
695 /**
696 * substitute ${expression} = expression evaluated by JavaScript
697 */
698 private String evalVars(String s) {
699 Pattern p = Pattern.compile("\\$\\{([^\\}]*)\\}");
700 Matcher mr = p.matcher(s);
701 StringBuffer sb = new StringBuffer();
702 while (mr.find()) {
703 try {
704 String result = engine.eval(mr.group(1)).toString();
705 mr.appendReplacement(sb, result);
706 } catch (ScriptException ex) {
707 log("Error: Can not evaluate expression %s : %s", mr.group(1), ex.getMessage());
708 }
709 }
710 mr.appendTail(sb);
711 return sb.toString();
712 }
713
714 private Preferences readPreferencesFromDOMElement(Element item) {
715 Preferences tmpPref = new Preferences();
716 try {
717 Transformer xformer = TransformerFactory.newInstance().newTransformer();
718 CharArrayWriter outputWriter = new CharArrayWriter(8192);
719 StreamResult out = new StreamResult(outputWriter);
720
721 xformer.transform(new DOMSource(item), out);
722
723 String fragmentWithReplacedVars= evalVars(outputWriter.toString());
724
725 CharArrayReader reader = new CharArrayReader(fragmentWithReplacedVars.toCharArray());
726 tmpPref.fromXML(reader);
727 } catch (Exception ex) {
728 log("Error: can not read XML fragment :" + ex.getMessage());
729 }
730
731 return tmpPref;
732 }
733
734 private String normalizeDirName(String dir) {
735 String s = dir.replace("\\", "/");
736 if (s.endsWith("/")) s=s.substring(0,s.length()-1);
737 return s;
738 }
739 }
740
741 /**
742 * Helper class to do specific Preferences operation - appending, replacing,
743 * deletion by key and by value
744 * Also contains functions that convert preferences object to JavaScript object and back
745 */
746 public static final class PreferencesUtils {
747
748 private PreferencesUtils() {
749 // Hide implicit public constructor for utility class
750 }
751
752 private static void replacePreferences(Preferences fragment, Preferences mainpref) {
753 for (Entry<String, Setting<?>> entry: fragment.settingsMap.entrySet()) {
754 mainpref.putSetting(entry.getKey(), entry.getValue());
755 }
756 }
757
758 private static void appendPreferences(Preferences fragment, Preferences mainpref) {
759 for (Entry<String, Setting<?>> entry: fragment.settingsMap.entrySet()) {
760 String key = entry.getKey();
761 if (entry.getValue() instanceof StringSetting) {
762 mainpref.putSetting(key, entry.getValue());
763 } else if (entry.getValue() instanceof ListSetting) {
764 ListSetting lSetting = (ListSetting) entry.getValue();
765 Collection<String> newItems = getCollection(mainpref, key, true);
766 if (newItems == null) continue;
767 for (String item : lSetting.getValue()) {
768 // add nonexisting elements to then list
769 if (!newItems.contains(item)) {
770 newItems.add(item);
771 }
772 }
773 mainpref.putCollection(key, newItems);
774 } else if (entry.getValue() instanceof ListListSetting) {
775 ListListSetting llSetting = (ListListSetting) entry.getValue();
776 Collection<Collection<String>> newLists = getArray(mainpref, key, true);
777 if (newLists == null) continue;
778
779 for (Collection<String> list : llSetting.getValue()) {
780 // add nonexisting list (equals comparison for lists is used implicitly)
781 if (!newLists.contains(list)) {
782 newLists.add(list);
783 }
784 }
785 mainpref.putArray(key, newLists);
786 } else if (entry.getValue() instanceof MapListSetting) {
787 MapListSetting mlSetting = (MapListSetting) entry.getValue();
788 List<Map<String, String>> newMaps = getListOfStructs(mainpref, key, true);
789 if (newMaps == null) continue;
790
791 // get existing properties as list of maps
792
793 for (Map<String, String> map : mlSetting.getValue()) {
794 // add nonexisting map (equals comparison for maps is used implicitly)
795 if (!newMaps.contains(map)) {
796 newMaps.add(map);
797 }
798 }
799 mainpref.putListOfStructs(entry.getKey(), newMaps);
800 }
801 }
802 }
803
804 /**
805 * Delete items from @param mainpref collections that match items from @param fragment collections
806 */
807 private static void deletePreferenceValues(Preferences fragment, Preferences mainpref) {
808
809 for (Entry<String, Setting<?>> entry : fragment.settingsMap.entrySet()) {
810 String key = entry.getKey();
811 if (entry.getValue() instanceof StringSetting) {
812 StringSetting sSetting = (StringSetting) entry.getValue();
813 // if mentioned value found, delete it
814 if (sSetting.equals(mainpref.settingsMap.get(key))) {
815 mainpref.put(key, null);
816 }
817 } else if (entry.getValue() instanceof ListSetting) {
818 ListSetting lSetting = (ListSetting) entry.getValue();
819 Collection<String> newItems = getCollection(mainpref, key, true);
820 if (newItems == null) continue;
821
822 // remove mentioned items from collection
823 for (String item : lSetting.getValue()) {
824 log("Deleting preferences: from list %s: %s\n", key, item);
825 newItems.remove(item);
826 }
827 mainpref.putCollection(entry.getKey(), newItems);
828 } else if (entry.getValue() instanceof ListListSetting) {
829 ListListSetting llSetting = (ListListSetting) entry.getValue();
830 Collection<Collection<String>> newLists = getArray(mainpref, key, true);
831 if (newLists == null) continue;
832
833 // if items are found in one of lists, remove that list!
834 Iterator<Collection<String>> listIterator = newLists.iterator();
835 while (listIterator.hasNext()) {
836 Collection<String> list = listIterator.next();
837 for (Collection<String> removeList : llSetting.getValue()) {
838 if (list.containsAll(removeList)) {
839 // remove current list, because it matches search criteria
840 log("Deleting preferences: list from lists %s: %s\n", key, list);
841 listIterator.remove();
842 }
843 }
844 }
845
846 mainpref.putArray(key, newLists);
847 } else if (entry.getValue() instanceof MapListSetting) {
848 MapListSetting mlSetting = (MapListSetting) entry.getValue();
849 List<Map<String, String>> newMaps = getListOfStructs(mainpref, key, true);
850 if (newMaps == null) continue;
851
852 Iterator<Map<String, String>> mapIterator = newMaps.iterator();
853 while (mapIterator.hasNext()) {
854 Map<String, String> map = mapIterator.next();
855 for (Map<String, String> removeMap : mlSetting.getValue()) {
856 if (map.entrySet().containsAll(removeMap.entrySet())) {
857 // the map contain all mentioned key-value pair, so it should be deleted from "maps"
858 log("Deleting preferences: deleting map from maps %s: %s\n", key, map);
859 mapIterator.remove();
860 }
861 }
862 }
863 mainpref.putListOfStructs(entry.getKey(), newMaps);
864 }
865 }
866 }
867
868 private static void deletePreferenceKeyByPattern(String pattern, Preferences pref) {
869 Map<String, Setting<?>> allSettings = pref.getAllSettings();
870 for (Entry<String, Setting<?>> entry : allSettings.entrySet()) {
871 String key = entry.getKey();
872 if (key.matches(pattern)) {
873 log("Deleting preferences: deleting key from preferences: " + key);
874 pref.putSetting(key, null);
875 }
876 }
877 }
878
879 private static void deletePreferenceKey(String key, Preferences pref) {
880 Map<String, Setting<?>> allSettings = pref.getAllSettings();
881 if (allSettings.containsKey(key)) {
882 log("Deleting preferences: deleting key from preferences: " + key);
883 pref.putSetting(key, null);
884 }
885 }
886
887 private static Collection<String> getCollection(Preferences mainpref, String key, boolean warnUnknownDefault) {
888 ListSetting existing = Utils.cast(mainpref.settingsMap.get(key), ListSetting.class);
889 ListSetting defaults = Utils.cast(mainpref.defaultsMap.get(key), ListSetting.class);
890 if (existing == null && defaults == null) {
891 if (warnUnknownDefault) defaultUnknownWarning(key);
892 return null;
893 }
894 if (existing != null)
895 return new ArrayList<>(existing.getValue());
896 else
897 return defaults.getValue() == null ? null : new ArrayList<>(defaults.getValue());
898 }
899
900 private static Collection<Collection<String>> getArray(Preferences mainpref, String key, boolean warnUnknownDefault) {
901 ListListSetting existing = Utils.cast(mainpref.settingsMap.get(key), ListListSetting.class);
902 ListListSetting defaults = Utils.cast(mainpref.defaultsMap.get(key), ListListSetting.class);
903
904 if (existing == null && defaults == null) {
905 if (warnUnknownDefault) defaultUnknownWarning(key);
906 return null;
907 }
908 if (existing != null)
909 return new ArrayList<Collection<String>>(existing.getValue());
910 else
911 return defaults.getValue() == null ? null : new ArrayList<Collection<String>>(defaults.getValue());
912 }
913
914 private static List<Map<String, String>> getListOfStructs(Preferences mainpref, String key, boolean warnUnknownDefault) {
915 MapListSetting existing = Utils.cast(mainpref.settingsMap.get(key), MapListSetting.class);
916 MapListSetting defaults = Utils.cast(mainpref.settingsMap.get(key), MapListSetting.class);
917
918 if (existing == null && defaults == null) {
919 if (warnUnknownDefault) defaultUnknownWarning(key);
920 return null;
921 }
922
923 if (existing != null)
924 return new ArrayList<>(existing.getValue());
925 else
926 return defaults.getValue() == null ? null : new ArrayList<>(defaults.getValue());
927 }
928
929 private static void defaultUnknownWarning(String key) {
930 log("Warning: Unknown default value of %s , skipped\n", key);
931 JOptionPane.showMessageDialog(
932 Main.parent,
933 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),
934 tr("Warning"),
935 JOptionPane.WARNING_MESSAGE);
936 }
937
938 private static void showPrefs(Preferences tmpPref) {
939 Main.info("properties: " + tmpPref.settingsMap);
940 }
941
942 private static void modifyPreferencesByScript(ScriptEngine engine, Preferences tmpPref, String js) throws ScriptException {
943 loadPrefsToJS(engine, tmpPref, "API.pref", true);
944 engine.eval(js);
945 readPrefsFromJS(engine, tmpPref, "API.pref");
946 }
947
948 /**
949 * Convert JavaScript preferences object to preferences data structures
950 * @param engine - JS engine to put object
951 * @param tmpPref - preferences to fill from JS
952 * @param varInJS - JS variable name, where preferences are stored
953 * @throws ScriptException
954 */
955 public static void readPrefsFromJS(ScriptEngine engine, Preferences tmpPref, String varInJS) throws ScriptException {
956 String finish =
957 "stringMap = new java.util.TreeMap ;"+
958 "listMap = new java.util.TreeMap ;"+
959 "listlistMap = new java.util.TreeMap ;"+
960 "listmapMap = new java.util.TreeMap ;"+
961 "for (key in "+varInJS+") {"+
962 " val = "+varInJS+"[key];"+
963 " type = typeof val == 'string' ? 'string' : val.type;"+
964 " if (type == 'string') {"+
965 " stringMap.put(key, val);"+
966 " } else if (type == 'list') {"+
967 " l = new java.util.ArrayList;"+
968 " for (i=0; i<val.length; i++) {"+
969 " l.add(java.lang.String.valueOf(val[i]));"+
970 " }"+
971 " listMap.put(key, l);"+
972 " } else if (type == 'listlist') {"+
973 " l = new java.util.ArrayList;"+
974 " for (i=0; i<val.length; i++) {"+
975 " list=val[i];"+
976 " jlist=new java.util.ArrayList;"+
977 " for (j=0; j<list.length; j++) {"+
978 " jlist.add(java.lang.String.valueOf(list[j]));"+
979 " }"+
980 " l.add(jlist);"+
981 " }"+
982 " listlistMap.put(key, l);"+
983 " } else if (type == 'listmap') {"+
984 " l = new java.util.ArrayList;"+
985 " for (i=0; i<val.length; i++) {"+
986 " map=val[i];"+
987 " jmap=new java.util.TreeMap;"+
988 " for (var key2 in map) {"+
989 " jmap.put(key2,java.lang.String.valueOf(map[key2]));"+
990 " }"+
991 " l.add(jmap);"+
992 " }"+
993 " listmapMap.put(key, l);"+
994 " } else {" +
995 " org.openstreetmap.josm.data.CustomConfigurator.log('Unknown type:'+val.type+ '- use list, listlist or listmap'); }"+
996 " }";
997 engine.eval(finish);
998
999 @SuppressWarnings("unchecked")
1000 Map<String, String> stringMap = (Map<String, String>) engine.get("stringMap");
1001 @SuppressWarnings("unchecked")
1002 Map<String, List<String>> listMap = (SortedMap<String, List<String>> ) engine.get("listMap");
1003 @SuppressWarnings("unchecked")
1004 Map<String, List<Collection<String>>> listlistMap = (SortedMap<String, List<Collection<String>>>) engine.get("listlistMap");
1005 @SuppressWarnings("unchecked")
1006 Map<String, List<Map<String, String>>> listmapMap = (SortedMap<String, List<Map<String,String>>>) engine.get("listmapMap");
1007
1008 tmpPref.settingsMap.clear();
1009
1010 Map<String, Setting<?>> tmp = new HashMap<>();
1011 for (Entry<String, String> e : stringMap.entrySet()) {
1012 tmp.put(e.getKey(), new StringSetting(e.getValue()));
1013 }
1014 for (Entry<String, List<String>> e : listMap.entrySet()) {
1015 tmp.put(e.getKey(), new ListSetting(e.getValue()));
1016 }
1017
1018 for (Entry<String, List<Collection<String>>> e : listlistMap.entrySet()) {
1019 @SuppressWarnings("unchecked")
1020 List<List<String>> value = (List)e.getValue();
1021 tmp.put(e.getKey(), new ListListSetting(value));
1022 }
1023 for (Entry<String, List<Map<String, String>>> e : listmapMap.entrySet()) {
1024 tmp.put(e.getKey(), new MapListSetting(e.getValue()));
1025 }
1026 for (Entry<String, Setting<?>> e : tmp.entrySet()) {
1027 if (e.getValue().equals(tmpPref.defaultsMap.get(e.getKey()))) continue;
1028 tmpPref.settingsMap.put(e.getKey(), e.getValue());
1029 }
1030 }
1031
1032 /**
1033 * Convert preferences data structures to JavaScript object
1034 * @param engine - JS engine to put object
1035 * @param tmpPref - preferences to convert
1036 * @param whereToPutInJS - variable name to store preferences in JS
1037 * @param includeDefaults - include known default values to JS objects
1038 * @throws ScriptException
1039 */
1040 public static void loadPrefsToJS(ScriptEngine engine, Preferences tmpPref, String whereToPutInJS, boolean includeDefaults) throws ScriptException {
1041 Map<String, String> stringMap = new TreeMap<>();
1042 Map<String, List<String>> listMap = new TreeMap<>();
1043 Map<String, List<List<String>>> listlistMap = new TreeMap<>();
1044 Map<String, List<Map<String, String>>> listmapMap = new TreeMap<>();
1045
1046 if (includeDefaults) {
1047 for (Map.Entry<String, Setting<?>> e: tmpPref.defaultsMap.entrySet()) {
1048 Setting<?> setting = e.getValue();
1049 if (setting instanceof StringSetting) {
1050 stringMap.put(e.getKey(), ((StringSetting) setting).getValue());
1051 } else if (setting instanceof ListSetting) {
1052 listMap.put(e.getKey(), ((ListSetting) setting).getValue());
1053 } else if (setting instanceof ListListSetting) {
1054 listlistMap.put(e.getKey(), ((ListListSetting) setting).getValue());
1055 } else if (setting instanceof MapListSetting) {
1056 listmapMap.put(e.getKey(), ((MapListSetting) setting).getValue());
1057 }
1058 }
1059 }
1060 Iterator<Map.Entry<String, Setting<?>>> it = tmpPref.settingsMap.entrySet().iterator();
1061 while (it.hasNext()) {
1062 Map.Entry<String, Setting<?>> e = it.next();
1063 if (e.getValue().getValue() == null) {
1064 it.remove();
1065 }
1066 }
1067
1068 for (Map.Entry<String, Setting<?>> e: tmpPref.settingsMap.entrySet()) {
1069 Setting<?> setting = e.getValue();
1070 if (setting instanceof StringSetting) {
1071 stringMap.put(e.getKey(), ((StringSetting) setting).getValue());
1072 } else if (setting instanceof ListSetting) {
1073 listMap.put(e.getKey(), ((ListSetting) setting).getValue());
1074 } else if (setting instanceof ListListSetting) {
1075 listlistMap.put(e.getKey(), ((ListListSetting) setting).getValue());
1076 } else if (setting instanceof MapListSetting) {
1077 listmapMap.put(e.getKey(), ((MapListSetting) setting).getValue());
1078 }
1079 }
1080
1081 engine.put("stringMap", stringMap);
1082 engine.put("listMap", listMap);
1083 engine.put("listlistMap", listlistMap);
1084 engine.put("listmapMap", listmapMap);
1085
1086 String init =
1087 "function getJSList( javaList ) {"+
1088 " var jsList; var i; "+
1089 " if (javaList == null) return null;"+
1090 "jsList = [];"+
1091 " for (i = 0; i < javaList.size(); i++) {"+
1092 " jsList.push(String(list.get(i)));"+
1093 " }"+
1094 "return jsList;"+
1095 "}"+
1096 "function getJSMap( javaMap ) {"+
1097 " var jsMap; var it; var e; "+
1098 " if (javaMap == null) return null;"+
1099 " jsMap = {};"+
1100 " for (it = javaMap.entrySet().iterator(); it.hasNext();) {"+
1101 " e = it.next();"+
1102 " jsMap[ String(e.getKey()) ] = String(e.getValue()); "+
1103 " }"+
1104 " return jsMap;"+
1105 "}"+
1106 "for (it = stringMap.entrySet().iterator(); it.hasNext();) {"+
1107 " e = it.next();"+
1108 whereToPutInJS+"[String(e.getKey())] = String(e.getValue());"+
1109 "}\n"+
1110 "for (it = listMap.entrySet().iterator(); it.hasNext();) {"+
1111 " e = it.next();"+
1112 " list = e.getValue();"+
1113 " jslist = getJSList(list);"+
1114 " jslist.type = 'list';"+
1115 whereToPutInJS+"[String(e.getKey())] = jslist;"+
1116 "}\n"+
1117 "for (it = listlistMap.entrySet().iterator(); it.hasNext(); ) {"+
1118 " e = it.next();"+
1119 " listlist = e.getValue();"+
1120 " jslistlist = [];"+
1121 " for (it2 = listlist.iterator(); it2.hasNext(); ) {"+
1122 " list = it2.next(); "+
1123 " jslistlist.push(getJSList(list));"+
1124 " }"+
1125 " jslistlist.type = 'listlist';"+
1126 whereToPutInJS+"[String(e.getKey())] = jslistlist;"+
1127 "}\n"+
1128 "for (it = listmapMap.entrySet().iterator(); it.hasNext();) {"+
1129 " e = it.next();"+
1130 " listmap = e.getValue();"+
1131 " jslistmap = [];"+
1132 " for (it2 = listmap.iterator(); it2.hasNext();) {"+
1133 " map = it2.next();"+
1134 " jslistmap.push(getJSMap(map));"+
1135 " }"+
1136 " jslistmap.type = 'listmap';"+
1137 whereToPutInJS+"[String(e.getKey())] = jslistmap;"+
1138 "}\n";
1139
1140 // Execute conversion script
1141 engine.eval(init);
1142 }
1143 }
1144}
Note: See TracBrowser for help on using the repository browser.