source: josm/trunk/src/org/openstreetmap/josm/tools/ExceptionUtil.java@ 3872

Last change on this file since 3872 was 3562, checked in by bastiK, 14 years ago

fixed #5417 - Failed to parse date

  • Property svn:eol-style set to native
File size: 20.1 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.tools;
3
4import static org.openstreetmap.josm.tools.I18n.tr;
5
6import java.io.IOException;
7import java.net.HttpURLConnection;
8import java.net.MalformedURLException;
9import java.net.SocketException;
10import java.net.URL;
11import java.net.UnknownHostException;
12import java.text.DateFormat;
13import java.text.ParseException;
14import java.text.SimpleDateFormat;
15import java.util.Date;
16import java.util.Locale;
17import java.util.regex.Matcher;
18import java.util.regex.Pattern;
19
20import org.openstreetmap.josm.Main;
21import org.openstreetmap.josm.gui.preferences.server.OAuthAccessTokenHolder;
22import org.openstreetmap.josm.io.ChangesetClosedException;
23import org.openstreetmap.josm.io.IllegalDataException;
24import org.openstreetmap.josm.io.MissingOAuthAccessTokenException;
25import org.openstreetmap.josm.io.OsmApi;
26import org.openstreetmap.josm.io.OsmApiException;
27import org.openstreetmap.josm.io.OsmApiInitializationException;
28import org.openstreetmap.josm.io.OsmTransferException;
29
30public class ExceptionUtil {
31 private ExceptionUtil() {
32 }
33
34 /**
35 * handles an exception caught during OSM API initialization
36 *
37 * @param e the exception
38 */
39 public static String explainOsmApiInitializationException(OsmApiInitializationException e) {
40 e.printStackTrace();
41 String msg = tr(
42 "<html>Failed to initialize communication with the OSM server {0}.<br>"
43 + "Check the server URL in your preferences and your internet connection.</html>", Main.pref.get(
44 "osm-server.url", "http://api.openstreetmap.org/api"));
45 return msg;
46 }
47
48
49 /**
50 * Creates the error message
51 *
52 * @param e the exception
53 */
54 public static String explainMissingOAuthAccessTokenException(MissingOAuthAccessTokenException e) {
55 e.printStackTrace();
56 String msg = tr(
57 "<html>Failed to authenticate at the OSM server ''{0}''.<br>"
58 + "You are using OAuth to authenticate but currently there is no<br>"
59 + "OAuth Access Token configured.<br>"
60 + "Please open the Preferences Dialog and generate or enter an Access Token."
61 + "</html>",
62 Main.pref.get("osm-server.url", "http://api.openstreetmap.org/api")
63 );
64 return msg;
65 }
66
67 /**
68 * Explains a precondition exception when a child relation could not be deleted because
69 * it is still referred to by an undeleted parent relation.
70 *
71 * @param e the exception
72 * @param childRelation the child relation
73 * @param parentRelation the parent relation
74 * @return
75 */
76 public static String explainDeletedRelationStillInUse(OsmApiException e, long childRelation, long parentRelation) {
77 String msg = tr(
78 "<html><strong>Failed</strong> to delete <strong>relation {0}</strong>."
79 + " It is still referred to by relation {1}.<br>"
80 + "Please load relation {1}, remove the reference to relation {0}, and upload again.</html>",
81 childRelation,parentRelation
82 );
83 return msg;
84 }
85
86 /**
87 * Explains an upload error due to a violated precondition, i.e. a HTTP return code 412
88 *
89 * @param e the exception
90 */
91 public static String explainPreconditionFailed(OsmApiException e) {
92 e.printStackTrace();
93 String msg = e.getErrorHeader();
94 if (msg != null) {
95 String pattern = "Precondition failed: The relation (\\d+) is used in relation (\\d+)\\.";
96 Pattern p = Pattern.compile(pattern);
97 Matcher m = p.matcher(msg);
98 if (m.matches()) {
99 long childRelation = Long.parseLong(m.group(1));
100 long parentRelation = Long.parseLong(m.group(2));
101 return explainDeletedRelationStillInUse(e, childRelation, parentRelation);
102 }
103 }
104 msg = tr(
105 "<html>Uploading to the server <strong>failed</strong> because your current<br>"
106 + "dataset violates a precondition.<br>" + "The error message is:<br>" + "{0}" + "</html>", e
107 .getMessage().replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;"));
108 return msg;
109 }
110
111 public static String explainFailedBasicAuthentication(OsmApiException e) {
112 e.printStackTrace();
113 return tr("<html>"
114 + "Authentication at the OSM server with the username ''{0}'' failed.<br>"
115 + "Please check the username and the password in the JOSM preferences."
116 + "</html>",
117 Main.pref.get("osm-server.username")
118 );
119 }
120
121 public static String explainFailedOAuthAuthentication(OsmApiException e) {
122 e.printStackTrace();
123 return tr("<html>"
124 + "Authentication at the OSM server with the OAuth token ''{0}'' failed.<br>"
125 + "Please launch the preferences dialog and retrieve another OAuth token."
126 + "</html>",
127 OAuthAccessTokenHolder.getInstance().getAccessTokenKey()
128 );
129 }
130
131 public static String explainFailedOAuthAuthorisation(OsmApiException e) {
132 e.printStackTrace();
133 return tr("<html>"
134 + "Authorisation at the OSM server with the OAuth token ''{0}'' failed.<br>"
135 + "The token is not authorised to access the protected resource<br>"
136 + "''{1}''.<br>"
137 + "Please launch the preferences dialog and retrieve another OAuth token."
138 + "</html>",
139 OAuthAccessTokenHolder.getInstance().getAccessTokenKey(),
140 e.getAccessedUrl() == null ? tr("unknown") : e.getAccessedUrl()
141 );
142 }
143
144 /**
145 * Explains an OSM API exception because of a client timeout (HTTP 408).
146 *
147 * @param e the exception
148 * @return the message
149 */
150 public static String explainClientTimeout(OsmApiException e) {
151 e.printStackTrace();
152 return tr("<html>"
153 + "Communication with the OSM server ''{0}'' timed out. Please retry later."
154 + "</html>",
155 OsmApi.getOsmApi().getBaseUrl()
156 );
157 }
158
159 /**
160 * Replies a generic error message for an OSM API exception
161 *
162 * @param e the exception
163 * @return the message
164 */
165 public static String explainGenericOsmApiException(OsmApiException e) {
166 e.printStackTrace();
167 String errMsg = e.getErrorHeader();
168 if (errMsg == null) {
169 errMsg = e.getErrorBody();
170 }
171 if (errMsg == null) {
172 errMsg = tr("no error message available");
173 }
174 return tr("<html>"
175 + "Communication with the OSM server ''{0}''failed. The server replied<br>"
176 + "the following error code and the following error message:<br>"
177 + "<strong>Error code:<strong> {1}<br>"
178 + "<strong>Error message (untranslated)</strong>: {2}"
179 + "</html>",
180 OsmApi.getOsmApi().getBaseUrl(),
181 e.getResponseCode(),
182 errMsg
183 );
184 }
185
186 /**
187 * Explains an error due to a 409 conflict
188 *
189 * @param e the exception
190 */
191 public static String explainConflict(OsmApiException e) {
192 e.printStackTrace();
193 String msg = e.getErrorHeader();
194 if (msg != null) {
195 String pattern = "The changeset (\\d+) was closed at (.*)";
196 Pattern p = Pattern.compile(pattern);
197 Matcher m = p.matcher(msg);
198 if (m.matches()) {
199 long changesetId = Long.parseLong(m.group(1));
200 // Example: "2010-09-07 14:39:41 UTC". Always parsed with US locale, regardless
201 // of the current locale in JOSM
202 DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z", Locale.US);
203 Date closeDate = null;
204 try {
205 closeDate = formatter.parse(m.group(2));
206 } catch(ParseException ex) {
207 System.err.println(tr("Failed to parse date ''{0}'' replied by server.", m.group(2)));
208 ex.printStackTrace();
209 }
210 if (closeDate == null) {
211 msg = tr(
212 "<html>Closing of changeset <strong>{0}</strong> failed <br>because it has already been closed.</html>",
213 changesetId
214 );
215 } else {
216 SimpleDateFormat dateFormat = new SimpleDateFormat();
217 msg = tr(
218 "<html>Closing of changeset <strong>{0}</strong> failed<br>"
219 +" because it has already been closed on {1}.</html>",
220 changesetId,
221 dateFormat.format(closeDate)
222 );
223 }
224 return msg;
225 }
226 msg = tr(
227 "<html>The server reported that it has detected a conflict.<br>" +
228 "Error message (untranslated):<br>{0}</html>",
229 msg
230 );
231 }
232 msg = tr(
233 "<html>The server reported that it has detected a conflict.</html>"
234 );
235 return msg;
236 }
237
238 /**
239 * Explains an exception thrown during upload because the changeset which data is
240 * uploaded to is already closed.
241 *
242 * @param e the exception
243 */
244 public static String explainChangesetClosedException(ChangesetClosedException e) {
245 String msg;
246 SimpleDateFormat dateFormat = new SimpleDateFormat();
247 msg = tr(
248 "<html>Failed to upload to changeset <strong>{0}</strong><br>"
249 +"because it has already been closed on {1}.</html>",
250 e.getChangesetId(),
251 e.getClosedOn() == null ? "?" : dateFormat.format(e.getClosedOn())
252 );
253 e.printStackTrace();
254 return msg;
255 }
256
257 /**
258 * Explains an exception with a generic message dialog
259 *
260 * @param e the exception
261 */
262 public static String explainGeneric(Exception e) {
263 String msg = e.getMessage();
264 if (msg == null || msg.trim().equals("")) {
265 msg = e.toString();
266 }
267 e.printStackTrace();
268 return msg;
269 }
270
271 /**
272 * Explains a {@see SecurityException} which has caused an {@see OsmTransferException}.
273 * This is most likely happening when user tries to access the OSM API from within an
274 * applet which wasn't loaded from the API server.
275 *
276 * @param e the exception
277 */
278
279 public static String explainSecurityException(OsmTransferException e) {
280 String apiUrl = e.getUrl();
281 String host = tr("unknown");
282 try {
283 host = new URL(apiUrl).getHost();
284 } catch (MalformedURLException ex) {
285 // shouldn't happen
286 }
287
288 String message = tr("<html>Failed to open a connection to the remote server<br>" + "''{0}''<br>"
289 + "for security reasons. This is most likely because you are running<br>"
290 + "in an applet and because you did not load your applet from ''{1}''.</html>", apiUrl, host);
291 return message;
292 }
293
294 /**
295 * Explains a {@see SocketException} which has caused an {@see OsmTransferException}.
296 * This is most likely because there's not connection to the Internet or because
297 * the remote server is not reachable.
298 *
299 * @param e the exception
300 */
301
302 public static String explainNestedSocketException(OsmTransferException e) {
303 String apiUrl = e.getUrl();
304 String message = tr("<html>Failed to open a connection to the remote server<br>" + "''{0}''.<br>"
305 + "Please check your internet connection.</html>", apiUrl);
306 e.printStackTrace();
307 return message;
308 }
309
310 /**
311 * Explains a {@see IOException} which has caused an {@see OsmTransferException}.
312 * This is most likely happening when the communication with the remote server is
313 * interrupted for any reason.
314 *
315 * @param e the exception
316 */
317
318 public static String explainNestedIOException(OsmTransferException e) {
319 IOException ioe = getNestedException(e, IOException.class);
320 String apiUrl = e.getUrl();
321 String message = tr("<html>Failed to upload data to or download data from<br>" + "''{0}''<br>"
322 + "due to a problem with transferring data.<br>" + "Details(untranslated): {1}</html>", apiUrl, ioe
323 .getMessage());
324 e.printStackTrace();
325 return message;
326 }
327
328 /**
329 * Explains a {@see IllegalDataException} which has caused an {@see OsmTransferException}.
330 * This is most likely happening when JOSM tries to load data in in an unsupported format.
331 *
332 * @param e the exception
333 */
334 public static String explainNestedIllegalDataException(OsmTransferException e) {
335 IllegalDataException ide = getNestedException(e, IllegalDataException.class);
336 String message = tr("<html>Failed to download data. "
337 + "Its format is either unsupported, ill-formed, and/or inconsistent.<br>"
338 + "<br>Details (untranslated): {0}</html>", ide.getMessage());
339 e.printStackTrace();
340 return message;
341 }
342
343 /**
344 * Explains a {@see OsmApiException} which was thrown because of an internal server
345 * error in the OSM API server..
346 *
347 * @param e the exception
348 */
349
350 public static String explainInternalServerError(OsmTransferException e) {
351 String apiUrl = e.getUrl();
352 String message = tr("<html>The OSM server<br>" + "''{0}''<br>" + "reported an internal server error.<br>"
353 + "This is most likely a temporary problem. Please try again later.</html>", apiUrl);
354 e.printStackTrace();
355 return message;
356 }
357
358 /**
359 * Explains a {@see OsmApiException} which was thrown because of a bad
360 * request
361 *
362 * @param e the exception
363 */
364 public static String explainBadRequest(OsmApiException e) {
365 String apiUrl = OsmApi.getOsmApi().getBaseUrl();
366 String message = tr("The OSM server ''{0}'' reported a bad request.<br>", apiUrl);
367 if (e.getErrorHeader() != null &&
368 (e.getErrorHeader().startsWith("The maximum bbox") ||
369 e.getErrorHeader().startsWith("You requested too many nodes"))) {
370 message += "<br>"
371 + tr("The area you tried to download is too big or your request was too large."
372 + "<br>Either request a smaller area or use an export file provided by the OSM community.");
373 } else if (e.getErrorHeader() != null) {
374 message += tr("<br>Error message(untranslated): {0}", e.getErrorHeader());
375 }
376 message = "<html>" + message + "</html>";
377 e.printStackTrace();
378 return message;
379 }
380
381 /**
382 * Explains a {@see OsmApiException} which was thrown because a resource wasn't found.
383 *
384 * @param e the exception
385 */
386 public static String explainNotFound(OsmApiException e) {
387 String apiUrl = OsmApi.getOsmApi().getBaseUrl();
388 String message = tr("The OSM server ''{0}'' does not know about an object<br>"
389 + "you tried to read, update, or delete. Either the respective object<br>"
390 + "does not exist on the server or you are using an invalid URL to access<br>"
391 + "it. Please carefully check the server''s address ''{0}'' for typos."
392 , apiUrl);
393 message = "<html>" + message + "</html>";
394 e.printStackTrace();
395 return message;
396 }
397
398 /**
399 * Explains a {@see UnknownHostException} which has caused an {@see OsmTransferException}.
400 * This is most likely happening when there is an error in the API URL or when
401 * local DNS services are not working.
402 *
403 * @param e the exception
404 */
405
406 public static String explainNestedUnknownHostException(OsmTransferException e) {
407 String apiUrl = e.getUrl();
408 String host = tr("unknown");
409 try {
410 host = new URL(apiUrl).getHost();
411 } catch (MalformedURLException ex) {
412 // shouldn't happen
413 }
414
415 String message = tr("<html>Failed to open a connection to the remote server<br>" + "''{0}''.<br>"
416 + "Host name ''{1}'' could not be resolved. <br>"
417 + "Please check the API URL in your preferences and your internet connection.</html>", apiUrl, host);
418 e.printStackTrace();
419 return message;
420 }
421
422 /**
423 * Replies the first nested exception of type <code>nestedClass</code> (including
424 * the root exception <code>e</code>) or null, if no such exception is found.
425 *
426 * @param <T>
427 * @param e the root exception
428 * @param nestedClass the type of the nested exception
429 * @return the first nested exception of type <code>nestedClass</code> (including
430 * the root exception <code>e</code>) or null, if no such exception is found.
431 */
432 protected static <T> T getNestedException(Exception e, Class<T> nestedClass) {
433 Throwable t = e;
434 while (t != null && !(nestedClass.isInstance(t))) {
435 t = t.getCause();
436 }
437 if (t == null)
438 return null;
439 else if (nestedClass.isInstance(t))
440 return nestedClass.cast(t);
441 return null;
442 }
443
444 /**
445 * Explains an {@see OsmTransferException} to the user.
446 *
447 * @param e the {@see OsmTransferException}
448 */
449 public static String explainOsmTransferException(OsmTransferException e) {
450 if (getNestedException(e, SecurityException.class) != null)
451 return explainSecurityException(e);
452 if (getNestedException(e, SocketException.class) != null)
453 return explainNestedSocketException(e);
454 if (getNestedException(e, UnknownHostException.class) != null)
455 return explainNestedUnknownHostException(e);
456 if (getNestedException(e, IOException.class) != null)
457 return explainNestedIOException(e);
458 if (e instanceof OsmApiInitializationException)
459 return explainOsmApiInitializationException((OsmApiInitializationException) e);
460
461 if (e instanceof ChangesetClosedException)
462 return explainChangesetClosedException((ChangesetClosedException)e);
463
464 if (e instanceof OsmApiException) {
465 OsmApiException oae = (OsmApiException) e;
466 if (oae.getResponseCode() == HttpURLConnection.HTTP_PRECON_FAILED)
467 return explainPreconditionFailed(oae);
468 if (oae.getResponseCode() == HttpURLConnection.HTTP_GONE)
469 return explainGoneForUnknownPrimitive(oae);
470 if (oae.getResponseCode() == HttpURLConnection.HTTP_INTERNAL_ERROR)
471 return explainInternalServerError(oae);
472 if (oae.getResponseCode() == HttpURLConnection.HTTP_BAD_REQUEST)
473 return explainBadRequest(oae);
474 }
475 return explainGeneric(e);
476 }
477
478 /**
479 * explains the case of an error due to a delete request on an already deleted
480 * {@see OsmPrimitive}, i.e. a HTTP response code 410, where we don't know which
481 * {@see OsmPrimitive} is causing the error.
482 *
483 * @param e the exception
484 */
485 public static String explainGoneForUnknownPrimitive(OsmApiException e) {
486 String msg = tr(
487 "<html>The server reports that an object is deleted.<br>"
488 + "<strong>Uploading failed</strong> if you tried to update or delete this object.<br> "
489 + "<strong>Downloading failed</strong> if you tried to download this object.<br>"
490 + "<br>"
491 + "The error message is:<br>" + "{0}"
492 + "</html>", e.getMessage().replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;"));
493 return msg;
494
495 }
496
497 /**
498 * Explains an {@see Exception} to the user.
499 *
500 * @param e the {@see Exception}
501 */
502 public static String explainException(Exception e) {
503 String msg = "";
504 if (e instanceof OsmTransferException) {
505 msg = explainOsmTransferException((OsmTransferException) e);
506 } else {
507 msg = explainGeneric(e);
508 }
509 e.printStackTrace();
510 return msg;
511 }
512}
Note: See TracBrowser for help on using the repository browser.