source: josm/trunk/src/org/openstreetmap/josm/io/OsmChangesetParser.java@ 17534

Last change on this file since 17534 was 16630, checked in by simon04, 4 years ago

see #19334 - https://errorprone.info/bugpattern/UnnecessaryParentheses

  • Property svn:eol-style set to native
File size: 11.1 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.io;
3
4import static org.openstreetmap.josm.tools.I18n.tr;
5
6import java.io.IOException;
7import java.io.InputStream;
8import java.io.InputStreamReader;
9import java.nio.charset.StandardCharsets;
10import java.text.MessageFormat;
11import java.util.Date;
12import java.util.LinkedList;
13import java.util.List;
14
15import javax.xml.parsers.ParserConfigurationException;
16
17import org.openstreetmap.josm.data.coor.LatLon;
18import org.openstreetmap.josm.data.osm.Changeset;
19import org.openstreetmap.josm.data.osm.ChangesetDiscussionComment;
20import org.openstreetmap.josm.data.osm.User;
21import org.openstreetmap.josm.gui.progress.ProgressMonitor;
22import org.openstreetmap.josm.tools.XmlParsingException;
23import org.openstreetmap.josm.tools.XmlUtils;
24import org.openstreetmap.josm.tools.date.DateUtils;
25import org.xml.sax.Attributes;
26import org.xml.sax.InputSource;
27import org.xml.sax.Locator;
28import org.xml.sax.SAXException;
29import org.xml.sax.helpers.DefaultHandler;
30
31/**
32 * Parser for a list of changesets, encapsulated in an OSM data set structure.
33 * Example:
34 * <pre>
35 * &lt;osm version="0.6" generator="OpenStreetMap server"&gt;
36 * &lt;changeset id="143" user="guggis" uid="1" created_at="2009-09-08T20:35:39Z" closed_at="2009-09-08T21:36:12Z" open="false"
37 * min_lon="7.380925" min_lat="46.9215164" max_lon="7.3984718" max_lat="46.9226502"&gt;
38 * &lt;tag k="asdfasdf" v="asdfasdf"/&gt;
39 * &lt;tag k="created_by" v="JOSM/1.5 (UNKNOWN de)"/&gt;
40 * &lt;tag k="comment" v="1234"/&gt;
41 * &lt;/changeset&gt;
42 * &lt;/osm&gt;
43 * </pre>
44 *
45 */
46public final class OsmChangesetParser {
47 private final List<Changeset> changesets;
48
49 private OsmChangesetParser() {
50 changesets = new LinkedList<>();
51 }
52
53 /**
54 * Returns the parsed changesets.
55 * @return the parsed changesets
56 */
57 public List<Changeset> getChangesets() {
58 return changesets;
59 }
60
61 private class Parser extends DefaultHandler {
62 private Locator locator;
63
64 @Override
65 public void setDocumentLocator(Locator locator) {
66 this.locator = locator;
67 }
68
69 protected void throwException(String msg) throws XmlParsingException {
70 throw new XmlParsingException(msg).rememberLocation(locator);
71 }
72
73 /** The current changeset */
74 private Changeset current;
75
76 /** The current comment */
77 private ChangesetDiscussionComment comment;
78
79 /** The current comment text */
80 private StringBuilder text;
81
82 protected void parseChangesetAttributes(Attributes atts) throws XmlParsingException {
83 // -- id
84 String value = atts.getValue("id");
85 if (value == null) {
86 throwException(tr("Missing mandatory attribute ''{0}''.", "id"));
87 }
88 current.setId(parseNumericAttribute(value, 1));
89
90 // -- user / uid
91 current.setUser(createUser(atts));
92
93 // -- created_at
94 value = atts.getValue("created_at");
95 if (value == null) {
96 current.setCreatedAt(null);
97 } else {
98 current.setCreatedAt(DateUtils.fromString(value));
99 }
100
101 // -- closed_at
102 value = atts.getValue("closed_at");
103 if (value == null) {
104 current.setClosedAt(null);
105 } else {
106 current.setClosedAt(DateUtils.fromString(value));
107 }
108
109 // -- open
110 value = atts.getValue("open");
111 if (value == null) {
112 throwException(tr("Missing mandatory attribute ''{0}''.", "open"));
113 } else if ("true".equals(value)) {
114 current.setOpen(true);
115 } else if ("false".equals(value)) {
116 current.setOpen(false);
117 } else {
118 throwException(tr("Illegal boolean value for attribute ''{0}''. Got ''{1}''.", "open", value));
119 }
120
121 // -- min_lon and min_lat
122 String minLonStr = atts.getValue("min_lon");
123 String minLatStr = atts.getValue("min_lat");
124 String maxLonStr = atts.getValue("max_lon");
125 String maxLatStr = atts.getValue("max_lat");
126 if (minLonStr != null && minLatStr != null && maxLonStr != null && maxLatStr != null) {
127 double minLon = 0;
128 try {
129 minLon = Double.parseDouble(minLonStr);
130 } catch (NumberFormatException e) {
131 throwException(tr("Illegal value for attribute ''{0}''. Got ''{1}''.", "min_lon", minLonStr));
132 }
133 double minLat = 0;
134 try {
135 minLat = Double.parseDouble(minLatStr);
136 } catch (NumberFormatException e) {
137 throwException(tr("Illegal value for attribute ''{0}''. Got ''{1}''.", "min_lat", minLatStr));
138 }
139 current.setMin(new LatLon(minLat, minLon));
140
141 // -- max_lon and max_lat
142
143 double maxLon = 0;
144 try {
145 maxLon = Double.parseDouble(maxLonStr);
146 } catch (NumberFormatException e) {
147 throwException(tr("Illegal value for attribute ''{0}''. Got ''{1}''.", "max_lon", maxLonStr));
148 }
149 double maxLat = 0;
150 try {
151 maxLat = Double.parseDouble(maxLatStr);
152 } catch (NumberFormatException e) {
153 throwException(tr("Illegal value for attribute ''{0}''. Got ''{1}''.", "max_lat", maxLatStr));
154 }
155 current.setMax(new LatLon(maxLat, maxLon));
156 }
157
158 // -- comments_count
159 String commentsCount = atts.getValue("comments_count");
160 if (commentsCount != null) {
161 current.setCommentsCount(parseNumericAttribute(commentsCount, 0));
162 }
163
164 // -- changes_count
165 String changesCount = atts.getValue("changes_count");
166 if (changesCount != null) {
167 current.setChangesCount(parseNumericAttribute(changesCount, 0));
168 }
169 }
170
171 private void parseCommentAttributes(Attributes atts) throws XmlParsingException {
172 // -- date
173 String value = atts.getValue("date");
174 Date date = null;
175 if (value != null) {
176 date = DateUtils.fromString(value);
177 }
178
179 comment = new ChangesetDiscussionComment(date, createUser(atts));
180 }
181
182 private int parseNumericAttribute(String value, int minAllowed) throws XmlParsingException {
183 int att = 0;
184 try {
185 att = Integer.parseInt(value);
186 } catch (NumberFormatException e) {
187 throwException(tr("Illegal value for attribute ''{0}''. Got ''{1}''.", "id", value));
188 }
189 if (att < minAllowed) {
190 throwException(tr("Illegal numeric value for attribute ''{0}''. Got ''{1}''.", "id", att));
191 }
192 return att;
193 }
194
195 @Override
196 public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException {
197 switch (qName) {
198 case "osm":
199 if (atts == null) {
200 throwException(tr("Missing mandatory attribute ''{0}'' of XML element {1}.", "version", "osm"));
201 return;
202 }
203 String v = atts.getValue("version");
204 if (v == null) {
205 throwException(tr("Missing mandatory attribute ''{0}''.", "version"));
206 }
207 if (!"0.6".equals(v)) {
208 throwException(tr("Unsupported version: {0}", v));
209 }
210 break;
211 case "changeset":
212 current = new Changeset();
213 parseChangesetAttributes(atts);
214 break;
215 case "tag":
216 String key = atts.getValue("k");
217 String value = atts.getValue("v");
218 current.put(key, value);
219 break;
220 case "discussion":
221 break;
222 case "comment":
223 parseCommentAttributes(atts);
224 break;
225 case "text":
226 text = new StringBuilder();
227 break;
228 default:
229 throwException(tr("Undefined element ''{0}'' found in input stream. Aborting.", qName));
230 }
231 }
232
233 @Override
234 public void characters(char[] ch, int start, int length) throws SAXException {
235 if (text != null) {
236 text.append(ch, start, length);
237 }
238 }
239
240 @Override
241 public void endElement(String uri, String localName, String qName) throws SAXException {
242 if ("changeset".equals(qName)) {
243 changesets.add(current);
244 current = null;
245 } else if ("comment".equals(qName)) {
246 current.addDiscussionComment(comment);
247 comment = null;
248 } else if ("text".equals(qName)) {
249 comment.setText(text.toString());
250 text = null;
251 }
252 }
253
254 protected User createUser(Attributes atts) throws XmlParsingException {
255 String name = atts.getValue("user");
256 String uid = atts.getValue("uid");
257 if (uid == null) {
258 if (name == null)
259 return null;
260 return User.createLocalUser(name);
261 }
262 try {
263 long id = Long.parseLong(uid);
264 return User.createOsmUser(id, name);
265 } catch (NumberFormatException e) {
266 throwException(MessageFormat.format("Illegal value for attribute ''uid''. Got ''{0}''.", uid));
267 }
268 return null;
269 }
270 }
271
272 /**
273 * Parse the given input source and return the list of changesets
274 *
275 * @param source the source input stream
276 * @param progressMonitor the progress monitor
277 *
278 * @return the list of changesets
279 * @throws IllegalDataException if the an error was found while parsing the data from the source
280 */
281 @SuppressWarnings("resource")
282 public static List<Changeset> parse(InputStream source, ProgressMonitor progressMonitor) throws IllegalDataException {
283 OsmChangesetParser parser = new OsmChangesetParser();
284 try {
285 progressMonitor.beginTask("");
286 progressMonitor.indeterminateSubTask(tr("Parsing list of changesets..."));
287 InputSource inputSource = new InputSource(new InvalidXmlCharacterFilter(new InputStreamReader(source, StandardCharsets.UTF_8)));
288 XmlUtils.parseSafeSAX(inputSource, parser.new Parser());
289 return parser.getChangesets();
290 } catch (ParserConfigurationException | SAXException e) {
291 throw new IllegalDataException(e.getMessage(), e);
292 } catch (IOException e) {
293 throw new IllegalDataException(e);
294 } finally {
295 progressMonitor.finishTask();
296 }
297 }
298}
Note: See TracBrowser for help on using the repository browser.