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

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

Sonar/FindBugs - Nested blocks of code should not be left empty

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