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.w3c.dom.Element;
016
017import org.openstreetmap.josm.gui.layer.Layer;
018import org.openstreetmap.josm.gui.progress.ProgressMonitor;
019import org.openstreetmap.josm.io.GpxImporter;
020import org.openstreetmap.josm.io.IllegalDataException;
021
022public class GpxTracksSessionImporter implements SessionLayerImporter {
023
024    @Override
025    public Layer load(Element elem, SessionReader.ImportSupport support, ProgressMonitor progressMonitor) throws IOException, IllegalDataException {
026        String version = elem.getAttribute("version");
027        if (!"0.1".equals(version)) {
028            throw new IllegalDataException(tr("Version ''{0}'' of meta data for gpx track layer is not supported. Expected: 0.1", version));
029        }
030        try {
031            XPathFactory xPathFactory = XPathFactory.newInstance();
032            XPath xpath = xPathFactory.newXPath();
033            XPathExpression fileExp = xpath.compile("file/text()");
034            String fileStr = (String) fileExp.evaluate(elem, XPathConstants.STRING);
035            if (fileStr == null || fileStr.isEmpty()) {
036                throw new IllegalDataException(tr("File name expected for layer no. {0}", support.getLayerIndex()));
037            }
038
039            InputStream in = support.getInputStream(fileStr);
040            GpxImporter.GpxImporterData importData = GpxImporter.loadLayers(in, support.getFile(fileStr), support.getLayerName(), null, progressMonitor);
041
042            support.addPostLayersTask(importData.getPostLayerTask());
043            return importData.getGpxLayer();
044
045        } catch (XPathExpressionException e) {
046            throw new RuntimeException(e);
047        }
048    }
049
050}