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

Last change on this file since 14628 was 14120, checked in by Don-vip, 6 years ago

see #15229 - deprecate all Main methods related to projections. New ProjectionRegistry class

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