source: josm/trunk/src/org/openstreetmap/josm/io/OsmApi.java@ 2037

Last change on this file since 2037 was 2037, checked in by Gubaer, 15 years ago

Improved cancellation of upload tasks
Refactored upload dialog
fixed #2597: Size of upload dialog - now restores dialog size from preferences
fixed #2913: Upload dialog enters scrolling-mode when JOSM isn't maximized - no scroling anymore in ExtendeDialog for UploadDialog
fixed #2518: focus & select comment editing field

File size: 19.9 KB
Line 
1//License: GPL. See README for details.
2package org.openstreetmap.josm.io;
3
4import static org.openstreetmap.josm.tools.I18n.tr;
5
6import java.io.BufferedReader;
7import java.io.BufferedWriter;
8import java.io.IOException;
9import java.io.InputStream;
10import java.io.InputStreamReader;
11import java.io.OutputStream;
12import java.io.OutputStreamWriter;
13import java.io.PrintWriter;
14import java.io.StringReader;
15import java.io.StringWriter;
16import java.net.ConnectException;
17import java.net.HttpURLConnection;
18import java.net.SocketTimeoutException;
19import java.net.URL;
20import java.net.UnknownHostException;
21import java.util.ArrayList;
22import java.util.Collection;
23import java.util.Collections;
24import java.util.HashMap;
25import java.util.Properties;
26
27import javax.xml.parsers.SAXParserFactory;
28
29import org.openstreetmap.josm.Main;
30import org.openstreetmap.josm.data.osm.Changeset;
31import org.openstreetmap.josm.data.osm.OsmPrimitive;
32import org.openstreetmap.josm.data.osm.OsmPrimitiveType;
33import org.openstreetmap.josm.data.osm.visitor.CreateOsmChangeVisitor;
34import org.openstreetmap.josm.gui.progress.ProgressMonitor;
35import org.xml.sax.Attributes;
36import org.xml.sax.InputSource;
37import org.xml.sax.SAXException;
38import org.xml.sax.helpers.DefaultHandler;
39
40/**
41 * Class that encapsulates the communications with the OSM API.
42 *
43 * All interaction with the server-side OSM API should go through this class.
44 *
45 * It is conceivable to extract this into an interface later and create various
46 * classes implementing the interface, to be able to talk to various kinds of servers.
47 *
48 */
49public class OsmApi extends OsmConnection {
50 /** max number of retries to send a request in case of HTTP 500 errors or timeouts */
51 static public final int DEFAULT_MAX_NUM_RETRIES = 5;
52
53 /** the collection of instantiated OSM APIs */
54 private static HashMap<String, OsmApi> instances = new HashMap<String, OsmApi>();
55
56 /**
57 * replies the {@see OsmApi} for a given server URL
58 *
59 * @param serverUrl the server URL
60 * @return the OsmApi
61 * @throws IllegalArgumentException thrown, if serverUrl is null
62 *
63 */
64 static public OsmApi getOsmApi(String serverUrl) {
65 OsmApi api = instances.get(serverUrl);
66 if (api == null) {
67 api = new OsmApi(serverUrl);
68 instances.put(serverUrl,api);
69 }
70 return api;
71 }
72 /**
73 * replies the {@see OsmApi} for the URL given by the preference <code>osm-server.url</code>
74 *
75 * @return the OsmApi
76 * @exception IllegalStateException thrown, if the preference <code>osm-server.url</code> is not set
77 *
78 */
79 static public OsmApi getOsmApi() {
80 String serverUrl = Main.pref.get("osm-server.url", "http://api.openstreetmap.org/api");
81 if (serverUrl == null)
82 throw new IllegalStateException(tr("preference ''{0}'' missing. Can't initialize OsmApi", "osm-server.url"));
83 return getOsmApi(serverUrl);
84 }
85
86 /** the server URL */
87 private String serverUrl;
88
89 /**
90 * Object describing current changeset
91 */
92 private Changeset changeset;
93
94 /**
95 * API version used for server communications
96 */
97 private String version = null;
98
99 /** the api capabilities */
100 private Capabilities capabilities = new Capabilities();
101
102 /**
103 * true if successfully initialized
104 */
105 private boolean initialized = false;
106
107 private StringWriter swriter = new StringWriter();
108 private OsmWriter osmWriter = new OsmWriter(new PrintWriter(swriter), true, null);
109
110 /**
111 * A parser for the "capabilities" response XML
112 */
113 private class CapabilitiesParser extends DefaultHandler {
114 @Override
115 public void startDocument() throws SAXException {
116 capabilities.clear();
117 }
118
119 @Override public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException {
120 for (int i=0; i< qName.length(); i++) {
121 capabilities.put(qName, atts.getQName(i), atts.getValue(i));
122 }
123 }
124 }
125
126 /**
127 * creates an OSM api for a specific server URL
128 *
129 * @param serverUrl the server URL. Must not be null
130 * @exception IllegalArgumentException thrown, if serverUrl is null
131 */
132 protected OsmApi(String serverUrl) {
133 if (serverUrl == null)
134 throw new IllegalArgumentException(tr("parameter '{0}' must not be null", "serverUrl"));
135 this.serverUrl = serverUrl;
136 }
137
138 /**
139 * Returns the OSM protocol version we use to talk to the server.
140 * @return protocol version, or null if not yet negotiated.
141 */
142 public String getVersion() {
143 return version;
144 }
145
146 /**
147 * Returns true if the negotiated version supports changesets.
148 * @return true if the negotiated version supports changesets.
149 */
150 public boolean hasChangesetSupport() {
151 return ((version != null) && (version.compareTo("0.6")>=0));
152 }
153
154 /**
155 * Initializes this component by negotiating a protocol version with the server.
156 *
157 * @exception OsmApiInitializationException thrown, if an exception occurs
158 */
159 public void initialize(ProgressMonitor monitor) throws OsmApiInitializationException {
160 if (initialized)
161 return;
162 cancel = false;
163 initAuthentication();
164 try {
165 String s = sendRequest("GET", "capabilities", null,monitor);
166 InputSource inputSource = new InputSource(new StringReader(s));
167 SAXParserFactory.newInstance().newSAXParser().parse(inputSource, new CapabilitiesParser());
168 if (capabilities.supportsVersion("0.6")) {
169 version = "0.6";
170 } else if (capabilities.supportsVersion("0.5")) {
171 version = "0.5";
172 } else {
173 System.err.println(tr("This version of JOSM is incompatible with the configured server."));
174 System.err.println(tr("It supports protocol versions 0.5 and 0.6, while the server says it supports {0} to {1}.",
175 capabilities.get("version", "minimum"), capabilities.get("version", "maximum")));
176 initialized = false;
177 }
178 System.out.println(tr("Communications with {0} established using protocol version {1}",
179 serverUrl,
180 version));
181 osmWriter.setVersion(version);
182 initialized = true;
183 } catch (Exception ex) {
184 initialized = false;
185 throw new OsmApiInitializationException(ex);
186 }
187 }
188
189 /**
190 * Makes an XML string from an OSM primitive. Uses the OsmWriter class.
191 * @param o the OSM primitive
192 * @param addBody true to generate the full XML, false to only generate the encapsulating tag
193 * @return XML string
194 */
195 private String toXml(OsmPrimitive o, boolean addBody) {
196 swriter.getBuffer().setLength(0);
197 osmWriter.setWithBody(addBody);
198 osmWriter.setChangeset(changeset);
199 osmWriter.header();
200 o.visit(osmWriter);
201 osmWriter.footer();
202 osmWriter.out.flush();
203 return swriter.toString();
204 }
205
206 /**
207 * Returns the base URL for API requests, including the negotiated version number.
208 * @return base URL string
209 */
210 public String getBaseUrl() {
211 StringBuffer rv = new StringBuffer(serverUrl);
212 if (version != null) {
213 rv.append("/");
214 rv.append(version);
215 }
216 rv.append("/");
217 // this works around a ruby (or lighttpd) bug where two consecutive slashes in
218 // an URL will cause a "404 not found" response.
219 int p; while ((p = rv.indexOf("//", 6)) > -1) { rv.delete(p, p + 1); }
220 return rv.toString();
221 }
222
223 /**
224 * Creates an OSM primitive on the server. The OsmPrimitive object passed in
225 * is modified by giving it the server-assigned id.
226 *
227 * @param osm the primitive
228 * @throws OsmTransferException if something goes wrong
229 */
230 public void createPrimitive(OsmPrimitive osm, ProgressMonitor monitor) throws OsmTransferException {
231 initialize(monitor);
232 String ret = "";
233 try {
234 ret = sendRequest("PUT", OsmPrimitiveType.from(osm).getAPIName()+"/create", toXml(osm, true),monitor);
235 osm.id = Long.parseLong(ret.trim());
236 osm.version = 1;
237 } catch(NumberFormatException e){
238 throw new OsmTransferException(tr("unexpected format of id replied by the server, got ''{0}''", ret));
239 }
240 }
241
242 /**
243 * Modifies an OSM primitive on the server. For protocols greater than 0.5,
244 * the OsmPrimitive object passed in is modified by giving it the server-assigned
245 * version.
246 *
247 * @param osm the primitive
248 * @throws OsmTransferException if something goes wrong
249 */
250 public void modifyPrimitive(OsmPrimitive osm, ProgressMonitor monitor) throws OsmTransferException {
251 initialize(monitor);
252 if (version.equals("0.5")) {
253 // legacy mode does not return the new object version.
254 sendRequest("PUT", OsmPrimitiveType.from(osm).getAPIName()+"/" + osm.getId(), toXml(osm, true),monitor);
255 } else {
256 String ret = null;
257 // normal mode (0.6 and up) returns new object version.
258 try {
259 ret = sendRequest("PUT", OsmPrimitiveType.from(osm).getAPIName()+"/" + osm.getId(), toXml(osm, true), monitor);
260 osm.version = Integer.parseInt(ret.trim());
261 } catch(NumberFormatException e) {
262 throw new OsmTransferException(tr("unexpected format of new version of modified primitive ''{0}'', got ''{1}''", osm.getId(), ret));
263 }
264 }
265 }
266
267 /**
268 * Deletes an OSM primitive on the server.
269 * @param osm the primitive
270 * @throws OsmTransferException if something goes wrong
271 */
272 public void deletePrimitive(OsmPrimitive osm, ProgressMonitor monitor) throws OsmTransferException {
273 initialize(monitor);
274 // can't use a the individual DELETE method in the 0.6 API. Java doesn't allow
275 // submitting a DELETE request with content, the 0.6 API requires it, however. Falling back
276 // to diff upload.
277 //
278 uploadDiff(Collections.singleton(osm), monitor.createSubTaskMonitor(ProgressMonitor.ALL_TICKS, false));
279 }
280
281 /**
282 * Creates a new changeset on the server to use for subsequent calls.
283 * @param comment the "commit comment" for the new changeset
284 * @throws OsmTransferException signifying a non-200 return code, or connection errors
285 */
286 public void createChangeset(String comment, ProgressMonitor progressMonitor) throws OsmTransferException {
287 progressMonitor.beginTask((tr("Opening changeset...")));
288 try {
289 changeset = new Changeset();
290 Properties sysProp = System.getProperties();
291 Object ua = sysProp.get("http.agent");
292 changeset.put("created_by", (ua == null) ? "JOSM" : ua.toString());
293 changeset.put("comment", comment);
294 createPrimitive(changeset, progressMonitor);
295 } finally {
296 progressMonitor.finishTask();
297 }
298 }
299
300 /**
301 * Closes a changeset on the server.
302 *
303 * @throws OsmTransferException if something goes wrong.
304 */
305 public void stopChangeset(ProgressMonitor progressMonitor) throws OsmTransferException {
306 progressMonitor.beginTask(tr("Closing changeset {0}...", changeset.getId()));
307 try {
308 initialize(progressMonitor);
309 sendRequest("PUT", "changeset" + "/" + changeset.getId() + "/close", null, progressMonitor);
310 changeset = null;
311 } finally {
312 progressMonitor.finishTask();
313 }
314 }
315
316 /**
317 * Uploads a list of changes in "diff" form to the server.
318 *
319 * @param list the list of changed OSM Primitives
320 * @return list of processed primitives
321 * @throws OsmTransferException if something is wrong
322 */
323 public Collection<OsmPrimitive> uploadDiff(final Collection<OsmPrimitive> list, ProgressMonitor progressMonitor) throws OsmTransferException {
324
325 progressMonitor.beginTask("", list.size() * 2);
326 try {
327 if (changeset == null)
328 throw new OsmTransferException(tr("No changeset present for diff upload"));
329
330 initialize(progressMonitor);
331 final ArrayList<OsmPrimitive> processed = new ArrayList<OsmPrimitive>();
332
333 CreateOsmChangeVisitor duv = new CreateOsmChangeVisitor(changeset, OsmApi.this);
334
335 progressMonitor.subTask(tr("Preparing..."));
336 for (OsmPrimitive osm : list) {
337 osm.visit(duv);
338 progressMonitor.worked(1);
339 }
340 progressMonitor.indeterminateSubTask(tr("Uploading..."));
341
342 String diff = duv.getDocument();
343 try {
344 String diffresult = sendRequest("POST", "changeset/" + changeset.getId() + "/upload", diff,progressMonitor);
345 DiffResultReader.parseDiffResult(diffresult, list, processed, duv.getNewIdMap(),
346 progressMonitor.createSubTaskMonitor(ProgressMonitor.ALL_TICKS, false));
347 } catch(OsmTransferException e) {
348 throw e;
349 } catch(Exception e) {
350 throw new OsmTransferException(e);
351 }
352
353 return processed;
354 } finally {
355 progressMonitor.finishTask();
356 }
357 }
358
359
360
361 private void sleepAndListen(int retry, ProgressMonitor monitor) throws OsmTransferCancelledException {
362 System.out.print(tr("Waiting 10 seconds ... "));
363 for(int i=0; i < 10; i++) {
364 if (monitor != null) {
365 monitor.setCustomText(tr("Starting retry {0} of {1} in {2} seconds ...", getMaxRetries() - retry,getMaxRetries(), 10-i));
366 }
367 if (cancel || isAuthCancelled())
368 throw new OsmTransferCancelledException();
369 try {
370 Thread.sleep(1000);
371 } catch (InterruptedException ex) {}
372 }
373 System.out.println(tr("OK - trying again."));
374 }
375
376 /**
377 * Replies the max. number of retries in case of 5XX errors on the server
378 *
379 * @return the max number of retries
380 */
381 protected int getMaxRetries() {
382 int ret = Main.pref.getInteger("osm-server.max-num-retries", DEFAULT_MAX_NUM_RETRIES);
383 return Math.max(ret,0);
384 }
385
386 /**
387 * Generic method for sending requests to the OSM API.
388 *
389 * This method will automatically re-try any requests that are answered with a 5xx
390 * error code, or that resulted in a timeout exception from the TCP layer.
391 *
392 * @param requestMethod The http method used when talking with the server.
393 * @param urlSuffix The suffix to add at the server url, not including the version number,
394 * but including any object ids (e.g. "/way/1234/history").
395 * @param requestBody the body of the HTTP request, if any.
396 *
397 * @return the body of the HTTP response, if and only if the response code was "200 OK".
398 * @exception OsmTransferException if the HTTP return code was not 200 (and retries have
399 * been exhausted), or rewrapping a Java exception.
400 */
401 private String sendRequest(String requestMethod, String urlSuffix,String requestBody, ProgressMonitor monitor) throws OsmTransferException {
402
403 StringBuffer responseBody = new StringBuffer();
404
405 int retries = getMaxRetries();
406
407 while(true) { // the retry loop
408 try {
409 URL url = new URL(new URL(getBaseUrl()), urlSuffix);
410 System.out.print(requestMethod + " " + url + "... ");
411 activeConnection = (HttpURLConnection)url.openConnection();
412 activeConnection.setConnectTimeout(15000);
413 activeConnection.setRequestMethod(requestMethod);
414 addAuth(activeConnection);
415
416 if (requestMethod.equals("PUT") || requestMethod.equals("POST") || requestMethod.equals("DELETE")) {
417 activeConnection.setDoOutput(true);
418 activeConnection.setRequestProperty("Content-type", "text/xml");
419 OutputStream out = activeConnection.getOutputStream();
420
421 // It seems that certain bits of the Ruby API are very unhappy upon
422 // receipt of a PUT/POST message withtout a Content-length header,
423 // even if the request has no payload.
424 // Since Java will not generate a Content-length header unless
425 // we use the output stream, we create an output stream for PUT/POST
426 // even if there is no payload.
427 if (requestBody != null) {
428 BufferedWriter bwr = new BufferedWriter(new OutputStreamWriter(out, "UTF-8"));
429 bwr.write(requestBody);
430 bwr.flush();
431 }
432 out.close();
433 }
434
435 activeConnection.connect();
436 System.out.println(activeConnection.getResponseMessage());
437 int retCode = activeConnection.getResponseCode();
438
439 if (retCode >= 500) {
440 if (retries-- > 0) {
441 sleepAndListen(retries, monitor);
442 System.out.println(tr("Starting retry {0} of {1}.", getMaxRetries() - retries,getMaxRetries()));
443 continue;
444 }
445 }
446
447 // populate return fields.
448 responseBody.setLength(0);
449
450 // If the API returned an error code like 403 forbidden, getInputStream
451 // will fail with an IOException.
452 InputStream i = null;
453 try {
454 i = activeConnection.getInputStream();
455 } catch (IOException ioe) {
456 i = activeConnection.getErrorStream();
457 }
458 BufferedReader in = new BufferedReader(new InputStreamReader(i));
459
460 String s;
461 while((s = in.readLine()) != null) {
462 responseBody.append(s);
463 responseBody.append("\n");
464 }
465 String errorHeader = null;
466 // Look for a detailed error message from the server
467 if (activeConnection.getHeaderField("Error") != null) {
468 errorHeader = activeConnection.getHeaderField("Error");
469 System.err.println("Error header: " + errorHeader);
470 } else if (retCode != 200 && responseBody.length()>0) {
471 System.err.println("Error body: " + responseBody);
472 }
473 activeConnection.disconnect();
474
475 if (retCode != 200)
476 throw new OsmApiException(
477 retCode,
478 errorHeader == null? null : errorHeader.trim(),
479 responseBody == null ? null : responseBody.toString().trim()
480 );
481
482 return responseBody.toString();
483 } catch (UnknownHostException e) {
484 throw new OsmTransferException(e);
485 } catch (SocketTimeoutException e) {
486 if (retries-- > 0) {
487 continue;
488 }
489 throw new OsmTransferException(e);
490 } catch (ConnectException e) {
491 if (retries-- > 0) {
492 continue;
493 }
494 throw new OsmTransferException(e);
495 } catch (Exception e) {
496 if (e instanceof OsmTransferException) throw (OsmTransferException) e;
497 throw new OsmTransferException(e);
498 }
499 }
500 }
501
502 /**
503 * returns the API capabilities; null, if the API is not initialized yet
504 *
505 * @return the API capabilities
506 */
507 public Capabilities getCapabilities() {
508 return capabilities;
509 }
510
511 /**
512 * Replies the current changeset
513 *
514 * @return the current changeset
515 */
516 public Changeset getCurrentChangeset() {
517 return changeset;
518 }
519}
Note: See TracBrowser for help on using the repository browser.