1 | // License: GPL. For details, see LICENSE file.
|
---|
2 | package org.openstreetmap.josm.io.session;
|
---|
3 |
|
---|
4 | import static org.openstreetmap.josm.tools.I18n.tr;
|
---|
5 | import static org.openstreetmap.josm.tools.Utils.equal;
|
---|
6 |
|
---|
7 | import java.awt.Component;
|
---|
8 | import java.io.BufferedInputStream;
|
---|
9 | import java.io.IOException;
|
---|
10 | import java.io.InputStream;
|
---|
11 | import java.io.File;
|
---|
12 | import java.io.FileInputStream;
|
---|
13 | import java.io.FileNotFoundException;
|
---|
14 | import java.lang.reflect.InvocationTargetException;
|
---|
15 | import java.util.ArrayList;
|
---|
16 | import java.util.Collections;
|
---|
17 | import java.util.Enumeration;
|
---|
18 | import java.util.HashMap;
|
---|
19 | import java.util.LinkedHashMap;
|
---|
20 | import java.util.List;
|
---|
21 | import java.util.Map;
|
---|
22 | import java.util.Map.Entry;
|
---|
23 | import java.util.TreeMap;
|
---|
24 | import java.util.zip.ZipEntry;
|
---|
25 | import java.util.zip.ZipException;
|
---|
26 | import java.util.zip.ZipFile;
|
---|
27 | import java.net.URI;
|
---|
28 | import java.net.URISyntaxException;
|
---|
29 |
|
---|
30 | import javax.swing.JOptionPane;
|
---|
31 | import javax.swing.SwingUtilities;
|
---|
32 | import javax.xml.parsers.DocumentBuilder;
|
---|
33 | import javax.xml.parsers.DocumentBuilderFactory;
|
---|
34 | import javax.xml.parsers.ParserConfigurationException;
|
---|
35 |
|
---|
36 | import org.w3c.dom.Document;
|
---|
37 | import org.w3c.dom.Element;
|
---|
38 | import org.w3c.dom.Node;
|
---|
39 | import org.w3c.dom.NodeList;
|
---|
40 | import org.xml.sax.SAXException;
|
---|
41 |
|
---|
42 | import org.openstreetmap.josm.Main;
|
---|
43 | import org.openstreetmap.josm.gui.ExtendedDialog;
|
---|
44 | import org.openstreetmap.josm.gui.layer.Layer;
|
---|
45 | import org.openstreetmap.josm.gui.progress.NullProgressMonitor;
|
---|
46 | import org.openstreetmap.josm.gui.progress.PleaseWaitProgressMonitor;
|
---|
47 | import org.openstreetmap.josm.gui.progress.ProgressMonitor;
|
---|
48 | import org.openstreetmap.josm.io.IllegalDataException;
|
---|
49 | import org.openstreetmap.josm.tools.MultiMap;
|
---|
50 | import org.openstreetmap.josm.tools.Utils;
|
---|
51 |
|
---|
52 | /**
|
---|
53 | * Reads a .jos session file and loads the layers in the process.
|
---|
54 | *
|
---|
55 | */
|
---|
56 | public class SessionReader {
|
---|
57 |
|
---|
58 | private static Map<String, Class<? extends SessionLayerImporter>> sessionLayerImporters = new HashMap<String, Class<? extends SessionLayerImporter>>();
|
---|
59 | static {
|
---|
60 | registerSessionLayerImporter("osm-data", OsmDataSessionImporter.class);
|
---|
61 | }
|
---|
62 |
|
---|
63 | public static void registerSessionLayerImporter(String layerType, Class<? extends SessionLayerImporter> importer) {
|
---|
64 | sessionLayerImporters.put(layerType, importer);
|
---|
65 | }
|
---|
66 |
|
---|
67 | public static SessionLayerImporter getSessionLayerImporter(String layerType) {
|
---|
68 | Class<? extends SessionLayerImporter> importerClass = sessionLayerImporters.get(layerType);
|
---|
69 | if (importerClass == null)
|
---|
70 | return null;
|
---|
71 | SessionLayerImporter importer = null;
|
---|
72 | try {
|
---|
73 | importer = importerClass.newInstance();
|
---|
74 | } catch (InstantiationException e) {
|
---|
75 | throw new RuntimeException(e);
|
---|
76 | } catch (IllegalAccessException e) {
|
---|
77 | throw new RuntimeException(e);
|
---|
78 | }
|
---|
79 | return importer;
|
---|
80 | }
|
---|
81 |
|
---|
82 | private File sessionFile;
|
---|
83 | private boolean zip; /* true, if session file is a .joz file; false if it is a .jos file */
|
---|
84 | private ZipFile zipFile;
|
---|
85 | private List<Layer> layers = new ArrayList<Layer>();
|
---|
86 | private List<Runnable> postLoadTasks = new ArrayList<Runnable>();
|
---|
87 |
|
---|
88 | /**
|
---|
89 | * @return list of layers that are later added to the mapview
|
---|
90 | */
|
---|
91 | public List<Layer> getLayers() {
|
---|
92 | return layers;
|
---|
93 | }
|
---|
94 |
|
---|
95 | /**
|
---|
96 | * @return actions executed in EDT after layers have been added (message dialog, etc.)
|
---|
97 | */
|
---|
98 | public List<Runnable> getPostLoadTasks() {
|
---|
99 | return postLoadTasks;
|
---|
100 | }
|
---|
101 |
|
---|
102 | public class ImportSupport {
|
---|
103 |
|
---|
104 | private String layerName;
|
---|
105 | private int layerIndex;
|
---|
106 | private LinkedHashMap<Integer,SessionLayerImporter> layerDependencies;
|
---|
107 |
|
---|
108 | public ImportSupport(String layerName, int layerIndex, LinkedHashMap<Integer,SessionLayerImporter> layerDependencies) {
|
---|
109 | this.layerName = layerName;
|
---|
110 | this.layerIndex = layerIndex;
|
---|
111 | this.layerDependencies = layerDependencies;
|
---|
112 | }
|
---|
113 |
|
---|
114 | /**
|
---|
115 | * Path of the file inside the zip archive.
|
---|
116 | * Used as alternative return value for getFile method.
|
---|
117 | */
|
---|
118 | private String inZipPath;
|
---|
119 |
|
---|
120 | /**
|
---|
121 | * Add a task, e.g. a message dialog, that should
|
---|
122 | * be executed in EDT after all layers have been added.
|
---|
123 | */
|
---|
124 | public void addPostLayersTask(Runnable task) {
|
---|
125 | postLoadTasks.add(task);
|
---|
126 | }
|
---|
127 |
|
---|
128 | /**
|
---|
129 | * Return an InputStream for a URI from a .jos/.joz file.
|
---|
130 | *
|
---|
131 | * The following forms are supported:
|
---|
132 | *
|
---|
133 | * - absolute file (both .jos and .joz):
|
---|
134 | * "file:///home/user/data.osm"
|
---|
135 | * "file:/home/user/data.osm"
|
---|
136 | * "file:///C:/files/data.osm"
|
---|
137 | * "file:/C:/file/data.osm"
|
---|
138 | * "/home/user/data.osm"
|
---|
139 | * "C:\files\data.osm" (not a URI, but recognized by File constructor on Windows systems)
|
---|
140 | * - standalone .jos files:
|
---|
141 | * - relative uri:
|
---|
142 | * "save/data.osm"
|
---|
143 | * "../project2/data.osm"
|
---|
144 | * - for .joz files:
|
---|
145 | * - file inside zip archive:
|
---|
146 | * "layers/01/data.osm"
|
---|
147 | * - relativ to the .joz file:
|
---|
148 | * "../save/data.osm" ("../" steps out of the archive)
|
---|
149 | *
|
---|
150 | * @throws IOException Thrown when no Stream can be opened for the given URI, e.g. when the linked file has been deleted.
|
---|
151 | */
|
---|
152 | public InputStream getInputStream(String uriStr) throws IOException {
|
---|
153 | File file = getFile(uriStr);
|
---|
154 | try {
|
---|
155 | if (file != null) {
|
---|
156 | return new BufferedInputStream(new FileInputStream(file));
|
---|
157 | } else if (inZipPath != null) {
|
---|
158 | ZipEntry entry = zipFile.getEntry(inZipPath);
|
---|
159 | if (entry != null) {
|
---|
160 | InputStream is = zipFile.getInputStream(entry);
|
---|
161 | return is;
|
---|
162 | }
|
---|
163 | }
|
---|
164 | } catch (FileNotFoundException e) {
|
---|
165 | throw new IOException(tr("File ''{0}'' does not exist.", file.getPath()));
|
---|
166 | }
|
---|
167 | throw new IOException(tr("Unable to locate file ''{0}''.", uriStr));
|
---|
168 | }
|
---|
169 |
|
---|
170 | /**
|
---|
171 | * Return a File for a URI from a .jos file.
|
---|
172 | *
|
---|
173 | * Returns null if the URI points to a file inside the zip archive.
|
---|
174 | * In this case, inZipPath will be set to the corresponding path.
|
---|
175 | */
|
---|
176 | public File getFile(String uriStr) throws IOException {
|
---|
177 | inZipPath = null;
|
---|
178 | try {
|
---|
179 | URI uri = new URI(uriStr);
|
---|
180 | if ("file".equals(uri.getScheme())) {
|
---|
181 | // absolute path
|
---|
182 | return new File(uri);
|
---|
183 | } else if (uri.getScheme() == null) {
|
---|
184 | // Check if this is an absolute path without 'file:' scheme part.
|
---|
185 | // At this point, (as an exception) platform dependent path separator will be recognized.
|
---|
186 | // (This form is discouraged, only for users that like to copy and paste a path manually.)
|
---|
187 | File file = new File(uriStr);
|
---|
188 | if (file.isAbsolute()) {
|
---|
189 | return file;
|
---|
190 | } else {
|
---|
191 | // for relative paths, only forward slashes are permitted
|
---|
192 | if (isZip()) {
|
---|
193 | if (uri.getPath().startsWith("../")) {
|
---|
194 | // relative to session file - "../" step out of the archive
|
---|
195 | String relPath = uri.getPath().substring(3);
|
---|
196 | return new File(sessionFile.toURI().resolve(relPath));
|
---|
197 | } else {
|
---|
198 | // file inside zip archive
|
---|
199 | inZipPath = uriStr;
|
---|
200 | return null;
|
---|
201 | }
|
---|
202 | } else {
|
---|
203 | return new File(sessionFile.toURI().resolve(uri));
|
---|
204 | }
|
---|
205 | }
|
---|
206 | } else {
|
---|
207 | throw new IOException(tr("Unsupported scheme ''{0}'' in URI ''{1}''.", uri.getScheme(), uriStr));
|
---|
208 | }
|
---|
209 | } catch (URISyntaxException e) {
|
---|
210 | throw new IOException(e);
|
---|
211 | }
|
---|
212 | }
|
---|
213 |
|
---|
214 | /**
|
---|
215 | * Returns true if we are reading from a .joz file.
|
---|
216 | */
|
---|
217 | public boolean isZip() {
|
---|
218 | return zip;
|
---|
219 | }
|
---|
220 |
|
---|
221 | /**
|
---|
222 | * Name of the layer that is currently imported.
|
---|
223 | */
|
---|
224 | public String getLayerName() {
|
---|
225 | return layerName;
|
---|
226 | }
|
---|
227 |
|
---|
228 | /**
|
---|
229 | * Index of the layer that is currently imported.
|
---|
230 | */
|
---|
231 | public int getLayerIndex() {
|
---|
232 | return layerIndex;
|
---|
233 | }
|
---|
234 |
|
---|
235 | /**
|
---|
236 | * Dependencies - maps the layer index to the importer of the given
|
---|
237 | * layer. All the dependent importers have loaded completely at this point.
|
---|
238 | */
|
---|
239 | public LinkedHashMap<Integer,SessionLayerImporter> getLayerDependencies() {
|
---|
240 | return layerDependencies;
|
---|
241 | }
|
---|
242 | }
|
---|
243 |
|
---|
244 | private void error(String msg) throws IllegalDataException {
|
---|
245 | throw new IllegalDataException(msg);
|
---|
246 | }
|
---|
247 |
|
---|
248 | private void parseJos(Document doc, ProgressMonitor progressMonitor) throws IllegalDataException {
|
---|
249 | Element root = doc.getDocumentElement();
|
---|
250 | if (!equal(root.getTagName(), "josm-session")) {
|
---|
251 | error(tr("Unexpected root element ''{0}'' in session file", root.getTagName()));
|
---|
252 | }
|
---|
253 | String version = root.getAttribute("version");
|
---|
254 | if (!"0.1".equals(version)) {
|
---|
255 | error(tr("Version ''{0}'' of session file is not supported. Expected: 0.1", version));
|
---|
256 | }
|
---|
257 |
|
---|
258 | NodeList layersNL = root.getElementsByTagName("layers");
|
---|
259 | if (layersNL.getLength() == 0) return;
|
---|
260 |
|
---|
261 | Element layersEl = (Element) layersNL.item(0);
|
---|
262 |
|
---|
263 | MultiMap<Integer, Integer> deps = new MultiMap<Integer, Integer>();
|
---|
264 | Map<Integer, Element> elems = new HashMap<Integer, Element>();
|
---|
265 |
|
---|
266 | NodeList nodes = layersEl.getChildNodes();
|
---|
267 |
|
---|
268 | for (int i=0; i<nodes.getLength(); ++i) {
|
---|
269 | Node node = nodes.item(i);
|
---|
270 | if (node.getNodeType() == Node.ELEMENT_NODE) {
|
---|
271 | Element e = (Element) node;
|
---|
272 | if (equal(e.getTagName(), "layer")) {
|
---|
273 |
|
---|
274 | if (!e.hasAttribute("index")) {
|
---|
275 | error(tr("missing mandatory attribute ''index'' for element ''layer''"));
|
---|
276 | }
|
---|
277 | Integer idx = null;
|
---|
278 | try {
|
---|
279 | idx = Integer.parseInt(e.getAttribute("index"));
|
---|
280 | } catch (NumberFormatException ex) {}
|
---|
281 | if (idx == null) {
|
---|
282 | error(tr("unexpected format of attribute ''index'' for element ''layer''"));
|
---|
283 | }
|
---|
284 | if (elems.containsKey(idx)) {
|
---|
285 | error(tr("attribute ''index'' ({0}) for element ''layer'' must be unique", Integer.toString(idx)));
|
---|
286 | }
|
---|
287 | elems.put(idx, e);
|
---|
288 |
|
---|
289 | deps.putVoid(idx);
|
---|
290 | String depStr = e.getAttribute("depends");
|
---|
291 | if (depStr != null) {
|
---|
292 | for (String sd : depStr.split(",")) {
|
---|
293 | Integer d = null;
|
---|
294 | try {
|
---|
295 | d = Integer.parseInt(sd);
|
---|
296 | } catch (NumberFormatException ex) {}
|
---|
297 | if (d != null) {
|
---|
298 | deps.put(idx, d);
|
---|
299 | }
|
---|
300 | }
|
---|
301 | }
|
---|
302 | }
|
---|
303 | }
|
---|
304 | }
|
---|
305 |
|
---|
306 | List<Integer> sorted = Utils.topologicalSort(deps);
|
---|
307 | final Map<Integer, Layer> layersMap = new TreeMap<Integer, Layer>(Collections.reverseOrder());
|
---|
308 | final Map<Integer, SessionLayerImporter> importers = new HashMap<Integer, SessionLayerImporter>();
|
---|
309 | final Map<Integer, String> names = new HashMap<Integer, String>();
|
---|
310 |
|
---|
311 | progressMonitor.setTicksCount(sorted.size());
|
---|
312 | LAYER: for (int idx: sorted) {
|
---|
313 | Element e = elems.get(idx);
|
---|
314 | if (e == null) {
|
---|
315 | error(tr("missing layer with index {0}", idx));
|
---|
316 | }
|
---|
317 | if (!e.hasAttribute("name")) {
|
---|
318 | error(tr("missing mandatory attribute ''name'' for element ''layer''"));
|
---|
319 | }
|
---|
320 | String name = e.getAttribute("name");
|
---|
321 | names.put(idx, name);
|
---|
322 | if (!e.hasAttribute("type")) {
|
---|
323 | error(tr("missing mandatory attribute ''type'' for element ''layer''"));
|
---|
324 | }
|
---|
325 | String type = e.getAttribute("type");
|
---|
326 | SessionLayerImporter imp = getSessionLayerImporter(type);
|
---|
327 | if (imp == null) {
|
---|
328 | CancelOrContinueDialog dialog = new CancelOrContinueDialog();
|
---|
329 | dialog.show(
|
---|
330 | tr("Unable to load layer"),
|
---|
331 | tr("Cannot load layer of type ''{0}'' because no suitable importer was found.", type),
|
---|
332 | JOptionPane.WARNING_MESSAGE,
|
---|
333 | progressMonitor
|
---|
334 | );
|
---|
335 | if (dialog.isCancel()) {
|
---|
336 | progressMonitor.cancel();
|
---|
337 | return;
|
---|
338 | } else {
|
---|
339 | continue;
|
---|
340 | }
|
---|
341 | } else {
|
---|
342 | importers.put(idx, imp);
|
---|
343 | LinkedHashMap<Integer,SessionLayerImporter> depsImp = new LinkedHashMap<Integer,SessionLayerImporter>();
|
---|
344 | for (int d : deps.get(idx)) {
|
---|
345 | SessionLayerImporter dImp = importers.get(d);
|
---|
346 | if (dImp == null) {
|
---|
347 | CancelOrContinueDialog dialog = new CancelOrContinueDialog();
|
---|
348 | dialog.show(
|
---|
349 | tr("Unable to load layer"),
|
---|
350 | tr("Cannot load layer {0} because it depends no layer {1} which has been skipped.", idx, d),
|
---|
351 | JOptionPane.WARNING_MESSAGE,
|
---|
352 | progressMonitor
|
---|
353 | );
|
---|
354 | if (dialog.isCancel()) {
|
---|
355 | progressMonitor.cancel();
|
---|
356 | return;
|
---|
357 | } else {
|
---|
358 | continue LAYER;
|
---|
359 | }
|
---|
360 | }
|
---|
361 | depsImp.put(d, dImp);
|
---|
362 | }
|
---|
363 | ImportSupport support = new ImportSupport(name, idx, depsImp);
|
---|
364 | Layer layer = null;
|
---|
365 | Exception exception = null;
|
---|
366 | try {
|
---|
367 | layer = imp.load(e, support, progressMonitor.createSubTaskMonitor(1, false));
|
---|
368 | } catch (IllegalDataException ex) {
|
---|
369 | exception = ex;
|
---|
370 | } catch (IOException ex) {
|
---|
371 | exception = ex;
|
---|
372 | }
|
---|
373 | if (exception != null) {
|
---|
374 | exception.printStackTrace();
|
---|
375 | CancelOrContinueDialog dialog = new CancelOrContinueDialog();
|
---|
376 | dialog.show(
|
---|
377 | tr("Error loading layer"),
|
---|
378 | tr("<html>Could not load layer {0} ''{1}''.<br>Error is:<br>{2}</html>", idx, name, exception.getMessage()),
|
---|
379 | JOptionPane.ERROR_MESSAGE,
|
---|
380 | progressMonitor
|
---|
381 | );
|
---|
382 | if (dialog.isCancel()) {
|
---|
383 | progressMonitor.cancel();
|
---|
384 | return;
|
---|
385 | } else {
|
---|
386 | continue;
|
---|
387 | }
|
---|
388 | }
|
---|
389 |
|
---|
390 | if (layer == null) throw new RuntimeException();
|
---|
391 | layersMap.put(idx, layer);
|
---|
392 | }
|
---|
393 | progressMonitor.worked(1);
|
---|
394 | }
|
---|
395 |
|
---|
396 | layers = new ArrayList<Layer>();
|
---|
397 | for (Entry<Integer, Layer> e : layersMap.entrySet()) {
|
---|
398 | Layer l = e.getValue();
|
---|
399 | if (l == null) continue;
|
---|
400 | l.setName(names.get(e.getKey()));
|
---|
401 | layers.add(l);
|
---|
402 | }
|
---|
403 | }
|
---|
404 |
|
---|
405 | /**
|
---|
406 | * Show Dialog when there is an error for one layer.
|
---|
407 | * Ask the user whether to cancel the complete session loading or just to skip this layer.
|
---|
408 | *
|
---|
409 | * This is expected to run in a worker thread (PleaseWaitRunnable), so invokeAndWait is
|
---|
410 | * needed to block the current thread and wait for the result of the modal dialog from EDT.
|
---|
411 | */
|
---|
412 | private class CancelOrContinueDialog {
|
---|
413 |
|
---|
414 | private boolean cancel;
|
---|
415 |
|
---|
416 | public void show(final String title, final String message, final int icon, final ProgressMonitor progressMonitor) {
|
---|
417 | try {
|
---|
418 | SwingUtilities.invokeAndWait(new Runnable() {
|
---|
419 | @Override public void run() {
|
---|
420 | Component parent;
|
---|
421 | if (progressMonitor instanceof PleaseWaitProgressMonitor) {
|
---|
422 | parent = ((PleaseWaitProgressMonitor) progressMonitor).getDialog();
|
---|
423 | } else {
|
---|
424 | parent = Main.parent;
|
---|
425 | }
|
---|
426 | ExtendedDialog dlg = new ExtendedDialog(
|
---|
427 | parent,
|
---|
428 | title,
|
---|
429 | new String[] { tr("Cancel"), tr("Skip layer and continue") }
|
---|
430 | );
|
---|
431 | dlg.setButtonIcons(new String[] {"cancel", "dialogs/next"});
|
---|
432 | dlg.setIcon(icon);
|
---|
433 | dlg.setContent(message);
|
---|
434 | dlg.showDialog();
|
---|
435 | cancel = dlg.getValue() != 2;
|
---|
436 | }
|
---|
437 | });
|
---|
438 | } catch (InvocationTargetException ex) {
|
---|
439 | throw new RuntimeException(ex);
|
---|
440 | } catch (InterruptedException ex) {
|
---|
441 | throw new RuntimeException(ex);
|
---|
442 | }
|
---|
443 | }
|
---|
444 |
|
---|
445 | public boolean isCancel() {
|
---|
446 | return cancel;
|
---|
447 | }
|
---|
448 | }
|
---|
449 |
|
---|
450 | public void loadSession(File sessionFile, boolean zip, ProgressMonitor progressMonitor) throws IllegalDataException, IOException {
|
---|
451 | if (progressMonitor == null) {
|
---|
452 | progressMonitor = NullProgressMonitor.INSTANCE;
|
---|
453 | }
|
---|
454 | this.sessionFile = sessionFile;
|
---|
455 | this.zip = zip;
|
---|
456 |
|
---|
457 | InputStream josIS = null;
|
---|
458 |
|
---|
459 | if (zip) {
|
---|
460 | try {
|
---|
461 | zipFile = new ZipFile(sessionFile);
|
---|
462 | ZipEntry josEntry = null;
|
---|
463 | Enumeration<? extends ZipEntry> entries = zipFile.entries();
|
---|
464 | while (entries.hasMoreElements()) {
|
---|
465 | ZipEntry entry = entries.nextElement();
|
---|
466 | if (entry.getName().toLowerCase().endsWith(".jos")) {
|
---|
467 | josEntry = entry;
|
---|
468 | break;
|
---|
469 | }
|
---|
470 | }
|
---|
471 | if (josEntry == null) {
|
---|
472 | error(tr("expected .jos file inside .joz archive"));
|
---|
473 | }
|
---|
474 | josIS = zipFile.getInputStream(josEntry);
|
---|
475 | } catch (ZipException ze) {
|
---|
476 | throw new IOException(ze);
|
---|
477 | }
|
---|
478 | } else {
|
---|
479 | try {
|
---|
480 | josIS = new FileInputStream(sessionFile);
|
---|
481 | } catch (FileNotFoundException ex) {
|
---|
482 | throw new IOException(ex);
|
---|
483 | }
|
---|
484 | }
|
---|
485 |
|
---|
486 | try {
|
---|
487 | DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
|
---|
488 | builderFactory.setValidating(false);
|
---|
489 | builderFactory.setNamespaceAware(true);
|
---|
490 | DocumentBuilder builder = builderFactory.newDocumentBuilder();
|
---|
491 | Document document = builder.parse(josIS);
|
---|
492 | parseJos(document, progressMonitor);
|
---|
493 | } catch (SAXException e) {
|
---|
494 | throw new IllegalDataException(e);
|
---|
495 | } catch (ParserConfigurationException e) {
|
---|
496 | throw new IOException(e);
|
---|
497 | }
|
---|
498 | }
|
---|
499 |
|
---|
500 | }
|
---|