source: josm/trunk/src/org/openstreetmap/josm/io/session/SessionWriter.java@ 12630

Last change on this file since 12630 was 12630, checked in by Don-vip, 7 years ago

see #15182 - deprecate Main.map and Main.isDisplayingMapView(). Replacements: gui.MainApplication.getMap() / gui.MainApplication.isDisplayingMapView()

  • Property svn:eol-style set to native
File size: 13.9 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.io.session;
3
4import java.io.BufferedOutputStream;
5import java.io.File;
6import java.io.FileNotFoundException;
7import java.io.FileOutputStream;
8import java.io.IOException;
9import java.io.OutputStream;
10import java.io.OutputStreamWriter;
11import java.nio.charset.StandardCharsets;
12import java.util.ArrayList;
13import java.util.Collection;
14import java.util.HashMap;
15import java.util.List;
16import java.util.Map;
17import java.util.Set;
18import java.util.zip.ZipEntry;
19import java.util.zip.ZipOutputStream;
20
21import javax.xml.parsers.DocumentBuilder;
22import javax.xml.parsers.ParserConfigurationException;
23import javax.xml.transform.OutputKeys;
24import javax.xml.transform.Transformer;
25import javax.xml.transform.TransformerException;
26import javax.xml.transform.TransformerFactory;
27import javax.xml.transform.dom.DOMSource;
28import javax.xml.transform.stream.StreamResult;
29
30import org.openstreetmap.josm.Main;
31import org.openstreetmap.josm.data.coor.EastNorth;
32import org.openstreetmap.josm.data.coor.LatLon;
33import org.openstreetmap.josm.data.projection.Projections;
34import org.openstreetmap.josm.gui.MainApplication;
35import org.openstreetmap.josm.gui.MapView;
36import org.openstreetmap.josm.gui.layer.GpxLayer;
37import org.openstreetmap.josm.gui.layer.Layer;
38import org.openstreetmap.josm.gui.layer.NoteLayer;
39import org.openstreetmap.josm.gui.layer.OsmDataLayer;
40import org.openstreetmap.josm.gui.layer.TMSLayer;
41import org.openstreetmap.josm.gui.layer.WMSLayer;
42import org.openstreetmap.josm.gui.layer.WMTSLayer;
43import org.openstreetmap.josm.gui.layer.geoimage.GeoImageLayer;
44import org.openstreetmap.josm.gui.layer.markerlayer.MarkerLayer;
45import org.openstreetmap.josm.gui.preferences.projection.ProjectionPreference;
46import org.openstreetmap.josm.tools.JosmRuntimeException;
47import org.openstreetmap.josm.tools.Logging;
48import org.openstreetmap.josm.tools.MultiMap;
49import org.openstreetmap.josm.tools.Utils;
50import org.w3c.dom.Document;
51import org.w3c.dom.Element;
52import org.w3c.dom.Text;
53
54/**
55 * Writes a .jos session file from current supported layers.
56 * @since 4685
57 */
58public class SessionWriter {
59
60 private static Map<Class<? extends Layer>, Class<? extends SessionLayerExporter>> sessionLayerExporters = new HashMap<>();
61
62 private final List<Layer> layers;
63 private final int active;
64 private final Map<Layer, SessionLayerExporter> exporters;
65 private final MultiMap<Layer, Layer> dependencies;
66 private final boolean zip;
67
68 private ZipOutputStream zipOut;
69
70 static {
71 registerSessionLayerExporter(OsmDataLayer.class, OsmDataSessionExporter.class);
72 registerSessionLayerExporter(TMSLayer.class, ImagerySessionExporter.class);
73 registerSessionLayerExporter(WMSLayer.class, ImagerySessionExporter.class);
74 registerSessionLayerExporter(WMTSLayer.class, ImagerySessionExporter.class);
75 registerSessionLayerExporter(GpxLayer.class, GpxTracksSessionExporter.class);
76 registerSessionLayerExporter(GeoImageLayer.class, GeoImageSessionExporter.class);
77 registerSessionLayerExporter(MarkerLayer.class, MarkerSessionExporter.class);
78 registerSessionLayerExporter(NoteLayer.class, NoteSessionExporter.class);
79 }
80
81 /**
82 * Register a session layer exporter.
83 *
84 * The exporter class must have a one-argument constructor with layerClass as formal parameter type.
85 * @param layerClass layer class
86 * @param exporter exporter for this layer class
87 */
88 public static void registerSessionLayerExporter(Class<? extends Layer> layerClass, Class<? extends SessionLayerExporter> exporter) {
89 sessionLayerExporters.put(layerClass, exporter);
90 }
91
92 /**
93 * Returns the session layer exporter for the given layer.
94 * @param layer layer to export
95 * @return session layer exporter for the given layer
96 */
97 public static SessionLayerExporter getSessionLayerExporter(Layer layer) {
98 Class<? extends Layer> layerClass = layer.getClass();
99 Class<? extends SessionLayerExporter> exporterClass = sessionLayerExporters.get(layerClass);
100 if (exporterClass == null)
101 return null;
102 try {
103 return exporterClass.getConstructor(layerClass).newInstance(layer);
104 } catch (ReflectiveOperationException e) {
105 throw new JosmRuntimeException(e);
106 }
107 }
108
109 /**
110 * Constructs a new {@code SessionWriter}.
111 * @param layers The ordered list of layers to save
112 * @param active The index of active layer in {@code layers} (starts at 0). Ignored if set to -1
113 * @param exporters The exporters to use to save layers
114 * @param dependencies layer dependencies
115 * @param zip {@code true} if a joz archive has to be created, {@code false otherwise}
116 * @since 6271
117 */
118 public SessionWriter(List<Layer> layers, int active, Map<Layer, SessionLayerExporter> exporters,
119 MultiMap<Layer, Layer> dependencies, boolean zip) {
120 this.layers = layers;
121 this.active = active;
122 this.exporters = exporters;
123 this.dependencies = dependencies;
124 this.zip = zip;
125 }
126
127 /**
128 * A class that provides some context for the individual {@link SessionLayerExporter}
129 * when doing the export.
130 */
131 public class ExportSupport {
132 private final Document doc;
133 private final int layerIndex;
134
135 /**
136 * Constructs a new {@code ExportSupport}.
137 * @param doc XML document
138 * @param layerIndex layer index
139 */
140 public ExportSupport(Document doc, int layerIndex) {
141 this.doc = doc;
142 this.layerIndex = layerIndex;
143 }
144
145 /**
146 * Creates an element of the type specified.
147 * @param name The name of the element type to instantiate
148 * @return A new {@code Element} object
149 * @see Document#createElement
150 */
151 public Element createElement(String name) {
152 return doc.createElement(name);
153 }
154
155 /**
156 * Creates a text node given the specified string.
157 * @param text The data for the node.
158 * @return The new {@code Text} object.
159 * @see Document#createTextNode
160 */
161 public Text createTextNode(String text) {
162 return doc.createTextNode(text);
163 }
164
165 /**
166 * Get the index of the layer that is currently exported.
167 * @return the index of the layer that is currently exported
168 */
169 public int getLayerIndex() {
170 return layerIndex;
171 }
172
173 /**
174 * Create a file inside the zip archive.
175 *
176 * @param zipPath the path inside the zip archive, e.g. "layers/03/data.xml"
177 * @return the OutputStream you can write to. Never close the returned
178 * output stream, but make sure to flush buffers.
179 * @throws IOException if any I/O error occurs
180 */
181 public OutputStream getOutputStreamZip(String zipPath) throws IOException {
182 if (!isZip()) throw new JosmRuntimeException("not zip");
183 ZipEntry entry = new ZipEntry(zipPath);
184 zipOut.putNextEntry(entry);
185 return zipOut;
186 }
187
188 /**
189 * Check, if the session is exported as a zip archive.
190 *
191 * @return true, if the session is exported as a zip archive (.joz file
192 * extension). It will always return true, if one of the
193 * {@link SessionLayerExporter} returns true for the
194 * {@link SessionLayerExporter#requiresZip()} method. Otherwise, the
195 * user can decide in the file chooser dialog.
196 */
197 public boolean isZip() {
198 return zip;
199 }
200 }
201
202 /**
203 * Creates XML (.jos) session document.
204 * @return new document
205 * @throws IOException if any I/O error occurs
206 */
207 public Document createJosDocument() throws IOException {
208 DocumentBuilder builder = null;
209 try {
210 builder = Utils.newSafeDOMBuilder();
211 } catch (ParserConfigurationException e) {
212 throw new IOException(e);
213 }
214 Document doc = builder.newDocument();
215
216 Element root = doc.createElement("josm-session");
217 root.setAttribute("version", "0.1");
218 doc.appendChild(root);
219
220 writeViewPort(root);
221 writeProjection(root);
222
223 Element layersEl = doc.createElement("layers");
224 if (active >= 0) {
225 layersEl.setAttribute("active", Integer.toString(active+1));
226 }
227 root.appendChild(layersEl);
228
229 for (int index = 0; index < layers.size(); ++index) {
230 Layer layer = layers.get(index);
231 SessionLayerExporter exporter = exporters.get(layer);
232 ExportSupport support = new ExportSupport(doc, index+1);
233 Element el = exporter.export(support);
234 el.setAttribute("index", Integer.toString(index+1));
235 el.setAttribute("name", layer.getName());
236 el.setAttribute("visible", Boolean.toString(layer.isVisible()));
237 if (!Utils.equalsEpsilon(layer.getOpacity(), 1.0)) {
238 el.setAttribute("opacity", Double.toString(layer.getOpacity()));
239 }
240 Set<Layer> deps = dependencies.get(layer);
241 if (deps != null && !deps.isEmpty()) {
242 List<Integer> depsInt = new ArrayList<>();
243 for (Layer depLayer : deps) {
244 int depIndex = layers.indexOf(depLayer);
245 if (depIndex == -1) {
246 Logging.warn("Unable to find " + depLayer);
247 } else {
248 depsInt.add(depIndex+1);
249 }
250 }
251 if (!depsInt.isEmpty()) {
252 el.setAttribute("depends", Utils.join(",", depsInt));
253 }
254 }
255 layersEl.appendChild(el);
256 }
257 return doc;
258 }
259
260 private static void writeViewPort(Element root) {
261 Document doc = root.getOwnerDocument();
262 Element viewportEl = doc.createElement("viewport");
263 root.appendChild(viewportEl);
264 Element centerEl = doc.createElement("center");
265 viewportEl.appendChild(centerEl);
266 MapView mapView = MainApplication.getMap().mapView;
267 EastNorth center = mapView.getCenter();
268 LatLon centerLL = Projections.inverseProject(center);
269 centerEl.setAttribute("lat", Double.toString(centerLL.lat()));
270 centerEl.setAttribute("lon", Double.toString(centerLL.lon()));
271 Element scale = doc.createElement("scale");
272 viewportEl.appendChild(scale);
273 double dist100px = mapView.getDist100Pixel();
274 scale.setAttribute("meter-per-pixel", Double.toString(dist100px / 100));
275 }
276
277 private static void writeProjection(Element root) {
278 Document doc = root.getOwnerDocument();
279 Element projectionEl = doc.createElement("projection");
280 root.appendChild(projectionEl);
281 String pcId = ProjectionPreference.getCurrentProjectionChoiceId();
282 Element projectionChoiceEl = doc.createElement("projection-choice");
283 projectionEl.appendChild(projectionChoiceEl);
284 Element idEl = doc.createElement("id");
285 projectionChoiceEl.appendChild(idEl);
286 idEl.setTextContent(pcId);
287 Collection<String> parameters = ProjectionPreference.getSubprojectionPreference(pcId);
288 Element parametersEl = doc.createElement("parameters");
289 projectionChoiceEl.appendChild(parametersEl);
290 if (parameters != null) {
291 for (String param : parameters) {
292 Element paramEl = doc.createElement("param");
293 parametersEl.appendChild(paramEl);
294 paramEl.setTextContent(param);
295 }
296 }
297 String code = Main.getProjection().toCode();
298 if (code != null) {
299 Element codeEl = doc.createElement("code");
300 projectionEl.appendChild(codeEl);
301 codeEl.setTextContent(code);
302 }
303 }
304
305 /**
306 * Writes given .jos document to an output stream.
307 * @param doc session document
308 * @param out output stream
309 * @throws IOException if any I/O error occurs
310 */
311 public void writeJos(Document doc, OutputStream out) throws IOException {
312 try {
313 OutputStreamWriter writer = new OutputStreamWriter(out, StandardCharsets.UTF_8);
314 writer.write("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
315 TransformerFactory transfac = TransformerFactory.newInstance();
316 Transformer trans = transfac.newTransformer();
317 trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
318 trans.setOutputProperty(OutputKeys.INDENT, "yes");
319 trans.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
320 StreamResult result = new StreamResult(writer);
321 DOMSource source = new DOMSource(doc);
322 trans.transform(source, result);
323 } catch (TransformerException e) {
324 throw new JosmRuntimeException(e);
325 }
326 }
327
328 /**
329 * Writes session to given file.
330 * @param f output file
331 * @throws IOException if any I/O error occurs
332 */
333 public void write(File f) throws IOException {
334 try (OutputStream out = new FileOutputStream(f)) {
335 write(out);
336 } catch (FileNotFoundException e) {
337 throw new IOException(e);
338 }
339 }
340
341 /**
342 * Writes session to given output stream.
343 * @param out output stream
344 * @throws IOException if any I/O error occurs
345 */
346 public void write(OutputStream out) throws IOException {
347 if (zip) {
348 zipOut = new ZipOutputStream(new BufferedOutputStream(out), StandardCharsets.UTF_8);
349 }
350 Document doc = createJosDocument(); // as side effect, files may be added to zipOut
351 if (zip) {
352 ZipEntry entry = new ZipEntry("session.jos");
353 zipOut.putNextEntry(entry);
354 writeJos(doc, zipOut);
355 Utils.close(zipOut);
356 } else {
357 writeJos(doc, new BufferedOutputStream(out));
358 }
359 }
360}
Note: See TracBrowser for help on using the repository browser.