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

Last change on this file since 12856 was 12778, checked in by bastiK, 7 years ago

see #15229 - deprecate Projections#project and Projections#inverseProject

replacement is a bit more verbose, but the fact that Main.proj is
involved need not be hidden

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