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

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

sonar - fb-contrib:ISB_INEFFICIENT_STRING_BUFFERING - Performance - Method passes simple concatenating string in StringBuffer or StringBuilder append

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