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

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

fixed #3041: Relation Editor: Provide action for zooming to a particular member

File size: 19.2 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.HashMap;
24import java.util.Properties;
25
26import javax.swing.JPopupMenu;
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() throws OsmApiInitializationException {
160 if (initialized)
161 return;
162 initAuthentication();
163 try {
164 String s = sendRequest("GET", "capabilities", null);
165 InputSource inputSource = new InputSource(new StringReader(s));
166 SAXParserFactory.newInstance().newSAXParser().parse(inputSource, new CapabilitiesParser());
167 if (capabilities.supportsVersion("0.6")) {
168 version = "0.6";
169 } else if (capabilities.supportsVersion("0.5")) {
170 version = "0.5";
171 } else {
172 System.err.println(tr("This version of JOSM is incompatible with the configured server."));
173 System.err.println(tr("It supports protocol versions 0.5 and 0.6, while the server says it supports {0} to {1}.",
174 capabilities.get("version", "minimum"), capabilities.get("version", "maximum")));
175 initialized = false;
176 }
177 System.out.println(tr("Communications with {0} established using protocol version {1}",
178 serverUrl,
179 version));
180 osmWriter.setVersion(version);
181 initialized = true;
182 } catch (Exception ex) {
183 initialized = false;
184 throw new OsmApiInitializationException(ex);
185 }
186 }
187
188 /**
189 * Makes an XML string from an OSM primitive. Uses the OsmWriter class.
190 * @param o the OSM primitive
191 * @param addBody true to generate the full XML, false to only generate the encapsulating tag
192 * @return XML string
193 */
194 private String toXml(OsmPrimitive o, boolean addBody) {
195 swriter.getBuffer().setLength(0);
196 osmWriter.setWithBody(addBody);
197 osmWriter.setChangeset(changeset);
198 osmWriter.header();
199 o.visit(osmWriter);
200 osmWriter.footer();
201 osmWriter.out.flush();
202 return swriter.toString();
203 }
204
205 /**
206 * Returns the base URL for API requests, including the negotiated version number.
207 * @return base URL string
208 */
209 public String getBaseUrl() {
210 StringBuffer rv = new StringBuffer(serverUrl);
211 if (version != null) {
212 rv.append("/");
213 rv.append(version);
214 }
215 rv.append("/");
216 // this works around a ruby (or lighttpd) bug where two consecutive slashes in
217 // an URL will cause a "404 not found" response.
218 int p; while ((p = rv.indexOf("//", 6)) > -1) { rv.delete(p, p + 1); }
219 return rv.toString();
220 }
221
222 /**
223 * Creates an OSM primitive on the server. The OsmPrimitive object passed in
224 * is modified by giving it the server-assigned id.
225 *
226 * @param osm the primitive
227 * @throws OsmTransferException if something goes wrong
228 */
229 public void createPrimitive(OsmPrimitive osm) throws OsmTransferException {
230 initialize();
231 String ret = "";
232 try {
233 ret = sendRequest("PUT", OsmPrimitiveType.from(osm).getAPIName()+"/create", toXml(osm, true));
234 osm.id = Long.parseLong(ret.trim());
235 osm.version = 1;
236 } catch(NumberFormatException e){
237 throw new OsmTransferException(tr("unexpected format of id replied by the server, got ''{0}''", ret));
238 }
239 }
240
241 /**
242 * Modifies an OSM primitive on the server. For protocols greater than 0.5,
243 * the OsmPrimitive object passed in is modified by giving it the server-assigned
244 * version.
245 *
246 * @param osm the primitive
247 * @throws OsmTransferException if something goes wrong
248 */
249 public void modifyPrimitive(OsmPrimitive osm) throws OsmTransferException {
250 initialize();
251 if (version.equals("0.5")) {
252 // legacy mode does not return the new object version.
253 sendRequest("PUT", OsmPrimitiveType.from(osm).getAPIName()+"/" + osm.id, toXml(osm, true));
254 } else {
255 String ret = null;
256 // normal mode (0.6 and up) returns new object version.
257 try {
258 ret = sendRequest("PUT", OsmPrimitiveType.from(osm).getAPIName()+"/" + osm.id, toXml(osm, true));
259 osm.version = Integer.parseInt(ret.trim());
260 } catch(NumberFormatException e) {
261 throw new OsmTransferException(tr("unexpected format of new version of modified primitive ''{0}'', got ''{1}''", osm.id, ret));
262 }
263 }
264 }
265
266 /**
267 * Deletes an OSM primitive on the server.
268 * @param osm the primitive
269 * @throws OsmTransferException if something goes wrong
270 */
271 public void deletePrimitive(OsmPrimitive osm) throws OsmTransferException {
272 initialize();
273 // legacy mode does not require payload. normal mode (0.6 and up) requires payload for version matching.
274 sendRequest("DELETE", OsmPrimitiveType.from(osm).getAPIName()+"/" + osm.id, version.equals("0.5") ? null : toXml(osm, false));
275 }
276
277 /**
278 * Creates a new changeset on the server to use for subsequent calls.
279 * @param comment the "commit comment" for the new changeset
280 * @throws OsmTransferException signifying a non-200 return code, or connection errors
281 */
282 public void createChangeset(String comment, ProgressMonitor progressMonitor) throws OsmTransferException {
283 progressMonitor.beginTask((tr("Opening changeset...")));
284 try {
285 changeset = new Changeset();
286 Properties sysProp = System.getProperties();
287 Object ua = sysProp.get("http.agent");
288 changeset.put("created_by", (ua == null) ? "JOSM" : ua.toString());
289 changeset.put("comment", comment);
290 createPrimitive(changeset);
291 } finally {
292 progressMonitor.finishTask();
293 }
294 }
295
296 /**
297 * Closes a changeset on the server.
298 *
299 * @throws OsmTransferException if something goes wrong.
300 */
301 public void stopChangeset(ProgressMonitor progressMonitor) throws OsmTransferException {
302 progressMonitor.beginTask(tr("Closing changeset..."));
303 try {
304 initialize();
305 sendRequest("PUT", "changeset" + "/" + changeset.id + "/close", null);
306 changeset = null;
307 } finally {
308 progressMonitor.finishTask();
309 }
310 }
311
312 /**
313 * Uploads a list of changes in "diff" form to the server.
314 *
315 * @param list the list of changed OSM Primitives
316 * @return list of processed primitives
317 * @throws OsmTransferException if something is wrong
318 */
319 public Collection<OsmPrimitive> uploadDiff(final Collection<OsmPrimitive> list, ProgressMonitor progressMonitor) throws OsmTransferException {
320
321 progressMonitor.beginTask("", list.size() * 2);
322 try {
323 if (changeset == null)
324 throw new OsmTransferException(tr("No changeset present for diff upload"));
325
326 initialize();
327 final ArrayList<OsmPrimitive> processed = new ArrayList<OsmPrimitive>();
328
329 CreateOsmChangeVisitor duv = new CreateOsmChangeVisitor(changeset, OsmApi.this);
330
331 progressMonitor.subTask(tr("Preparing..."));
332 for (OsmPrimitive osm : list) {
333 osm.visit(duv);
334 progressMonitor.worked(1);
335 }
336 progressMonitor.indeterminateSubTask(tr("Uploading..."));
337
338 String diff = duv.getDocument();
339 try {
340 String diffresult = sendRequest("POST", "changeset/" + changeset.id + "/upload", diff);
341 DiffResultReader.parseDiffResult(diffresult, list, processed, duv.getNewIdMap(),
342 progressMonitor.createSubTaskMonitor(ProgressMonitor.ALL_TICKS, false));
343 } catch(OsmTransferException e) {
344 throw e;
345 } catch(Exception e) {
346 throw new OsmTransferException(e);
347 }
348
349 return processed;
350 } finally {
351 progressMonitor.finishTask();
352 }
353 }
354
355
356
357 private void sleepAndListen() throws OsmTransferCancelledException {
358 System.out.print(tr("Waiting 10 seconds ... "));
359 for(int i=0; i < 10; i++) {
360 if (cancel || isAuthCancelled())
361 throw new OsmTransferCancelledException();
362 try {
363 Thread.sleep(1000);
364 } catch (InterruptedException ex) {}
365 }
366 System.out.println(tr("OK - trying again."));
367 }
368
369 /**
370 * Replies the max. number of retries in case of 5XX errors on the server
371 *
372 * @return the max number of retries
373 */
374 protected int getMaxRetries() {
375 int ret = Main.pref.getInteger("osm-server.max-num-retries", DEFAULT_MAX_NUM_RETRIES);
376 return Math.max(ret,0);
377 }
378
379 /**
380 * Generic method for sending requests to the OSM API.
381 *
382 * This method will automatically re-try any requests that are answered with a 5xx
383 * error code, or that resulted in a timeout exception from the TCP layer.
384 *
385 * @param requestMethod The http method used when talking with the server.
386 * @param urlSuffix The suffix to add at the server url, not including the version number,
387 * but including any object ids (e.g. "/way/1234/history").
388 * @param requestBody the body of the HTTP request, if any.
389 *
390 * @return the body of the HTTP response, if and only if the response code was "200 OK".
391 * @exception OsmTransferException if the HTTP return code was not 200 (and retries have
392 * been exhausted), or rewrapping a Java exception.
393 */
394 private String sendRequest(String requestMethod, String urlSuffix,
395 String requestBody) throws OsmTransferException {
396
397 StringBuffer responseBody = new StringBuffer();
398
399 int retries = getMaxRetries();
400
401 while(true) { // the retry loop
402 try {
403 URL url = new URL(new URL(getBaseUrl()), urlSuffix, new MyHttpHandler());
404 System.out.print(requestMethod + " " + url + "... ");
405 activeConnection = (HttpURLConnection)url.openConnection();
406 activeConnection.setConnectTimeout(15000);
407 activeConnection.setRequestMethod(requestMethod);
408 addAuth(activeConnection);
409
410 if (requestMethod.equals("PUT") || requestMethod.equals("POST") || requestMethod.equals("DELETE")) {
411 activeConnection.setDoOutput(true);
412 activeConnection.setRequestProperty("Content-type", "text/xml");
413 OutputStream out = activeConnection.getOutputStream();
414
415 // It seems that certain bits of the Ruby API are very unhappy upon
416 // receipt of a PUT/POST message withtout a Content-length header,
417 // even if the request has no payload.
418 // Since Java will not generate a Content-length header unless
419 // we use the output stream, we create an output stream for PUT/POST
420 // even if there is no payload.
421 if (requestBody != null) {
422 BufferedWriter bwr = new BufferedWriter(new OutputStreamWriter(out, "UTF-8"));
423 bwr.write(requestBody);
424 bwr.flush();
425 }
426 out.close();
427 }
428
429 activeConnection.connect();
430 System.out.println(activeConnection.getResponseMessage());
431 int retCode = activeConnection.getResponseCode();
432
433 if (retCode >= 500) {
434 if (retries-- > 0) {
435 sleepAndListen();
436 int maxRetries = getMaxRetries();
437 System.out.println(tr("Starting retry {0} of {1}.", maxRetries - retries,maxRetries));
438 continue;
439 }
440 }
441
442 // populate return fields.
443 responseBody.setLength(0);
444
445 // If the API returned an error code like 403 forbidden, getInputStream
446 // will fail with an IOException.
447 InputStream i = null;
448 try {
449 i = activeConnection.getInputStream();
450 } catch (IOException ioe) {
451 i = activeConnection.getErrorStream();
452 }
453 BufferedReader in = new BufferedReader(new InputStreamReader(i));
454
455 String s;
456 while((s = in.readLine()) != null) {
457 responseBody.append(s);
458 responseBody.append("\n");
459 }
460 String errorHeader = null;
461 // Look for a detailed error message from the server
462 if (activeConnection.getHeaderField("Error") != null) {
463 errorHeader = activeConnection.getHeaderField("Error");
464 System.err.println("Error header: " + errorHeader);
465 } else if (retCode != 200 && responseBody.length()>0) {
466 System.err.println("Error body: " + responseBody);
467 }
468 activeConnection.disconnect();
469
470 if (retCode != 200)
471 throw new OsmApiException(
472 retCode,
473 errorHeader == null? null : errorHeader.trim(),
474 responseBody == null ? null : responseBody.toString().trim()
475 );
476
477 return responseBody.toString();
478 } catch (UnknownHostException e) {
479 throw new OsmTransferException(e);
480 } catch (SocketTimeoutException e) {
481 if (retries-- > 0) {
482 continue;
483 }
484 throw new OsmTransferException(e);
485 } catch (ConnectException e) {
486 if (retries-- > 0) {
487 continue;
488 }
489 throw new OsmTransferException(e);
490 } catch (Exception e) {
491 if (e instanceof OsmTransferException) throw (OsmTransferException) e;
492 throw new OsmTransferException(e);
493 }
494 }
495 }
496
497 /**
498 * returns the API capabilities; null, if the API is not initialized yet
499 *
500 * @return the API capabilities
501 */
502 public Capabilities getCapabilities() {
503 return capabilities;
504 }
505
506}
Note: See TracBrowser for help on using the repository browser.