1 | //License: GPL. See README for details.
|
---|
2 | package org.openstreetmap.josm.io;
|
---|
3 |
|
---|
4 | import static org.openstreetmap.josm.tools.I18n.tr;
|
---|
5 | import static org.openstreetmap.josm.tools.I18n.trn;
|
---|
6 |
|
---|
7 | import java.io.BufferedReader;
|
---|
8 | import java.io.BufferedWriter;
|
---|
9 | import java.io.IOException;
|
---|
10 | import java.io.InputStream;
|
---|
11 | import java.io.InputStreamReader;
|
---|
12 | import java.io.OutputStream;
|
---|
13 | import java.io.OutputStreamWriter;
|
---|
14 | import java.io.PrintWriter;
|
---|
15 | import java.io.StringReader;
|
---|
16 | import java.io.StringWriter;
|
---|
17 | import java.net.ConnectException;
|
---|
18 | import java.net.HttpURLConnection;
|
---|
19 | import java.net.SocketTimeoutException;
|
---|
20 | import java.net.URL;
|
---|
21 | import java.net.UnknownHostException;
|
---|
22 | import java.util.Collection;
|
---|
23 | import java.util.Collections;
|
---|
24 | import java.util.HashMap;
|
---|
25 | import java.util.logging.Logger;
|
---|
26 |
|
---|
27 | import javax.xml.parsers.ParserConfigurationException;
|
---|
28 | import javax.xml.parsers.SAXParserFactory;
|
---|
29 |
|
---|
30 | import org.openstreetmap.josm.Main;
|
---|
31 | import org.openstreetmap.josm.data.osm.Changeset;
|
---|
32 | import org.openstreetmap.josm.data.osm.OsmPrimitive;
|
---|
33 | import org.openstreetmap.josm.data.osm.OsmPrimitiveType;
|
---|
34 | import org.openstreetmap.josm.gui.progress.NullProgressMonitor;
|
---|
35 | import org.openstreetmap.josm.gui.progress.ProgressMonitor;
|
---|
36 | import org.openstreetmap.josm.tools.CheckParameterUtil;
|
---|
37 | import org.xml.sax.Attributes;
|
---|
38 | import org.xml.sax.InputSource;
|
---|
39 | import org.xml.sax.SAXException;
|
---|
40 | import org.xml.sax.helpers.DefaultHandler;
|
---|
41 |
|
---|
42 | /**
|
---|
43 | * Class that encapsulates the communications with the OSM API.
|
---|
44 | *
|
---|
45 | * All interaction with the server-side OSM API should go through this class.
|
---|
46 | *
|
---|
47 | * It is conceivable to extract this into an interface later and create various
|
---|
48 | * classes implementing the interface, to be able to talk to various kinds of servers.
|
---|
49 | *
|
---|
50 | */
|
---|
51 | public class OsmApi extends OsmConnection {
|
---|
52 | @SuppressWarnings("unused")
|
---|
53 | static private final Logger logger = Logger.getLogger(OsmApi.class.getName());
|
---|
54 | /** max number of retries to send a request in case of HTTP 500 errors or timeouts */
|
---|
55 | static public final int DEFAULT_MAX_NUM_RETRIES = 5;
|
---|
56 |
|
---|
57 | /** the collection of instantiated OSM APIs */
|
---|
58 | private static HashMap<String, OsmApi> instances = new HashMap<String, OsmApi>();
|
---|
59 |
|
---|
60 | /**
|
---|
61 | * replies the {@see OsmApi} for a given server URL
|
---|
62 | *
|
---|
63 | * @param serverUrl the server URL
|
---|
64 | * @return the OsmApi
|
---|
65 | * @throws IllegalArgumentException thrown, if serverUrl is null
|
---|
66 | *
|
---|
67 | */
|
---|
68 | static public OsmApi getOsmApi(String serverUrl) {
|
---|
69 | OsmApi api = instances.get(serverUrl);
|
---|
70 | if (api == null) {
|
---|
71 | api = new OsmApi(serverUrl);
|
---|
72 | instances.put(serverUrl,api);
|
---|
73 | }
|
---|
74 | return api;
|
---|
75 | }
|
---|
76 | /**
|
---|
77 | * replies the {@see OsmApi} for the URL given by the preference <code>osm-server.url</code>
|
---|
78 | *
|
---|
79 | * @return the OsmApi
|
---|
80 | * @exception IllegalStateException thrown, if the preference <code>osm-server.url</code> is not set
|
---|
81 | *
|
---|
82 | */
|
---|
83 | static public OsmApi getOsmApi() {
|
---|
84 | String serverUrl = Main.pref.get("osm-server.url", "http://api.openstreetmap.org/api");
|
---|
85 | if (serverUrl == null)
|
---|
86 | throw new IllegalStateException(tr("Preference ''{0}'' missing. Cannot initialize OsmApi.", "osm-server.url"));
|
---|
87 | return getOsmApi(serverUrl);
|
---|
88 | }
|
---|
89 |
|
---|
90 | /** the server URL */
|
---|
91 | private String serverUrl;
|
---|
92 |
|
---|
93 | /**
|
---|
94 | * Object describing current changeset
|
---|
95 | */
|
---|
96 | private Changeset changeset;
|
---|
97 |
|
---|
98 | /**
|
---|
99 | * API version used for server communications
|
---|
100 | */
|
---|
101 | private String version = null;
|
---|
102 |
|
---|
103 | /** the api capabilities */
|
---|
104 | private Capabilities capabilities = new Capabilities();
|
---|
105 |
|
---|
106 | /**
|
---|
107 | * true if successfully initialized
|
---|
108 | */
|
---|
109 | private boolean initialized = false;
|
---|
110 |
|
---|
111 | private StringWriter swriter = new StringWriter();
|
---|
112 | private OsmWriter osmWriter = new OsmWriter(new PrintWriter(swriter), true, null);
|
---|
113 |
|
---|
114 | /**
|
---|
115 | * A parser for the "capabilities" response XML
|
---|
116 | */
|
---|
117 | private class CapabilitiesParser extends DefaultHandler {
|
---|
118 | @Override
|
---|
119 | public void startDocument() throws SAXException {
|
---|
120 | capabilities.clear();
|
---|
121 | }
|
---|
122 |
|
---|
123 | @Override public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException {
|
---|
124 | for (int i=0; i< atts.getLength(); i++) {
|
---|
125 | capabilities.put(qName, atts.getQName(i), atts.getValue(i));
|
---|
126 | }
|
---|
127 | }
|
---|
128 | }
|
---|
129 |
|
---|
130 | /**
|
---|
131 | * creates an OSM api for a specific server URL
|
---|
132 | *
|
---|
133 | * @param serverUrl the server URL. Must not be null
|
---|
134 | * @exception IllegalArgumentException thrown, if serverUrl is null
|
---|
135 | */
|
---|
136 | protected OsmApi(String serverUrl) {
|
---|
137 | CheckParameterUtil.ensureParameterNotNull(serverUrl, "serverUrl");
|
---|
138 | this.serverUrl = serverUrl;
|
---|
139 | }
|
---|
140 |
|
---|
141 | /**
|
---|
142 | * Returns the OSM protocol version we use to talk to the server.
|
---|
143 | * @return protocol version, or null if not yet negotiated.
|
---|
144 | */
|
---|
145 | public String getVersion() {
|
---|
146 | return version;
|
---|
147 | }
|
---|
148 |
|
---|
149 | /**
|
---|
150 | * Initializes this component by negotiating a protocol version with the server.
|
---|
151 | *
|
---|
152 | * @exception OsmApiInitializationException thrown, if an exception occurs
|
---|
153 | */
|
---|
154 | public void initialize(ProgressMonitor monitor) throws OsmApiInitializationException, OsmTransferCancelledException {
|
---|
155 | if (initialized)
|
---|
156 | return;
|
---|
157 | cancel = false;
|
---|
158 | try {
|
---|
159 | String s = sendRequest("GET", "capabilities", null,monitor, false);
|
---|
160 | InputSource inputSource = new InputSource(new StringReader(s));
|
---|
161 | SAXParserFactory.newInstance().newSAXParser().parse(inputSource, new CapabilitiesParser());
|
---|
162 | if (capabilities.supportsVersion("0.6")) {
|
---|
163 | version = "0.6";
|
---|
164 | } else {
|
---|
165 | System.err.println(tr("This version of JOSM is incompatible with the configured server."));
|
---|
166 | System.err.println(tr("It supports protocol version 0.6, while the server says it supports {0} to {1}.",
|
---|
167 | capabilities.get("version", "minimum"), capabilities.get("version", "maximum")));
|
---|
168 | initialized = false;
|
---|
169 | }
|
---|
170 | System.out.println(tr("Communications with {0} established using protocol version {1}.",
|
---|
171 | serverUrl,
|
---|
172 | version));
|
---|
173 | osmWriter.setVersion(version);
|
---|
174 | initialized = true;
|
---|
175 | } catch(IOException e) {
|
---|
176 | initialized = false;
|
---|
177 | throw new OsmApiInitializationException(e);
|
---|
178 | } catch(SAXException e) {
|
---|
179 | initialized = false;
|
---|
180 | throw new OsmApiInitializationException(e);
|
---|
181 | } catch(ParserConfigurationException e) {
|
---|
182 | initialized = false;
|
---|
183 | throw new OsmApiInitializationException(e);
|
---|
184 | } catch(OsmTransferCancelledException e){
|
---|
185 | throw e;
|
---|
186 | } catch(OsmTransferException e) {
|
---|
187 | initialized = false;
|
---|
188 | throw new OsmApiInitializationException(e);
|
---|
189 | }
|
---|
190 | }
|
---|
191 |
|
---|
192 | /**
|
---|
193 | * Makes an XML string from an OSM primitive. Uses the OsmWriter class.
|
---|
194 | * @param o the OSM primitive
|
---|
195 | * @param addBody true to generate the full XML, false to only generate the encapsulating tag
|
---|
196 | * @return XML string
|
---|
197 | */
|
---|
198 | private String toXml(OsmPrimitive o, boolean addBody) {
|
---|
199 | swriter.getBuffer().setLength(0);
|
---|
200 | osmWriter.setWithBody(addBody);
|
---|
201 | osmWriter.setChangeset(changeset);
|
---|
202 | osmWriter.header();
|
---|
203 | o.visit(osmWriter);
|
---|
204 | osmWriter.footer();
|
---|
205 | osmWriter.out.flush();
|
---|
206 | return swriter.toString();
|
---|
207 | }
|
---|
208 |
|
---|
209 | /**
|
---|
210 | * Makes an XML string from an OSM primitive. Uses the OsmWriter class.
|
---|
211 | * @param o the OSM primitive
|
---|
212 | * @param addBody true to generate the full XML, false to only generate the encapsulating tag
|
---|
213 | * @return XML string
|
---|
214 | */
|
---|
215 | private String toXml(Changeset s) {
|
---|
216 | swriter.getBuffer().setLength(0);
|
---|
217 | osmWriter.header();
|
---|
218 | s.visit(osmWriter);
|
---|
219 | osmWriter.footer();
|
---|
220 | osmWriter.out.flush();
|
---|
221 | return swriter.toString();
|
---|
222 | }
|
---|
223 |
|
---|
224 | /**
|
---|
225 | * Returns the base URL for API requests, including the negotiated version number.
|
---|
226 | * @return base URL string
|
---|
227 | */
|
---|
228 | public String getBaseUrl() {
|
---|
229 | StringBuffer rv = new StringBuffer(serverUrl);
|
---|
230 | if (version != null) {
|
---|
231 | rv.append("/");
|
---|
232 | rv.append(version);
|
---|
233 | }
|
---|
234 | rv.append("/");
|
---|
235 | // this works around a ruby (or lighttpd) bug where two consecutive slashes in
|
---|
236 | // an URL will cause a "404 not found" response.
|
---|
237 | int p; while ((p = rv.indexOf("//", 6)) > -1) { rv.delete(p, p + 1); }
|
---|
238 | return rv.toString();
|
---|
239 | }
|
---|
240 |
|
---|
241 | /**
|
---|
242 | * Creates an OSM primitive on the server. The OsmPrimitive object passed in
|
---|
243 | * is modified by giving it the server-assigned id.
|
---|
244 | *
|
---|
245 | * @param osm the primitive
|
---|
246 | * @throws OsmTransferException if something goes wrong
|
---|
247 | */
|
---|
248 | public void createPrimitive(OsmPrimitive osm, ProgressMonitor monitor) throws OsmTransferException {
|
---|
249 | String ret = "";
|
---|
250 | try {
|
---|
251 | ensureValidChangeset();
|
---|
252 | initialize(monitor);
|
---|
253 | ret = sendRequest("PUT", OsmPrimitiveType.from(osm).getAPIName()+"/create", toXml(osm, true),monitor);
|
---|
254 | osm.setOsmId(Long.parseLong(ret.trim()), 1);
|
---|
255 | osm.setChangesetId(getChangeset().getId());
|
---|
256 | } catch(NumberFormatException e){
|
---|
257 | throw new OsmTransferException(tr("Unexpected format of ID replied by the server. Got ''{0}''.", ret));
|
---|
258 | }
|
---|
259 | }
|
---|
260 |
|
---|
261 | /**
|
---|
262 | * Modifies an OSM primitive on the server.
|
---|
263 | *
|
---|
264 | * @param osm the primitive. Must not be null.
|
---|
265 | * @param monitor the progress monitor
|
---|
266 | * @throws OsmTransferException if something goes wrong
|
---|
267 | */
|
---|
268 | public void modifyPrimitive(OsmPrimitive osm, ProgressMonitor monitor) throws OsmTransferException {
|
---|
269 | String ret = null;
|
---|
270 | try {
|
---|
271 | ensureValidChangeset();
|
---|
272 | initialize(monitor);
|
---|
273 | // normal mode (0.6 and up) returns new object version.
|
---|
274 | ret = sendRequest("PUT", OsmPrimitiveType.from(osm).getAPIName()+"/" + osm.getId(), toXml(osm, true), monitor);
|
---|
275 | osm.setOsmId(osm.getId(), Integer.parseInt(ret.trim()));
|
---|
276 | osm.setChangesetId(getChangeset().getId());
|
---|
277 | osm.setVisible(true);
|
---|
278 | } catch(NumberFormatException e) {
|
---|
279 | throw new OsmTransferException(tr("Unexpected format of new version of modified primitive ''{0}''. Got ''{1}''.", osm.getId(), ret));
|
---|
280 | }
|
---|
281 | }
|
---|
282 |
|
---|
283 | /**
|
---|
284 | * Deletes an OSM primitive on the server.
|
---|
285 | * @param osm the primitive
|
---|
286 | * @throws OsmTransferException if something goes wrong
|
---|
287 | */
|
---|
288 | public void deletePrimitive(OsmPrimitive osm, ProgressMonitor monitor) throws OsmTransferException {
|
---|
289 | ensureValidChangeset();
|
---|
290 | initialize(monitor);
|
---|
291 | // can't use a the individual DELETE method in the 0.6 API. Java doesn't allow
|
---|
292 | // submitting a DELETE request with content, the 0.6 API requires it, however. Falling back
|
---|
293 | // to diff upload.
|
---|
294 | //
|
---|
295 | uploadDiff(Collections.singleton(osm), monitor.createSubTaskMonitor(ProgressMonitor.ALL_TICKS, false));
|
---|
296 | }
|
---|
297 |
|
---|
298 | /**
|
---|
299 | * Creates a new changeset based on the keys in <code>changeset</code>. If this
|
---|
300 | * method succeeds, changeset.getId() replies the id the server assigned to the new
|
---|
301 | * changeset
|
---|
302 | *
|
---|
303 | * The changeset must not be null, but its key/value-pairs may be empty.
|
---|
304 | *
|
---|
305 | * @param changeset the changeset toe be created. Must not be null.
|
---|
306 | * @param progressMonitor the progress monitor
|
---|
307 | * @throws OsmTransferException signifying a non-200 return code, or connection errors
|
---|
308 | * @throws IllegalArgumentException thrown if changeset is null
|
---|
309 | */
|
---|
310 | public void openChangeset(Changeset changeset, ProgressMonitor progressMonitor) throws OsmTransferException {
|
---|
311 | CheckParameterUtil.ensureParameterNotNull(changeset, "changeset");
|
---|
312 | try {
|
---|
313 | progressMonitor.beginTask((tr("Creating changeset...")));
|
---|
314 | initialize(progressMonitor);
|
---|
315 | String ret = "";
|
---|
316 | try {
|
---|
317 | ret = sendRequest("PUT", "changeset/create", toXml(changeset),progressMonitor);
|
---|
318 | changeset.setId(Integer.parseInt(ret.trim()));
|
---|
319 | changeset.setOpen(true);
|
---|
320 | } catch(NumberFormatException e){
|
---|
321 | throw new OsmTransferException(tr("Unexpected format of ID replied by the server. Got ''{0}''.", ret));
|
---|
322 | }
|
---|
323 | progressMonitor.setCustomText((tr("Successfully opened changeset {0}",changeset.getId())));
|
---|
324 | } finally {
|
---|
325 | progressMonitor.finishTask();
|
---|
326 | }
|
---|
327 | }
|
---|
328 |
|
---|
329 | /**
|
---|
330 | * Updates a changeset with the keys in <code>changesetUpdate</code>. The changeset must not
|
---|
331 | * be null and id > 0 must be true.
|
---|
332 | *
|
---|
333 | * @param changeset the changeset to update. Must not be null.
|
---|
334 | * @param monitor the progress monitor. If null, uses the {@see NullProgressMonitor#INSTANCE}.
|
---|
335 | *
|
---|
336 | * @throws OsmTransferException if something goes wrong.
|
---|
337 | * @throws IllegalArgumentException if changeset is null
|
---|
338 | * @throws IllegalArgumentException if changeset.getId() <= 0
|
---|
339 | *
|
---|
340 | */
|
---|
341 | public void updateChangeset(Changeset changeset, ProgressMonitor monitor) throws OsmTransferException {
|
---|
342 | CheckParameterUtil.ensureParameterNotNull(changeset, "changeset");
|
---|
343 | if (monitor == null) {
|
---|
344 | monitor = NullProgressMonitor.INSTANCE;
|
---|
345 | }
|
---|
346 | if (changeset.getId() <= 0)
|
---|
347 | throw new IllegalArgumentException(tr("Changeset ID > 0 expected. Got {0}.", changeset.getId()));
|
---|
348 | try {
|
---|
349 | monitor.beginTask(tr("Updating changeset..."));
|
---|
350 | initialize(monitor);
|
---|
351 | monitor.setCustomText(tr("Updating changeset {0}...", changeset.getId()));
|
---|
352 | sendRequest(
|
---|
353 | "PUT",
|
---|
354 | "changeset/" + changeset.getId(),
|
---|
355 | toXml(changeset),
|
---|
356 | monitor
|
---|
357 | );
|
---|
358 | } catch(ChangesetClosedException e) {
|
---|
359 | e.setSource(ChangesetClosedException.Source.UPDATE_CHANGESET);
|
---|
360 | throw e;
|
---|
361 | } catch(OsmApiException e) {
|
---|
362 | if (e.getResponseCode() == HttpURLConnection.HTTP_CONFLICT && ChangesetClosedException.errorHeaderMatchesPattern(e.getErrorHeader()))
|
---|
363 | throw new ChangesetClosedException(e.getErrorHeader(), ChangesetClosedException.Source.UPDATE_CHANGESET);
|
---|
364 | throw e;
|
---|
365 | } finally {
|
---|
366 | monitor.finishTask();
|
---|
367 | }
|
---|
368 | }
|
---|
369 |
|
---|
370 | /**
|
---|
371 | * Closes a changeset on the server. Sets changeset.setOpen(false) if this operation
|
---|
372 | * succeeds.
|
---|
373 | *
|
---|
374 | * @param changeset the changeset to be closed. Must not be null. changeset.getId() > 0 required.
|
---|
375 | * @param monitor the progress monitor. If null, uses {@see NullProgressMonitor#INSTANCE}
|
---|
376 | *
|
---|
377 | * @throws OsmTransferException if something goes wrong.
|
---|
378 | * @throws IllegalArgumentException thrown if changeset is null
|
---|
379 | * @throws IllegalArgumentException thrown if changeset.getId() <= 0
|
---|
380 | */
|
---|
381 | public void closeChangeset(Changeset changeset, ProgressMonitor monitor) throws OsmTransferException {
|
---|
382 | CheckParameterUtil.ensureParameterNotNull(changeset, "changeset");
|
---|
383 | if (monitor == null) {
|
---|
384 | monitor = NullProgressMonitor.INSTANCE;
|
---|
385 | }
|
---|
386 | if (changeset.getId() <= 0)
|
---|
387 | throw new IllegalArgumentException(tr("Changeset ID > 0 expected. Got {0}.", changeset.getId()));
|
---|
388 | try {
|
---|
389 | monitor.beginTask(tr("Closing changeset..."));
|
---|
390 | initialize(monitor);
|
---|
391 | sendRequest("PUT", "changeset" + "/" + changeset.getId() + "/close", null, monitor);
|
---|
392 | changeset.setOpen(false);
|
---|
393 | } finally {
|
---|
394 | monitor.finishTask();
|
---|
395 | }
|
---|
396 | }
|
---|
397 |
|
---|
398 | /**
|
---|
399 | * Uploads a list of changes in "diff" form to the server.
|
---|
400 | *
|
---|
401 | * @param list the list of changed OSM Primitives
|
---|
402 | * @param monitor the progress monitor
|
---|
403 | * @return list of processed primitives
|
---|
404 | * @throws OsmTransferException if something is wrong
|
---|
405 | */
|
---|
406 | public Collection<OsmPrimitive> uploadDiff(Collection<OsmPrimitive> list, ProgressMonitor monitor) throws OsmTransferException {
|
---|
407 | try {
|
---|
408 | monitor.beginTask("", list.size() * 2);
|
---|
409 | if (changeset == null)
|
---|
410 | throw new OsmTransferException(tr("No changeset present for diff upload."));
|
---|
411 |
|
---|
412 | initialize(monitor);
|
---|
413 |
|
---|
414 | // prepare upload request
|
---|
415 | //
|
---|
416 | OsmChangeBuilder changeBuilder = new OsmChangeBuilder(changeset);
|
---|
417 | monitor.subTask(tr("Preparing upload request..."));
|
---|
418 | changeBuilder.start();
|
---|
419 | changeBuilder.append(list);
|
---|
420 | changeBuilder.finish();
|
---|
421 | String diffUploadRequest = changeBuilder.getDocument();
|
---|
422 |
|
---|
423 | // Upload to the server
|
---|
424 | //
|
---|
425 | monitor.indeterminateSubTask(
|
---|
426 | trn("Uploading {0} object...", "Uploading {0} objects...", list.size(), list.size()));
|
---|
427 | String diffUploadResponse = sendRequest("POST", "changeset/" + changeset.getId() + "/upload", diffUploadRequest,monitor);
|
---|
428 |
|
---|
429 | // Process the response from the server
|
---|
430 | //
|
---|
431 | DiffResultProcessor reader = new DiffResultProcessor(list);
|
---|
432 | reader.parse(diffUploadResponse, monitor.createSubTaskMonitor(ProgressMonitor.ALL_TICKS, false));
|
---|
433 | return reader.postProcess(
|
---|
434 | getChangeset(),
|
---|
435 | monitor.createSubTaskMonitor(ProgressMonitor.ALL_TICKS, false)
|
---|
436 | );
|
---|
437 | } catch(OsmTransferException e) {
|
---|
438 | throw e;
|
---|
439 | } catch(OsmDataParsingException e) {
|
---|
440 | throw new OsmTransferException(e);
|
---|
441 | } finally {
|
---|
442 | monitor.finishTask();
|
---|
443 | }
|
---|
444 | }
|
---|
445 |
|
---|
446 | private void sleepAndListen(int retry, ProgressMonitor monitor) throws OsmTransferCancelledException {
|
---|
447 | System.out.print(tr("Waiting 10 seconds ... "));
|
---|
448 | for(int i=0; i < 10; i++) {
|
---|
449 | if (monitor != null) {
|
---|
450 | monitor.setCustomText(tr("Starting retry {0} of {1} in {2} seconds ...", getMaxRetries() - retry,getMaxRetries(), 10-i));
|
---|
451 | }
|
---|
452 | if (cancel)
|
---|
453 | throw new OsmTransferCancelledException();
|
---|
454 | try {
|
---|
455 | Thread.sleep(1000);
|
---|
456 | } catch (InterruptedException ex) {}
|
---|
457 | }
|
---|
458 | System.out.println(tr("OK - trying again."));
|
---|
459 | }
|
---|
460 |
|
---|
461 | /**
|
---|
462 | * Replies the max. number of retries in case of 5XX errors on the server
|
---|
463 | *
|
---|
464 | * @return the max number of retries
|
---|
465 | */
|
---|
466 | protected int getMaxRetries() {
|
---|
467 | int ret = Main.pref.getInteger("osm-server.max-num-retries", DEFAULT_MAX_NUM_RETRIES);
|
---|
468 | return Math.max(ret,0);
|
---|
469 | }
|
---|
470 |
|
---|
471 | protected boolean isUsingOAuth() {
|
---|
472 | String authMethod = Main.pref.get("osm-server.auth-method", "basic");
|
---|
473 | return authMethod.equals("oauth");
|
---|
474 | }
|
---|
475 |
|
---|
476 | private String sendRequest(String requestMethod, String urlSuffix,String requestBody, ProgressMonitor monitor) throws OsmTransferException {
|
---|
477 | return sendRequest(requestMethod, urlSuffix, requestBody, monitor, true);
|
---|
478 | }
|
---|
479 |
|
---|
480 | /**
|
---|
481 | * Generic method for sending requests to the OSM API.
|
---|
482 | *
|
---|
483 | * This method will automatically re-try any requests that are answered with a 5xx
|
---|
484 | * error code, or that resulted in a timeout exception from the TCP layer.
|
---|
485 | *
|
---|
486 | * @param requestMethod The http method used when talking with the server.
|
---|
487 | * @param urlSuffix The suffix to add at the server url, not including the version number,
|
---|
488 | * but including any object ids (e.g. "/way/1234/history").
|
---|
489 | * @param requestBody the body of the HTTP request, if any.
|
---|
490 | * @param monitor the progress monitor
|
---|
491 | * @param doAuthenticate set to true, if the request sent to the server shall include authentication
|
---|
492 | * credentials;
|
---|
493 | *
|
---|
494 | * @return the body of the HTTP response, if and only if the response code was "200 OK".
|
---|
495 | * @exception OsmTransferException if the HTTP return code was not 200 (and retries have
|
---|
496 | * been exhausted), or rewrapping a Java exception.
|
---|
497 | */
|
---|
498 | private String sendRequest(String requestMethod, String urlSuffix,String requestBody, ProgressMonitor monitor, boolean doAuthenticate) throws OsmTransferException {
|
---|
499 | StringBuffer responseBody = new StringBuffer();
|
---|
500 | int retries = getMaxRetries();
|
---|
501 |
|
---|
502 | while(true) { // the retry loop
|
---|
503 | try {
|
---|
504 | URL url = new URL(new URL(getBaseUrl()), urlSuffix);
|
---|
505 | System.out.print(requestMethod + " " + url + "... ");
|
---|
506 | activeConnection = (HttpURLConnection)url.openConnection();
|
---|
507 | activeConnection.setConnectTimeout(15000);
|
---|
508 | activeConnection.setRequestMethod(requestMethod);
|
---|
509 | if (doAuthenticate) {
|
---|
510 | addAuth(activeConnection);
|
---|
511 | }
|
---|
512 |
|
---|
513 | if (requestMethod.equals("PUT") || requestMethod.equals("POST") || requestMethod.equals("DELETE")) {
|
---|
514 | activeConnection.setDoOutput(true);
|
---|
515 | activeConnection.setRequestProperty("Content-type", "text/xml");
|
---|
516 | OutputStream out = activeConnection.getOutputStream();
|
---|
517 |
|
---|
518 | // It seems that certain bits of the Ruby API are very unhappy upon
|
---|
519 | // receipt of a PUT/POST message without a Content-length header,
|
---|
520 | // even if the request has no payload.
|
---|
521 | // Since Java will not generate a Content-length header unless
|
---|
522 | // we use the output stream, we create an output stream for PUT/POST
|
---|
523 | // even if there is no payload.
|
---|
524 | if (requestBody != null) {
|
---|
525 | BufferedWriter bwr = new BufferedWriter(new OutputStreamWriter(out, "UTF-8"));
|
---|
526 | bwr.write(requestBody);
|
---|
527 | bwr.flush();
|
---|
528 | }
|
---|
529 | out.close();
|
---|
530 | }
|
---|
531 |
|
---|
532 | activeConnection.connect();
|
---|
533 | System.out.println(activeConnection.getResponseMessage());
|
---|
534 | int retCode = activeConnection.getResponseCode();
|
---|
535 |
|
---|
536 | if (retCode >= 500) {
|
---|
537 | if (retries-- > 0) {
|
---|
538 | sleepAndListen(retries, monitor);
|
---|
539 | System.out.println(tr("Starting retry {0} of {1}.", getMaxRetries() - retries,getMaxRetries()));
|
---|
540 | continue;
|
---|
541 | }
|
---|
542 | }
|
---|
543 |
|
---|
544 | // populate return fields.
|
---|
545 | responseBody.setLength(0);
|
---|
546 |
|
---|
547 | // If the API returned an error code like 403 forbidden, getInputStream
|
---|
548 | // will fail with an IOException.
|
---|
549 | InputStream i = null;
|
---|
550 | try {
|
---|
551 | i = activeConnection.getInputStream();
|
---|
552 | } catch (IOException ioe) {
|
---|
553 | i = activeConnection.getErrorStream();
|
---|
554 | }
|
---|
555 | if (i != null) {
|
---|
556 | // the input stream can be null if both the input and the error stream
|
---|
557 | // are null. Seems to be the case if the OSM server replies a 401
|
---|
558 | // Unauthorized, see #3887.
|
---|
559 | //
|
---|
560 | BufferedReader in = new BufferedReader(new InputStreamReader(i));
|
---|
561 | String s;
|
---|
562 | while((s = in.readLine()) != null) {
|
---|
563 | responseBody.append(s);
|
---|
564 | responseBody.append("\n");
|
---|
565 | }
|
---|
566 | }
|
---|
567 | String errorHeader = null;
|
---|
568 | // Look for a detailed error message from the server
|
---|
569 | if (activeConnection.getHeaderField("Error") != null) {
|
---|
570 | errorHeader = activeConnection.getHeaderField("Error");
|
---|
571 | System.err.println("Error header: " + errorHeader);
|
---|
572 | } else if (retCode != 200 && responseBody.length()>0) {
|
---|
573 | System.err.println("Error body: " + responseBody);
|
---|
574 | }
|
---|
575 | activeConnection.disconnect();
|
---|
576 |
|
---|
577 | errorHeader = errorHeader == null? null : errorHeader.trim();
|
---|
578 | String errorBody = responseBody.length() == 0? null : responseBody.toString().trim();
|
---|
579 | switch(retCode) {
|
---|
580 | case HttpURLConnection.HTTP_OK:
|
---|
581 | return responseBody.toString();
|
---|
582 | case HttpURLConnection.HTTP_GONE:
|
---|
583 | throw new OsmApiPrimitiveGoneException(errorHeader, errorBody);
|
---|
584 | case HttpURLConnection.HTTP_CONFLICT:
|
---|
585 | if (ChangesetClosedException.errorHeaderMatchesPattern(errorHeader))
|
---|
586 | throw new ChangesetClosedException(errorBody, ChangesetClosedException.Source.UPLOAD_DATA);
|
---|
587 | else
|
---|
588 | throw new OsmApiException(retCode, errorHeader, errorBody);
|
---|
589 | case HttpURLConnection.HTTP_FORBIDDEN:
|
---|
590 | OsmApiException e = new OsmApiException(retCode, errorHeader, errorBody);
|
---|
591 | e.setAccessedUrl(activeConnection.getURL().toString());
|
---|
592 | throw e;
|
---|
593 | default:
|
---|
594 | throw new OsmApiException(retCode, errorHeader, errorBody);
|
---|
595 | }
|
---|
596 | } catch (UnknownHostException e) {
|
---|
597 | throw new OsmTransferException(e);
|
---|
598 | } catch (SocketTimeoutException e) {
|
---|
599 | if (retries-- > 0) {
|
---|
600 | continue;
|
---|
601 | }
|
---|
602 | throw new OsmTransferException(e);
|
---|
603 | } catch (ConnectException e) {
|
---|
604 | if (retries-- > 0) {
|
---|
605 | continue;
|
---|
606 | }
|
---|
607 | throw new OsmTransferException(e);
|
---|
608 | } catch(IOException e){
|
---|
609 | throw new OsmTransferException(e);
|
---|
610 | } catch(OsmTransferCancelledException e){
|
---|
611 | throw e;
|
---|
612 | } catch(OsmTransferException e) {
|
---|
613 | throw e;
|
---|
614 | }
|
---|
615 | }
|
---|
616 | }
|
---|
617 |
|
---|
618 | /**
|
---|
619 | * returns the API capabilities; null, if the API is not initialized yet
|
---|
620 | *
|
---|
621 | * @return the API capabilities
|
---|
622 | */
|
---|
623 | public Capabilities getCapabilities() {
|
---|
624 | return capabilities;
|
---|
625 | }
|
---|
626 |
|
---|
627 | /**
|
---|
628 | * Ensures that the current changeset can be used for uploading data
|
---|
629 | *
|
---|
630 | * @throws OsmTransferException thrown if the current changeset can't be used for
|
---|
631 | * uploading data
|
---|
632 | */
|
---|
633 | protected void ensureValidChangeset() throws OsmTransferException {
|
---|
634 | if (changeset == null)
|
---|
635 | throw new OsmTransferException(tr("Current changeset is null. Cannot upload data."));
|
---|
636 | if (changeset.getId() <= 0)
|
---|
637 | throw new OsmTransferException(tr("ID of current changeset > 0 required. Current ID is {0}.", changeset.getId()));
|
---|
638 | }
|
---|
639 | /**
|
---|
640 | * Replies the changeset data uploads are currently directed to
|
---|
641 | *
|
---|
642 | * @return the changeset data uploads are currently directed to
|
---|
643 | */
|
---|
644 | public Changeset getChangeset() {
|
---|
645 | return changeset;
|
---|
646 | }
|
---|
647 |
|
---|
648 | /**
|
---|
649 | * Sets the changesets to which further data uploads are directed. The changeset
|
---|
650 | * can be null. If it isn't null it must have been created, i.e. id > 0 is required. Furthermore,
|
---|
651 | * it must be open.
|
---|
652 | *
|
---|
653 | * @param changeset the changeset
|
---|
654 | * @throws IllegalArgumentException thrown if changeset.getId() <= 0
|
---|
655 | * @throws IllegalArgumentException thrown if !changeset.isOpen()
|
---|
656 | */
|
---|
657 | public void setChangeset(Changeset changeset) {
|
---|
658 | if (changeset == null) {
|
---|
659 | this.changeset = null;
|
---|
660 | return;
|
---|
661 | }
|
---|
662 | if (changeset.getId() <= 0)
|
---|
663 | throw new IllegalArgumentException(tr("Changeset ID > 0 expected. Got {0}.", changeset.getId()));
|
---|
664 | if (!changeset.isOpen())
|
---|
665 | throw new IllegalArgumentException(tr("Open changeset expected. Got closed changeset with id {0}.", changeset.getId()));
|
---|
666 | this.changeset = changeset;
|
---|
667 | }
|
---|
668 | }
|
---|