001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.io.session;
003
004import static org.openstreetmap.josm.tools.I18n.tr;
005
006import java.io.IOException;
007import java.io.InputStream;
008
009import javax.xml.xpath.XPath;
010import javax.xml.xpath.XPathConstants;
011import javax.xml.xpath.XPathExpression;
012import javax.xml.xpath.XPathExpressionException;
013import javax.xml.xpath.XPathFactory;
014
015import org.openstreetmap.josm.gui.io.importexport.GpxImporter;
016import org.openstreetmap.josm.gui.layer.Layer;
017import org.openstreetmap.josm.gui.layer.markerlayer.MarkerLayer;
018import org.openstreetmap.josm.gui.progress.ProgressMonitor;
019import org.openstreetmap.josm.io.IllegalDataException;
020import org.openstreetmap.josm.io.session.SessionReader.ImportSupport;
021import org.openstreetmap.josm.tools.Utils;
022import org.w3c.dom.Element;
023
024/**
025 * Session importer for {@link MarkerLayer}.
026 * @since 5684
027 */
028public class MarkerSessionImporter implements SessionLayerImporter {
029
030    @Override
031    public Layer load(Element elem, ImportSupport support, ProgressMonitor progressMonitor) throws IOException, IllegalDataException {
032        String version = elem.getAttribute("version");
033        if (!"0.1".equals(version)) {
034            throw new IllegalDataException(tr("Version ''{0}'' of meta data for marker layer is not supported. Expected: 0.1", version));
035        }
036        try {
037            XPathFactory xPathFactory = XPathFactory.newInstance();
038            XPath xpath = xPathFactory.newXPath();
039            XPathExpression fileExp = xpath.compile("file/text()");
040            String fileStr = (String) fileExp.evaluate(elem, XPathConstants.STRING);
041            if (Utils.isEmpty(fileStr)) {
042                throw new IllegalDataException(tr("File name expected for layer no. {0}", support.getLayerIndex()));
043            }
044
045            try (InputStream in = support.getInputStream(fileStr)) {
046                GpxImporter.GpxImporterData importData = GpxImporter.loadLayers(in, support.getFile(fileStr), support.getLayerName(),
047                        progressMonitor);
048
049                support.addPostLayersTask(importData.getPostLayerTask());
050
051                return importData.getMarkerLayer();
052            }
053        } catch (XPathExpressionException e) {
054            throw new IllegalDataException(e);
055        }
056    }
057}