001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.io.session;
003
004import java.io.OutputStream;
005import java.io.OutputStreamWriter;
006import java.io.PrintWriter;
007import java.io.Writer;
008import java.nio.charset.StandardCharsets;
009
010import org.openstreetmap.josm.data.osm.DataSet;
011import org.openstreetmap.josm.gui.layer.OsmDataLayer;
012import org.openstreetmap.josm.io.OsmWriter;
013import org.openstreetmap.josm.io.OsmWriterFactory;
014
015/**
016 * Session exporter for {@link OsmDataLayer}.
017 * @since 4685
018 */
019public class OsmDataSessionExporter extends GenericSessionExporter<OsmDataLayer> {
020
021    /**
022     * Constructs a new {@code OsmDataSessionExporter}.
023     * @param layer Data layer to export
024     */
025    public OsmDataSessionExporter(OsmDataLayer layer) { // NO_UCD (test only)
026        super(layer, "osm-data", "0.1", "osm");
027    }
028
029    @Override
030    protected void addDataFile(OutputStream out) {
031        exportData(layer.data, out);
032    }
033
034    /**
035     * Exports OSM data to the given output stream.
036     * @param data data set
037     * @param out output stream (must be closed by caller; note: if caller has access, caller should use
038     *            {@link org.apache.commons.io.output.CloseShieldOutputStream} when calling this method to
039     *            avoid potential future issues)
040     */
041    @SuppressWarnings("squid:S2095") // All the closeables in this method will close the input OutputStream.
042    public static void exportData(DataSet data, OutputStream out) {
043        // This writer will close out when it is closed
044        Writer writer = new OutputStreamWriter(out, StandardCharsets.UTF_8);
045        // The PrintWriter will close the writer when it is closed, and the OsmWriter will close the PrintWriter when it is closed.
046        OsmWriter w = OsmWriterFactory.createOsmWriter(new PrintWriter(writer), false, data.getVersion());
047        data.getReadLock().lock();
048        try {
049            w.write(data);
050            w.flush();
051        } finally {
052            data.getReadLock().unlock();
053        }
054    }
055}