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

Last change on this file since 11992 was 11535, checked in by Don-vip, 7 years ago

sonar - squid:S2142 - "InterruptedException" should not be ignored

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