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

Last change on this file since 5132 was 5115, checked in by akks, 12 years ago

see #4421: plugin installation fix for JOSM custom configurator

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