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

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

see #4421: Mechanism to modify JOSM settings and store files, advanced preferences dialog modifications
+ JavaScript configuration API
+ Asynchronous file download task DownloadFileTask
+ Function to export arbitrary preference keys to file

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