source: josm/trunk/src/org/openstreetmap/josm/io/session/SessionReader.java@ 5501

Last change on this file since 5501 was 5501, checked in by bastiK, 12 years ago

add session support for gpx layers (see #4029)

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