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

Last change on this file since 6084 was 6084, checked in by bastiK, 11 years ago

see #8902 - add missing @Override annotations (patch by shinigami)

File size: 49.3 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.concurrent.Future;
25import java.util.regex.Matcher;
26import java.util.regex.Pattern;
27
28import javax.script.ScriptEngine;
29import javax.script.ScriptEngineManager;
30import javax.script.ScriptException;
31import javax.swing.JOptionPane;
32import javax.swing.SwingUtilities;
33import javax.xml.parsers.DocumentBuilder;
34import javax.xml.parsers.DocumentBuilderFactory;
35import javax.xml.transform.OutputKeys;
36import javax.xml.transform.Transformer;
37import javax.xml.transform.TransformerFactory;
38import javax.xml.transform.dom.DOMSource;
39import javax.xml.transform.stream.StreamResult;
40
41import org.openstreetmap.josm.Main;
42import org.openstreetmap.josm.data.Preferences.Setting;
43import org.openstreetmap.josm.gui.io.DownloadFileTask;
44import org.openstreetmap.josm.plugins.PluginDownloadTask;
45import org.openstreetmap.josm.plugins.PluginInformation;
46import org.openstreetmap.josm.plugins.ReadLocalPluginInformationTask;
47import org.openstreetmap.josm.tools.LanguageInfo;
48import org.openstreetmap.josm.tools.Utils;
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("UTF-8"));
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 @Override
333 public void run() {
334 if (task.isCanceled()) return;
335 synchronized (CustomConfigurator.class) {
336 try { // proceed only after all other tasks were finished
337 while (busy) CustomConfigurator.class.wait();
338 } catch (InterruptedException ex) { }
339
340 SwingUtilities.invokeLater(new Runnable() {
341 @Override
342 public void run() {
343 List<PluginInformation> availablePlugins = task.getAvailablePlugins();
344 List<PluginInformation> toInstallPlugins = new ArrayList<PluginInformation>();
345 List<PluginInformation> toRemovePlugins = new ArrayList<PluginInformation>();
346 List<PluginInformation> toDeletePlugins = new ArrayList<PluginInformation>();
347 for (PluginInformation pi: availablePlugins) {
348 //System.out.print(pi.name+";");
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)) pls.add(pi.name);
361 }
362 for (PluginInformation pi: toRemovePlugins) {
363 pls.remove(pi.name);
364 }
365 for (PluginInformation pi: toDeletePlugins) {
366 pls.remove(pi.name);
367 new File(Main.pref.getPluginsDirectory(),pi.name+".jar").deleteOnExit();
368 }
369 System.out.println(pls);
370 Main.pref.putCollection("plugins",pls);
371 }
372 });
373 }
374 }
375
376 };
377 Main.worker.submit(task);
378 Main.worker.submit(r);
379 }
380
381 private static String getDirectoryByAbbr(String base) {
382 String dir;
383 if ("prefs".equals(base) || base.length()==0) {
384 dir = Main.pref.getPreferencesDir();
385 } else if ("cache".equals(base)) {
386 dir = Main.pref.getCacheDirectory().getAbsolutePath();
387 } else if ("plugins".equals(base)) {
388 dir = Main.pref.getPluginsDirectory().getAbsolutePath();
389 } else {
390 dir = null;
391 }
392 return dir;
393 }
394
395 public static Preferences clonePreferences(Preferences pref) {
396 Preferences tmp = new Preferences();
397 tmp.defaults.putAll( pref.defaults );
398 tmp.properties.putAll( pref.properties );
399 tmp.arrayDefaults.putAll( pref.arrayDefaults );
400 tmp.arrayProperties.putAll( pref.arrayProperties );
401 tmp.collectionDefaults.putAll( pref.collectionDefaults );
402 tmp.collectionProperties.putAll( pref.collectionProperties );
403 tmp.listOfStructsDefaults.putAll( pref.listOfStructsDefaults );
404 tmp.listOfStructsProperties.putAll( pref.listOfStructsProperties );
405 tmp.colornames.putAll( pref.colornames );
406
407 return tmp;
408 }
409
410
411 public static class XMLCommandProcessor {
412
413 Preferences mainPrefs;
414 Map<String,Element> tasksMap = new HashMap<String,Element>();
415
416 private boolean lastV; // last If condition result
417
418
419 ScriptEngine engine ;
420
421 public void openAndReadXML(File file) {
422 log("-- Reading custom preferences from " + file.getAbsolutePath() + " --");
423 try {
424 String fileDir = file.getParentFile().getAbsolutePath();
425 if (fileDir!=null) engine.eval("scriptDir='"+normalizeDirName(fileDir) +"';");
426 openAndReadXML(new BufferedInputStream(new FileInputStream(file)));
427 } catch (Exception ex) {
428 log("Error reading custom preferences: " + ex.getMessage());
429 }
430 }
431
432 public void openAndReadXML(InputStream is) {
433 try {
434 DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
435 builderFactory.setValidating(false);
436 builderFactory.setNamespaceAware(true);
437 DocumentBuilder builder = builderFactory.newDocumentBuilder();
438 Document document = builder.parse(is);
439 synchronized (CustomConfigurator.class) {
440 processXML(document);
441 }
442 } catch (Exception ex) {
443 log("Error reading custom preferences: "+ex.getMessage());
444 } finally {
445 Utils.close(is);
446 }
447 log("-- Reading complete --");
448 }
449
450 public XMLCommandProcessor(Preferences mainPrefs) {
451 try {
452 this.mainPrefs = mainPrefs;
453 CustomConfigurator.summary = new StringBuilder();
454 engine = new ScriptEngineManager().getEngineByName("rhino");
455 engine.eval("API={}; API.pref={}; API.fragments={};");
456
457 engine.eval("homeDir='"+normalizeDirName(Main.pref.getPreferencesDir()) +"';");
458 engine.eval("josmVersion="+Version.getInstance().getVersion()+";");
459 String className = CustomConfigurator.class.getName();
460 engine.eval("API.messageBox="+className+".messageBox");
461 engine.eval("API.askText=function(text) { return String("+className+".askForText(text));}");
462 engine.eval("API.askOption="+className+".askForOption");
463 engine.eval("API.downloadFile="+className+".downloadFile");
464 engine.eval("API.downloadAndUnpackFile="+className+".downloadAndUnpackFile");
465 engine.eval("API.deleteFile="+className+".deleteFile");
466 engine.eval("API.plugin ="+className+".pluginOperation");
467 engine.eval("API.pluginInstall = function(names) { "+className+".pluginOperation(names,'','');}");
468 engine.eval("API.pluginUninstall = function(names) { "+className+".pluginOperation('',names,'');}");
469 engine.eval("API.pluginDelete = function(names) { "+className+".pluginOperation('','',names);}");
470 } catch (Exception ex) {
471 log("Error: initializing script engine: "+ex.getMessage());
472 }
473 }
474
475 private void processXML(Document document) {
476 Element root = document.getDocumentElement();
477 processXmlFragment(root);
478 }
479
480 private void processXmlFragment(Element root) {
481 NodeList childNodes = root.getChildNodes();
482 int nops = childNodes.getLength();
483 for (int i = 0; i < nops; i++) {
484 Node item = childNodes.item(i);
485 if (item.getNodeType() != Node.ELEMENT_NODE) continue;
486 String elementName = item.getNodeName();
487 //if (monitor!=null) monitor.indeterminateSubTask(elementName);
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 * subsititute ${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 //mr.appendReplacement(sb, mr.group(0));
700 }
701 }
702 mr.appendTail(sb);
703 return sb.toString();
704 }
705
706 private Preferences readPreferencesFromDOMElement(Element item) {
707 Preferences tmpPref = new Preferences();
708 try {
709 Transformer xformer = TransformerFactory.newInstance().newTransformer();
710 CharArrayWriter outputWriter = new CharArrayWriter(8192);
711 StreamResult out = new StreamResult(outputWriter);
712
713 xformer.transform(new DOMSource(item), out);
714
715 String fragmentWithReplacedVars= evalVars(outputWriter.toString());
716
717 CharArrayReader reader = new CharArrayReader(fragmentWithReplacedVars.toCharArray());
718 tmpPref.fromXML(reader);
719 } catch (Exception ex) {
720 log("Error: can not read XML fragment :" + ex.getMessage());
721 }
722
723 return tmpPref;
724 }
725
726 private String normalizeDirName(String dir) {
727 String s = dir.replace("\\", "/");
728 if (s.endsWith("/")) s=s.substring(0,s.length()-1);
729 return s;
730 }
731
732
733 }
734
735 /**
736 * Helper class to do specific Prefrences operation - appending, replacing,
737 * deletion by key and by value
738 * Also contains functions that convert preferences object to JavaScript object and back
739 */
740 public static class PreferencesUtils {
741
742 private static void replacePreferences(Preferences fragment, Preferences mainpref) {
743 // normal prefs
744 for (Entry<String, String> entry : fragment.properties.entrySet()) {
745 mainpref.put(entry.getKey(), entry.getValue());
746 }
747 // "list"
748 for (Entry<String, List<String>> entry : fragment.collectionProperties.entrySet()) {
749 mainpref.putCollection(entry.getKey(), entry.getValue());
750 }
751 // "lists"
752 for (Entry<String, List<List<String>>> entry : fragment.arrayProperties.entrySet()) {
753 ArrayList<Collection<String>> array = new ArrayList<Collection<String>>();
754 array.addAll(entry.getValue());
755 mainpref.putArray(entry.getKey(), array);
756 }
757 /// "maps"
758 for (Entry<String, List<Map<String, String>>> entry : fragment.listOfStructsProperties.entrySet()) {
759 mainpref.putListOfStructs(entry.getKey(), entry.getValue());
760 }
761
762 }
763
764 private static void appendPreferences(Preferences fragment, Preferences mainpref) {
765 // normal prefs
766 for (Entry<String, String> entry : fragment.properties.entrySet()) {
767 mainpref.put(entry.getKey(), entry.getValue());
768 }
769
770 // "list"
771 for (Entry<String, List<String>> entry : fragment.collectionProperties.entrySet()) {
772 String key = entry.getKey();
773
774 Collection<String> newItems = getCollection(mainpref, key, true);
775 if (newItems == null) continue;
776
777 for (String item : entry.getValue()) {
778 // add nonexisting elements to then list
779 if (!newItems.contains(item)) {
780 newItems.add(item);
781 }
782 }
783 mainpref.putCollection(entry.getKey(), newItems);
784 }
785
786 // "lists"
787 for (Entry<String, List<List<String>>> entry : fragment.arrayProperties.entrySet()) {
788 String key = entry.getKey();
789
790 Collection<Collection<String>> newLists = getArray(mainpref, key, true);
791 if (newLists == null) continue;
792
793 for (Collection<String> list : entry.getValue()) {
794 // add nonexisting list (equals comparison for lists is used implicitly)
795 if (!newLists.contains(list)) {
796 newLists.add(list);
797 }
798 }
799 mainpref.putArray(entry.getKey(), newLists);
800 }
801
802 /// "maps"
803 for (Entry<String, List<Map<String, String>>> entry : fragment.listOfStructsProperties.entrySet()) {
804 String key = entry.getKey();
805
806 List<Map<String, String>> newMaps = getListOfStructs(mainpref, key, true);
807 if (newMaps == null) continue;
808
809 // get existing properties as list of maps
810
811 for (Map<String, String> map : entry.getValue()) {
812 // add nonexisting map (equals comparison for maps is used implicitly)
813 if (!newMaps.contains(map)) {
814 newMaps.add(map);
815 }
816 }
817 mainpref.putListOfStructs(entry.getKey(), newMaps);
818 }
819 }
820
821 /**
822 * Delete items from @param mainpref collections that match items from @param fragment collections
823 */
824 private static void deletePreferenceValues(Preferences fragment, Preferences mainpref) {
825
826
827 // normal prefs
828 for (Entry<String, String> entry : fragment.properties.entrySet()) {
829 // if mentioned value found, delete it
830 if (entry.getValue().equals(mainpref.properties.get(entry.getKey()))) {
831 mainpref.put(entry.getKey(), null);
832 }
833 }
834
835 // "list"
836 for (Entry<String, List<String>> entry : fragment.collectionProperties.entrySet()) {
837 String key = entry.getKey();
838
839 Collection<String> newItems = getCollection(mainpref, key, true);
840 if (newItems == null) continue;
841
842 // remove mentioned items from collection
843 for (String item : entry.getValue()) {
844 log("Deleting preferences: from list %s: %s\n", key, item);
845 newItems.remove(item);
846 }
847 mainpref.putCollection(entry.getKey(), newItems);
848 }
849
850 // "lists"
851 for (Entry<String, List<List<String>>> entry : fragment.arrayProperties.entrySet()) {
852 String key = entry.getKey();
853
854
855 Collection<Collection<String>> newLists = getArray(mainpref, key, true);
856 if (newLists == null) continue;
857
858 // if items are found in one of lists, remove that list!
859 Iterator<Collection<String>> listIterator = newLists.iterator();
860 while (listIterator.hasNext()) {
861 Collection<String> list = listIterator.next();
862 for (Collection<String> removeList : entry.getValue()) {
863 if (list.containsAll(removeList)) {
864 // remove current list, because it matches search criteria
865 log("Deleting preferences: list from lists %s: %s\n", key, list);
866 listIterator.remove();
867 }
868 }
869 }
870
871 mainpref.putArray(entry.getKey(), newLists);
872 }
873
874 /// "maps"
875 for (Entry<String, List<Map<String, String>>> entry : fragment.listOfStructsProperties.entrySet()) {
876 String key = entry.getKey();
877
878 List<Map<String, String>> newMaps = getListOfStructs(mainpref, key, true);
879 if (newMaps == null) continue;
880
881 Iterator<Map<String, String>> mapIterator = newMaps.iterator();
882 while (mapIterator.hasNext()) {
883 Map<String, String> map = mapIterator.next();
884 for (Map<String, String> removeMap : entry.getValue()) {
885 if (map.entrySet().containsAll(removeMap.entrySet())) {
886 // the map contain all mentioned key-value pair, so it should be deleted from "maps"
887 log("Deleting preferences: deleting map from maps %s: %s\n", key, map);
888 mapIterator.remove();
889 }
890 }
891 }
892 mainpref.putListOfStructs(entry.getKey(), newMaps);
893 }
894 }
895
896 private static void deletePreferenceKeyByPattern(String pattern, Preferences pref) {
897 Map<String, Setting> allSettings = pref.getAllSettings();
898 for (String key : allSettings.keySet()) {
899 if (key.matches(pattern)) {
900 log("Deleting preferences: deleting key from preferences: " + key);
901 pref.putSetting(key, allSettings.get(key).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
953
954 private static void defaultUnknownWarning(String key) {
955 log("Warning: Unknown default value of %s , skipped\n", key);
956 JOptionPane.showMessageDialog(
957 Main.parent,
958 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),
959 tr("Warning"),
960 JOptionPane.WARNING_MESSAGE);
961 }
962
963 private static void showPrefs(Preferences tmpPref) {
964 System.out.println("properties: " + tmpPref.properties);
965 System.out.println("collections: " + tmpPref.collectionProperties);
966 System.out.println("arrays: " + tmpPref.arrayProperties);
967 System.out.println("maps: " + tmpPref.listOfStructsProperties);
968 }
969
970 private static void modifyPreferencesByScript(ScriptEngine engine, Preferences tmpPref, String js) throws ScriptException {
971 loadPrefsToJS(engine, tmpPref, "API.pref", true);
972 engine.eval(js);
973 readPrefsFromJS(engine, tmpPref, "API.pref");
974 }
975
976
977 /**
978 * Convert JavaScript preferences object to preferences data structures
979 * @param engine - JS engine to put object
980 * @param tmpPref - preferences to fill from JS
981 * @param varInJS - JS variable name, where preferences are stored
982 * @throws ScriptException
983 */
984 public static void readPrefsFromJS(ScriptEngine engine, Preferences tmpPref, String varInJS) throws ScriptException {
985 String finish =
986 "stringMap = new java.util.TreeMap ;"+
987 "listMap = new java.util.TreeMap ;"+
988 "listlistMap = new java.util.TreeMap ;"+
989 "listmapMap = new java.util.TreeMap ;"+
990 "for (key in "+varInJS+") {"+
991 " val = "+varInJS+"[key];"+
992 " type = typeof val == 'string' ? 'string' : val.type;"+
993 " if (type == 'string') {"+
994 " stringMap.put(key, val);"+
995 " } else if (type == 'list') {"+
996 " l = new java.util.ArrayList;"+
997 " for (i=0; i<val.length; i++) {"+
998 " l.add(java.lang.String.valueOf(val[i]));"+
999 " }"+
1000 " listMap.put(key, l);"+
1001 " } else if (type == 'listlist') {"+
1002 " l = new java.util.ArrayList;"+
1003 " for (i=0; i<val.length; i++) {"+
1004 " list=val[i];"+
1005 " jlist=new java.util.ArrayList;"+
1006 " for (j=0; j<list.length; j++) {"+
1007 " jlist.add(java.lang.String.valueOf(list[j]));"+
1008 " }"+
1009 " l.add(jlist);"+
1010 " }"+
1011 " listlistMap.put(key, l);"+
1012 " } else if (type == 'listmap') {"+
1013 " l = new java.util.ArrayList;"+
1014 " for (i=0; i<val.length; i++) {"+
1015 " map=val[i];"+
1016 " jmap=new java.util.TreeMap;"+
1017 " for (var key2 in map) {"+
1018 " jmap.put(key2,java.lang.String.valueOf(map[key2]));"+
1019 " }"+
1020 " l.add(jmap);"+
1021 " }"+
1022 " listmapMap.put(key, l);"+
1023 " } else {" +
1024 " org.openstreetmap.josm.data.CustomConfigurator.log('Unknown type:'+val.type+ '- use list, listlist or listmap'); }"+
1025 " }";
1026 engine.eval(finish);
1027
1028 @SuppressWarnings("unchecked")
1029 Map<String, String> stringMap = (Map<String, String>) engine.get("stringMap");
1030 @SuppressWarnings("unchecked")
1031 Map<String, List<String>> listMap = (SortedMap<String, List<String>> ) engine.get("listMap");
1032 @SuppressWarnings("unchecked")
1033 Map<String, List<Collection<String>>> listlistMap = (SortedMap<String, List<Collection<String>>>) engine.get("listlistMap");
1034 @SuppressWarnings("unchecked")
1035 Map<String, List<Map<String, String>>> listmapMap = (SortedMap<String, List<Map<String,String>>>) engine.get("listmapMap");
1036
1037 tmpPref.properties.clear();
1038 tmpPref.collectionProperties.clear();
1039 tmpPref.arrayProperties.clear();
1040 tmpPref.listOfStructsProperties.clear();
1041
1042 for (Entry<String, String> e : stringMap.entrySet()) {
1043 if (e.getValue().equals( tmpPref.defaults.get(e.getKey())) ) continue;
1044 tmpPref.properties.put(e.getKey(), e.getValue());
1045 }
1046
1047 for (Entry<String, List<String>> e : listMap.entrySet()) {
1048 if (Preferences.equalCollection(e.getValue(), tmpPref.collectionDefaults.get(e.getKey()))) continue;
1049 tmpPref.collectionProperties.put(e.getKey(), e.getValue());
1050 }
1051
1052 for (Entry<String, List<Collection<String>>> e : listlistMap.entrySet()) {
1053 if (Preferences.equalArray(e.getValue(), tmpPref.arrayDefaults.get(e.getKey()))) continue;
1054 @SuppressWarnings("unchecked") List<List<String>> value = (List)e.getValue();
1055 tmpPref.arrayProperties.put(e.getKey(), value);
1056 }
1057
1058 for (Entry<String, List<Map<String, String>>> e : listmapMap.entrySet()) {
1059 if (Preferences.equalListOfStructs(e.getValue(), tmpPref.listOfStructsDefaults.get(e.getKey()))) continue;
1060 tmpPref.listOfStructsProperties.put(e.getKey(), e.getValue());
1061 }
1062
1063 }
1064
1065
1066 /**
1067 * Convert preferences data structures to JavaScript object
1068 * @param engine - JS engine to put object
1069 * @param tmpPref - preferences to convert
1070 * @param whereToPutInJS - variable name to store preferences in JS
1071 * @param includeDefaults - include known default values to JS objects
1072 * @throws ScriptException
1073 */
1074 public static void loadPrefsToJS(ScriptEngine engine, Preferences tmpPref, String whereToPutInJS, boolean includeDefaults) throws ScriptException {
1075 Map<String, String> stringMap = new TreeMap<String, String>();
1076 Map<String, List<String>> listMap = new TreeMap<String, List<String>>();
1077 Map<String, List<List<String>>> listlistMap = new TreeMap<String, List<List<String>>>();
1078 Map<String, List<Map<String, String>>> listmapMap = new TreeMap<String, List<Map<String, String>>>();
1079
1080 if (includeDefaults) {
1081 stringMap.putAll(tmpPref.defaults);
1082 listMap.putAll(tmpPref.collectionDefaults);
1083 listlistMap.putAll(tmpPref.arrayDefaults);
1084 listmapMap.putAll(tmpPref.listOfStructsDefaults);
1085 }
1086
1087 while (stringMap.values().remove(null)) { };
1088 while (listMap.values().remove(null)) { };
1089 while (listlistMap.values().remove(null)) { };
1090 while (listmapMap.values().remove(null)) { };
1091
1092 stringMap.putAll(tmpPref.properties);
1093 listMap.putAll(tmpPref.collectionProperties);
1094 listlistMap.putAll(tmpPref.arrayProperties);
1095 listmapMap.putAll(tmpPref.listOfStructsProperties);
1096
1097 engine.put("stringMap", stringMap);
1098 engine.put("listMap", listMap);
1099 engine.put("listlistMap", listlistMap);
1100 engine.put("listmapMap", listmapMap);
1101
1102 String init =
1103 "function getJSList( javaList ) {"+
1104 " var jsList; var i; "+
1105 " if (javaList == null) return null;"+
1106 "jsList = [];"+
1107 " for (i = 0; i < javaList.size(); i++) {"+
1108 " jsList.push(String(list.get(i)));"+
1109 " }"+
1110 "return jsList;"+
1111 "}"+
1112 "function getJSMap( javaMap ) {"+
1113 " var jsMap; var it; var e; "+
1114 " if (javaMap == null) return null;"+
1115 " jsMap = {};"+
1116 " for (it = javaMap.entrySet().iterator(); it.hasNext();) {"+
1117 " e = it.next();"+
1118 " jsMap[ String(e.getKey()) ] = String(e.getValue()); "+
1119 " }"+
1120 " return jsMap;"+
1121 "}"+
1122 "for (it = stringMap.entrySet().iterator(); it.hasNext();) {"+
1123 " e = it.next();"+
1124 whereToPutInJS+"[String(e.getKey())] = String(e.getValue());"+
1125 "}\n"+
1126 "for (it = listMap.entrySet().iterator(); it.hasNext();) {"+
1127 " e = it.next();"+
1128 " list = e.getValue();"+
1129 " jslist = getJSList(list);"+
1130 " jslist.type = 'list';"+
1131 whereToPutInJS+"[String(e.getKey())] = jslist;"+
1132 "}\n"+
1133 "for (it = listlistMap.entrySet().iterator(); it.hasNext(); ) {"+
1134 " e = it.next();"+
1135 " listlist = e.getValue();"+
1136 " jslistlist = [];"+
1137 " for (it2 = listlist.iterator(); it2.hasNext(); ) {"+
1138 " list = it2.next(); "+
1139 " jslistlist.push(getJSList(list));"+
1140 " }"+
1141 " jslistlist.type = 'listlist';"+
1142 whereToPutInJS+"[String(e.getKey())] = jslistlist;"+
1143 "}\n"+
1144 "for (it = listmapMap.entrySet().iterator(); it.hasNext();) {"+
1145 " e = it.next();"+
1146 " listmap = e.getValue();"+
1147 " jslistmap = [];"+
1148 " for (it2 = listmap.iterator(); it2.hasNext();) {"+
1149 " map = it2.next();"+
1150 " jslistmap.push(getJSMap(map));"+
1151 " }"+
1152 " jslistmap.type = 'listmap';"+
1153 whereToPutInJS+"[String(e.getKey())] = jslistmap;"+
1154 "}\n";
1155
1156 //System.out.println("map1: "+stringMap );
1157 //System.out.println("lists1: "+listMap );
1158 //System.out.println("listlist1: "+listlistMap );
1159 //System.out.println("listmap1: "+listmapMap );
1160
1161 // Execute conversion script
1162 engine.eval(init);
1163
1164 }
1165 }
1166}
Note: See TracBrowser for help on using the repository browser.