001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.io;
003
004import java.io.ByteArrayInputStream;
005import java.io.IOException;
006import java.io.InputStream;
007import java.nio.charset.StandardCharsets;
008import java.time.Instant;
009import java.util.ArrayList;
010import java.util.List;
011import java.util.Locale;
012import java.util.Optional;
013import java.util.function.UnaryOperator;
014
015import javax.xml.parsers.ParserConfigurationException;
016
017import org.openstreetmap.josm.data.coor.LatLon;
018import org.openstreetmap.josm.data.notes.Note;
019import org.openstreetmap.josm.data.notes.NoteComment;
020import org.openstreetmap.josm.data.notes.NoteComment.Action;
021import org.openstreetmap.josm.data.osm.User;
022import org.openstreetmap.josm.tools.Logging;
023import org.openstreetmap.josm.tools.XmlUtils;
024import org.openstreetmap.josm.tools.date.DateUtils;
025import org.xml.sax.Attributes;
026import org.xml.sax.InputSource;
027import org.xml.sax.SAXException;
028import org.xml.sax.helpers.DefaultHandler;
029
030/**
031 * Class to read Note objects from their XML representation. It can take
032 * either API style XML which starts with an "osm" tag or a planet dump
033 * style XML which starts with an "osm-notes" tag.
034 */
035public class NoteReader {
036
037    private final InputSource inputSource;
038    private List<Note> parsedNotes;
039
040    /**
041     * Notes can be represented in two XML formats. One is returned by the API
042     * while the other is used to generate the notes dump file. The parser
043     * needs to know which one it is handling.
044     */
045    private enum NoteParseMode {
046        API,
047        DUMP
048    }
049
050    /**
051     * SAX handler to read note information from its XML representation.
052     * Reads both API style and planet dump style formats.
053     */
054    private final class Parser extends DefaultHandler {
055
056        private NoteParseMode parseMode;
057        private final StringBuilder buffer = new StringBuilder();
058        private Note thisNote;
059        private long commentUid;
060        private String commentUsername;
061        private Action noteAction;
062        private Instant commentCreateDate;
063        private boolean commentIsNew;
064        private List<Note> notes;
065        private String commentText;
066
067        @Override
068        public void characters(char[] ch, int start, int length) throws SAXException {
069            buffer.append(ch, start, length);
070        }
071
072        @Override
073        public void startElement(String uri, String localName, String qName, Attributes attrs) throws SAXException {
074            buffer.setLength(0);
075            switch (qName) {
076            case "osm":
077                parseMode = NoteParseMode.API;
078                notes = new ArrayList<>(100);
079                return;
080            case "osm-notes":
081                parseMode = NoteParseMode.DUMP;
082                notes = new ArrayList<>(10_000);
083                return;
084            default: // Keep going
085            }
086
087            if (parseMode == NoteParseMode.API) {
088                if ("note".equals(qName)) {
089                    thisNote = parseNoteBasic(attrs);
090                }
091                return;
092            }
093
094            //The rest only applies for dump mode
095            switch (qName) {
096            case "note":
097                thisNote = parseNoteFull(attrs);
098                break;
099            case "comment":
100                commentUid = Long.parseLong(Optional.ofNullable(attrs.getValue("uid")).orElse("0"));
101                commentUsername = attrs.getValue("user");
102                noteAction = Action.valueOf(attrs.getValue("action").toUpperCase(Locale.ENGLISH));
103                commentCreateDate = DateUtils.parseInstant(attrs.getValue("timestamp"));
104                commentIsNew = Boolean.parseBoolean(Optional.ofNullable(attrs.getValue("is_new")).orElse("false"));
105                break;
106            default: // Do nothing
107            }
108        }
109
110        @Override
111        public void endElement(String namespaceURI, String localName, String qName) {
112            if (notes != null && "note".equals(qName)) {
113                notes.add(thisNote);
114            }
115            if ("comment".equals(qName)) {
116                final User commentUser;
117                if (commentUid == 0) {
118                    commentUser = User.getAnonymous();
119                } else {
120                    commentUser = User.createOsmUser(commentUid, commentUsername);
121                }
122                if (parseMode == NoteParseMode.API) {
123                    commentIsNew = false;
124                }
125                if (parseMode == NoteParseMode.DUMP) {
126                    commentText = buffer.toString();
127                }
128                thisNote.addComment(new NoteComment(commentCreateDate, commentUser, commentText, noteAction, commentIsNew));
129                commentUid = 0;
130                commentUsername = null;
131                commentCreateDate = null;
132                commentIsNew = false;
133                commentText = null;
134            }
135            if (parseMode == NoteParseMode.DUMP) {
136                return;
137            }
138
139            //the rest only applies to API mode
140            switch (qName) {
141            case "id":
142                thisNote.setId(Long.parseLong(buffer.toString()));
143                break;
144            case "status":
145                thisNote.setState(Note.State.valueOf(buffer.toString().toUpperCase(Locale.ENGLISH)));
146                break;
147            case "date_created":
148                thisNote.setCreatedAt(DateUtils.parseInstant(buffer.toString()));
149                break;
150            case "date_closed":
151                thisNote.setClosedAt(DateUtils.parseInstant(buffer.toString()));
152                break;
153            case "date":
154                commentCreateDate = DateUtils.parseInstant(buffer.toString());
155                break;
156            case "user":
157                commentUsername = buffer.toString();
158                break;
159            case "uid":
160                commentUid = Long.parseLong(buffer.toString());
161                break;
162            case "text":
163                commentText = buffer.toString();
164                buffer.setLength(0);
165                break;
166            case "action":
167                noteAction = Action.valueOf(buffer.toString().toUpperCase(Locale.ENGLISH));
168                break;
169            case "note": //nothing to do for comment or note, already handled above
170            case "comment":
171                break;
172            default: // Keep going (return)
173            }
174        }
175
176        @Override
177        public void endDocument() throws SAXException {
178            parsedNotes = notes;
179        }
180    }
181
182    static LatLon parseLatLon(UnaryOperator<String> attrs) {
183        final double lat = Double.parseDouble(attrs.apply("lat"));
184        final double lon = Double.parseDouble(attrs.apply("lon"));
185        return new LatLon(lat, lon);
186    }
187
188    static Note parseNoteBasic(Attributes attrs) {
189        return parseNoteBasic(attrs::getValue);
190    }
191
192    static Note parseNoteBasic(UnaryOperator<String> attrs) {
193        return new Note(parseLatLon(attrs));
194    }
195
196    static Note parseNoteFull(Attributes attrs) {
197        return parseNoteFull(attrs::getValue);
198    }
199
200    static Note parseNoteFull(UnaryOperator<String> attrs) {
201        final Note note = parseNoteBasic(attrs);
202        String id = attrs.apply("id");
203        if (id != null) {
204            note.setId(Long.parseLong(id));
205        }
206        String closedTimeStr = attrs.apply("closed_at");
207        if (closedTimeStr == null) { //no closed_at means the note is still open
208            note.setState(Note.State.OPEN);
209        } else {
210            note.setState(Note.State.CLOSED);
211            note.setClosedAt(DateUtils.parseInstant(closedTimeStr));
212        }
213        String createdAt = attrs.apply("created_at");
214        if (createdAt != null) {
215            note.setCreatedAt(DateUtils.parseInstant(createdAt));
216        }
217        return note;
218    }
219
220    /**
221     * Initializes the reader with a given InputStream
222     * @param source - InputStream containing Notes XML
223     */
224    public NoteReader(InputStream source) {
225        this.inputSource = new InputSource(source);
226    }
227
228    /**
229     * Initializes the reader with a string as a source
230     * @param source UTF-8 string containing Notes XML to parse
231     */
232    public NoteReader(String source) {
233        this.inputSource = new InputSource(new ByteArrayInputStream(source.getBytes(StandardCharsets.UTF_8)));
234    }
235
236    /**
237     * Parses the InputStream given to the constructor and returns
238     * the resulting Note objects
239     * @return List of Notes parsed from the input data
240     * @throws SAXException if any SAX parsing error occurs
241     * @throws IOException if any I/O error occurs
242     */
243    public List<Note> parse() throws SAXException, IOException {
244        DefaultHandler parser = new Parser();
245        try {
246            XmlUtils.parseSafeSAX(inputSource, parser);
247        } catch (ParserConfigurationException e) {
248            Logging.error(e); // broken SAXException chaining
249            throw new SAXException(e);
250        }
251        return parsedNotes;
252    }
253}