001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.io;
003
004import static org.openstreetmap.josm.tools.I18n.tr;
005
006import java.time.Instant;
007import java.util.HashMap;
008import java.util.Map;
009
010import org.openstreetmap.josm.data.coor.LatLon;
011import org.openstreetmap.josm.data.osm.OsmPrimitiveType;
012import org.openstreetmap.josm.data.osm.RelationMemberData;
013import org.openstreetmap.josm.data.osm.User;
014import org.openstreetmap.josm.data.osm.history.HistoryNode;
015import org.openstreetmap.josm.data.osm.history.HistoryOsmPrimitive;
016import org.openstreetmap.josm.data.osm.history.HistoryRelation;
017import org.openstreetmap.josm.data.osm.history.HistoryWay;
018import org.openstreetmap.josm.tools.date.DateUtils;
019import org.xml.sax.Attributes;
020import org.xml.sax.Locator;
021import org.xml.sax.SAXException;
022import org.xml.sax.helpers.DefaultHandler;
023
024/**
025 * Base class of {@link OsmChangesetContentParser} and {@link OsmHistoryReader} internal parsers.
026 * @since 6201
027 */
028public abstract class AbstractParser extends DefaultHandler {
029
030    /** the current primitive to be read */
031    protected HistoryOsmPrimitive currentPrimitive;
032    protected Locator locator;
033    /** if true, replace user information in input by anonymous user */
034    protected boolean useAnonymousUser;
035    private Map<RelationMemberData, RelationMemberData> memberCache = new HashMap<>();
036
037    @Override
038    public void setDocumentLocator(Locator locator) {
039        this.locator = locator;
040    }
041
042    protected abstract void throwException(String message) throws SAXException;
043
044    protected abstract void throwException(String message, Exception e) throws SAXException;
045
046    protected final long getMandatoryAttributeLong(Attributes attr, String name) throws SAXException {
047        String v = attr.getValue(name);
048        if (v == null) {
049            throwException(tr("Missing mandatory attribute ''{0}''.", name));
050        }
051        long l = 0L;
052        try {
053            l = Long.parseLong(v);
054        } catch (NumberFormatException e) {
055            throwException(tr("Illegal value for mandatory attribute ''{0}'' of type long. Got ''{1}''.", name, v), e);
056        }
057        if (l < 0) {
058            throwException(tr("Illegal value for mandatory attribute ''{0}'' of type long (>=0). Got ''{1}''.", name, v));
059        }
060        return l;
061    }
062
063    protected final Long getAttributeLong(Attributes attr, String name) throws SAXException {
064        String v = attr.getValue(name);
065        if (v == null)
066            return null;
067        Long l = 0L;
068        try {
069            l = Long.valueOf(v);
070        } catch (NumberFormatException e) {
071            throwException(tr("Illegal value for mandatory attribute ''{0}'' of type long. Got ''{1}''.", name, v), e);
072        }
073        if (l < 0) {
074            throwException(tr("Illegal value for mandatory attribute ''{0}'' of type long (>=0). Got ''{1}''.", name, v));
075        }
076        return l;
077    }
078
079    protected final Double getAttributeDouble(Attributes attr, String name) throws SAXException {
080        String v = attr.getValue(name);
081        if (v == null) {
082            return null;
083        }
084        double d = 0.0;
085        try {
086            d = Double.parseDouble(v);
087        } catch (NumberFormatException e) {
088            throwException(tr("Illegal value for attribute ''{0}'' of type double. Got ''{1}''.", name, v), e);
089        }
090        return d;
091    }
092
093    protected final String getMandatoryAttributeString(Attributes attr, String name) throws SAXException {
094        String v = attr.getValue(name);
095        if (v == null) {
096            throwException(tr("Missing mandatory attribute ''{0}''.", name));
097        }
098        return v;
099    }
100
101    protected boolean getMandatoryAttributeBoolean(Attributes attr, String name) throws SAXException {
102        String v = attr.getValue(name);
103        if (v == null) {
104            throwException(tr("Missing mandatory attribute ''{0}''.", name));
105        }
106        if ("true".equals(v)) return true;
107        if ("false".equals(v)) return false;
108        throwException(tr("Illegal value for mandatory attribute ''{0}'' of type boolean. Got ''{1}''.", name, v));
109        return false; // not reached
110    }
111
112    protected final HistoryOsmPrimitive createPrimitive(Attributes atts, OsmPrimitiveType type) throws SAXException {
113        long id = getMandatoryAttributeLong(atts, "id");
114        long version = getMandatoryAttributeLong(atts, "version");
115        Long changeset = getAttributeLong(atts, "changeset");
116        long changesetId = changeset != null ? changeset : 0L;
117        boolean visible = getMandatoryAttributeBoolean(atts, "visible");
118
119        User user = null;
120        if (!useAnonymousUser) {
121            Long uid = getAttributeLong(atts, "uid");
122            String userStr = atts.getValue("user");
123            if (userStr != null) {
124                if (uid != null) {
125                    user = User.createOsmUser(uid, userStr);
126                    user.setPreferredName(userStr);
127                } else {
128                    user = User.createLocalUser(userStr);
129                }
130            }
131        }
132        if (user == null) {
133            user = User.getAnonymous();
134        }
135
136        String v = getMandatoryAttributeString(atts, "timestamp");
137        Instant timestamp = DateUtils.parseInstant(v);
138        HistoryOsmPrimitive primitive = null;
139        if (type == OsmPrimitiveType.NODE) {
140            Double lat = getAttributeDouble(atts, "lat");
141            Double lon = getAttributeDouble(atts, "lon");
142            LatLon coor = (lat != null && lon != null) ? new LatLon(lat, lon) : null;
143            primitive = new HistoryNode(id, version, visible, user, changesetId, timestamp, coor, changeset != null);
144
145        } else if (type == OsmPrimitiveType.WAY) {
146            primitive = new HistoryWay(id, version, visible, user, changesetId, timestamp, changeset != null);
147        } else if (type == OsmPrimitiveType.RELATION) {
148            primitive = new HistoryRelation(id, version, visible, user, changesetId, timestamp, changeset != null);
149        }
150        return primitive;
151    }
152
153    protected final void startNode(Attributes atts) throws SAXException {
154        currentPrimitive = createPrimitive(atts, OsmPrimitiveType.NODE);
155    }
156
157    protected final void startWay(Attributes atts) throws SAXException {
158        currentPrimitive = createPrimitive(atts, OsmPrimitiveType.WAY);
159    }
160
161    protected final void startRelation(Attributes atts) throws SAXException {
162        currentPrimitive = createPrimitive(atts, OsmPrimitiveType.RELATION);
163    }
164
165    protected final void handleTag(Attributes atts) throws SAXException {
166        String key = getMandatoryAttributeString(atts, "k");
167        String value = getMandatoryAttributeString(atts, "v");
168        currentPrimitive.put(key, value);
169    }
170
171    protected final void handleNodeReference(Attributes atts) throws SAXException {
172        long ref = getMandatoryAttributeLong(atts, "ref");
173        ((HistoryWay) currentPrimitive).addNode(ref);
174    }
175
176    protected void handleMember(Attributes atts) throws SAXException {
177        long ref = getMandatoryAttributeLong(atts, "ref");
178        String v = getMandatoryAttributeString(atts, "type");
179        OsmPrimitiveType type = null;
180        try {
181            type = OsmPrimitiveType.fromApiTypeName(v);
182        } catch (IllegalArgumentException e) {
183            throwException(tr("Illegal value for mandatory attribute ''{0}'' of type OsmPrimitiveType. Got ''{1}''.", "type", v), e);
184        }
185        String role = getMandatoryAttributeString(atts, "role");
186        RelationMemberData member = new RelationMemberData(role, type, ref);
187        // see #20405: cache equal instances of members
188        RelationMemberData cachedMember = memberCache.computeIfAbsent(member, m -> m);
189        ((HistoryRelation) currentPrimitive).addMember(cachedMember);
190    }
191
192    protected final boolean doStartElement(String qName, Attributes atts) throws SAXException {
193        switch (qName) {
194        case "node":
195            startNode(atts);
196            return true;
197        case "way":
198            startWay(atts);
199            return true;
200        case "relation":
201            startRelation(atts);
202            return true;
203        case "tag":
204            handleTag(atts);
205            return true;
206        case "nd":
207            handleNodeReference(atts);
208            return true;
209        case "member":
210            handleMember(atts);
211            return true;
212        default:
213            return false;
214        }
215    }
216}