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

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

When doing a String.toLowerCase()/toUpperCase() call, use a Locale. This avoids problems with certain locales, i.e. Lithuanian or Turkish. See PMD UseLocaleWithCaseConversions rule and String.toLowerCase() javadoc.

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