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

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

sonar - fix various minor issues

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