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

Last change on this file since 10658 was 10626, checked in by Don-vip, 8 years ago

simplify handling of ignored/traced exceptions

  • Property svn:eol-style set to native
File size: 32.9 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.tools;
3
4import static org.openstreetmap.josm.tools.I18n.tr;
5import static org.openstreetmap.josm.tools.I18n.trn;
6
7import java.io.IOException;
8import java.net.HttpURLConnection;
9import java.net.MalformedURLException;
10import java.net.SocketException;
11import java.net.URL;
12import java.net.UnknownHostException;
13import java.text.DateFormat;
14import java.text.ParseException;
15import java.util.Collection;
16import java.util.Date;
17import java.util.TreeSet;
18import java.util.regex.Matcher;
19import java.util.regex.Pattern;
20
21import org.openstreetmap.josm.Main;
22import org.openstreetmap.josm.data.osm.Node;
23import org.openstreetmap.josm.data.osm.OsmPrimitive;
24import org.openstreetmap.josm.data.osm.Relation;
25import org.openstreetmap.josm.data.osm.Way;
26import org.openstreetmap.josm.gui.preferences.server.OAuthAccessTokenHolder;
27import org.openstreetmap.josm.io.ChangesetClosedException;
28import org.openstreetmap.josm.io.IllegalDataException;
29import org.openstreetmap.josm.io.MissingOAuthAccessTokenException;
30import org.openstreetmap.josm.io.OfflineAccessException;
31import org.openstreetmap.josm.io.OsmApi;
32import org.openstreetmap.josm.io.OsmApiException;
33import org.openstreetmap.josm.io.OsmApiInitializationException;
34import org.openstreetmap.josm.io.OsmTransferException;
35import org.openstreetmap.josm.io.auth.CredentialsManager;
36import org.openstreetmap.josm.tools.Utils.Function;
37import org.openstreetmap.josm.tools.date.DateUtils;
38
39/**
40 * Utilities for exception handling.
41 * @since 2097
42 */
43public final class ExceptionUtil {
44
45 private ExceptionUtil() {
46 // Hide default constructor for utils classes
47 }
48
49 /**
50 * Explains an exception caught during OSM API initialization.
51 *
52 * @param e the exception
53 * @return The HTML formatted error message to display
54 */
55 public static String explainOsmApiInitializationException(OsmApiInitializationException e) {
56 Main.error(e);
57 return tr(
58 "<html>Failed to initialize communication with the OSM server {0}.<br>"
59 + "Check the server URL in your preferences and your internet connection.",
60 OsmApi.getOsmApi().getServerUrl())+"</html>";
61 }
62
63 /**
64 * Explains a {@link OsmApiException} which was thrown because accessing a protected
65 * resource was forbidden.
66 *
67 * @param e the exception
68 * @return The HTML formatted error message to display
69 */
70 public static String explainMissingOAuthAccessTokenException(MissingOAuthAccessTokenException e) {
71 Main.error(e);
72 return tr(
73 "<html>Failed to authenticate at the OSM server ''{0}''.<br>"
74 + "You are using OAuth to authenticate but currently there is no<br>"
75 + "OAuth Access Token configured.<br>"
76 + "Please open the Preferences Dialog and generate or enter an Access Token."
77 + "</html>",
78 OsmApi.getOsmApi().getServerUrl()
79 );
80 }
81
82 public static Pair<OsmPrimitive, Collection<OsmPrimitive>> parsePreconditionFailed(String msg) {
83 if (msg == null)
84 return null;
85 final String ids = "(\\d+(?:,\\d+)*)";
86 final Collection<OsmPrimitive> refs = new TreeSet<>(); // error message can contain several times the same way
87 Matcher m;
88 m = Pattern.compile(".*Node (\\d+) is still used by relations? " + ids + ".*").matcher(msg);
89 if (m.matches()) {
90 OsmPrimitive n = new Node(Long.parseLong(m.group(1)));
91 for (String s : m.group(2).split(",")) {
92 refs.add(new Relation(Long.parseLong(s)));
93 }
94 return Pair.create(n, refs);
95 }
96 m = Pattern.compile(".*Node (\\d+) is still used by ways? " + ids + ".*").matcher(msg);
97 if (m.matches()) {
98 OsmPrimitive n = new Node(Long.parseLong(m.group(1)));
99 for (String s : m.group(2).split(",")) {
100 refs.add(new Way(Long.parseLong(s)));
101 }
102 return Pair.create(n, refs);
103 }
104 m = Pattern.compile(".*The relation (\\d+) is used in relations? " + ids + ".*").matcher(msg);
105 if (m.matches()) {
106 OsmPrimitive n = new Relation(Long.parseLong(m.group(1)));
107 for (String s : m.group(2).split(",")) {
108 refs.add(new Relation(Long.parseLong(s)));
109 }
110 return Pair.create(n, refs);
111 }
112 m = Pattern.compile(".*Way (\\d+) is still used by relations? " + ids + ".*").matcher(msg);
113 if (m.matches()) {
114 OsmPrimitive n = new Way(Long.parseLong(m.group(1)));
115 for (String s : m.group(2).split(",")) {
116 refs.add(new Relation(Long.parseLong(s)));
117 }
118 return Pair.create(n, refs);
119 }
120 m = Pattern.compile(".*Way (\\d+) requires the nodes with id in " + ids + ".*").matcher(msg);
121 // ... ", which either do not exist, or are not visible"
122 if (m.matches()) {
123 OsmPrimitive n = new Way(Long.parseLong(m.group(1)));
124 for (String s : m.group(2).split(",")) {
125 refs.add(new Node(Long.parseLong(s)));
126 }
127 return Pair.create(n, refs);
128 }
129 return null;
130 }
131
132 /**
133 * Explains an upload error due to a violated precondition, i.e. a HTTP return code 412
134 *
135 * @param e the exception
136 * @return The HTML formatted error message to display
137 */
138 public static String explainPreconditionFailed(OsmApiException e) {
139 Main.error(e);
140 Pair<OsmPrimitive, Collection<OsmPrimitive>> conflict = parsePreconditionFailed(e.getErrorHeader());
141 if (conflict != null) {
142 OsmPrimitive firstRefs = conflict.b.iterator().next();
143 String objId = Long.toString(conflict.a.getId());
144 Collection<Long> refIds = Utils.transform(conflict.b, (Function<OsmPrimitive, Long>) x -> x.getId());
145 String refIdsString = refIds.size() == 1 ? refIds.iterator().next().toString() : refIds.toString();
146 if (conflict.a instanceof Node) {
147 if (firstRefs instanceof Node) {
148 return "<html>" + trn(
149 "<strong>Failed</strong> to delete <strong>node {0}</strong>."
150 + " It is still referred to by node {1}.<br>"
151 + "Please load the node, remove the reference to the node, and upload again.",
152 "<strong>Failed</strong> to delete <strong>node {0}</strong>."
153 + " It is still referred to by nodes {1}.<br>"
154 + "Please load the nodes, remove the reference to the node, and upload again.",
155 conflict.b.size(), objId, refIdsString) + "</html>";
156 } else if (firstRefs instanceof Way) {
157 return "<html>" + trn(
158 "<strong>Failed</strong> to delete <strong>node {0}</strong>."
159 + " It is still referred to by way {1}.<br>"
160 + "Please load the way, remove the reference to the node, and upload again.",
161 "<strong>Failed</strong> to delete <strong>node {0}</strong>."
162 + " It is still referred to by ways {1}.<br>"
163 + "Please load the ways, remove the reference to the node, and upload again.",
164 conflict.b.size(), objId, refIdsString) + "</html>";
165 } else if (firstRefs instanceof Relation) {
166 return "<html>" + trn(
167 "<strong>Failed</strong> to delete <strong>node {0}</strong>."
168 + " It is still referred to by relation {1}.<br>"
169 + "Please load the relation, remove the reference to the node, and upload again.",
170 "<strong>Failed</strong> to delete <strong>node {0}</strong>."
171 + " It is still referred to by relations {1}.<br>"
172 + "Please load the relations, remove the reference to the node, and upload again.",
173 conflict.b.size(), objId, refIdsString) + "</html>";
174 } else {
175 throw new IllegalStateException();
176 }
177 } else if (conflict.a instanceof Way) {
178 if (firstRefs instanceof Node) {
179 return "<html>" + trn(
180 "<strong>Failed</strong> to delete <strong>way {0}</strong>."
181 + " It is still referred to by node {1}.<br>"
182 + "Please load the node, remove the reference to the way, and upload again.",
183 "<strong>Failed</strong> to delete <strong>way {0}</strong>."
184 + " It is still referred to by nodes {1}.<br>"
185 + "Please load the nodes, remove the reference to the way, and upload again.",
186 conflict.b.size(), objId, refIdsString) + "</html>";
187 } else if (firstRefs instanceof Way) {
188 return "<html>" + trn(
189 "<strong>Failed</strong> to delete <strong>way {0}</strong>."
190 + " It is still referred to by way {1}.<br>"
191 + "Please load the way, remove the reference to the way, and upload again.",
192 "<strong>Failed</strong> to delete <strong>way {0}</strong>."
193 + " It is still referred to by ways {1}.<br>"
194 + "Please load the ways, remove the reference to the way, and upload again.",
195 conflict.b.size(), objId, refIdsString) + "</html>";
196 } else if (firstRefs instanceof Relation) {
197 return "<html>" + trn(
198 "<strong>Failed</strong> to delete <strong>way {0}</strong>."
199 + " It is still referred to by relation {1}.<br>"
200 + "Please load the relation, remove the reference to the way, and upload again.",
201 "<strong>Failed</strong> to delete <strong>way {0}</strong>."
202 + " It is still referred to by relations {1}.<br>"
203 + "Please load the relations, remove the reference to the way, and upload again.",
204 conflict.b.size(), objId, refIdsString) + "</html>";
205 } else {
206 throw new IllegalStateException();
207 }
208 } else if (conflict.a instanceof Relation) {
209 if (firstRefs instanceof Node) {
210 return "<html>" + trn(
211 "<strong>Failed</strong> to delete <strong>relation {0}</strong>."
212 + " It is still referred to by node {1}.<br>"
213 + "Please load the node, remove the reference to the relation, and upload again.",
214 "<strong>Failed</strong> to delete <strong>relation {0}</strong>."
215 + " It is still referred to by nodes {1}.<br>"
216 + "Please load the nodes, remove the reference to the relation, and upload again.",
217 conflict.b.size(), objId, refIdsString) + "</html>";
218 } else if (firstRefs instanceof Way) {
219 return "<html>" + trn(
220 "<strong>Failed</strong> to delete <strong>relation {0}</strong>."
221 + " It is still referred to by way {1}.<br>"
222 + "Please load the way, remove the reference to the relation, and upload again.",
223 "<strong>Failed</strong> to delete <strong>relation {0}</strong>."
224 + " It is still referred to by ways {1}.<br>"
225 + "Please load the ways, remove the reference to the relation, and upload again.",
226 conflict.b.size(), objId, refIdsString) + "</html>";
227 } else if (firstRefs instanceof Relation) {
228 return "<html>" + trn(
229 "<strong>Failed</strong> to delete <strong>relation {0}</strong>."
230 + " It is still referred to by relation {1}.<br>"
231 + "Please load the relation, remove the reference to the relation, and upload again.",
232 "<strong>Failed</strong> to delete <strong>relation {0}</strong>."
233 + " It is still referred to by relations {1}.<br>"
234 + "Please load the relations, remove the reference to the relation, and upload again.",
235 conflict.b.size(), objId, refIdsString) + "</html>";
236 } else {
237 throw new IllegalStateException();
238 }
239 } else {
240 throw new IllegalStateException();
241 }
242 } else {
243 return tr(
244 "<html>Uploading to the server <strong>failed</strong> because your current<br>"
245 + "dataset violates a precondition.<br>" + "The error message is:<br>" + "{0}" + "</html>",
246 Utils.escapeReservedCharactersHTML(e.getMessage()));
247 }
248 }
249
250 /**
251 * Explains a {@link OsmApiException} which was thrown because the authentication at
252 * the OSM server failed, with basic authentication.
253 *
254 * @param e the exception
255 * @return The HTML formatted error message to display
256 */
257 public static String explainFailedBasicAuthentication(OsmApiException e) {
258 Main.error(e);
259 return tr("<html>"
260 + "Authentication at the OSM server with the username ''{0}'' failed.<br>"
261 + "Please check the username and the password in the JOSM preferences."
262 + "</html>",
263 CredentialsManager.getInstance().getUsername()
264 );
265 }
266
267 /**
268 * Explains a {@link OsmApiException} which was thrown because the authentication at
269 * the OSM server failed, with OAuth authentication.
270 *
271 * @param e the exception
272 * @return The HTML formatted error message to display
273 */
274 public static String explainFailedOAuthAuthentication(OsmApiException e) {
275 Main.error(e);
276 return tr("<html>"
277 + "Authentication at the OSM server with the OAuth token ''{0}'' failed.<br>"
278 + "Please launch the preferences dialog and retrieve another OAuth token."
279 + "</html>",
280 OAuthAccessTokenHolder.getInstance().getAccessTokenKey()
281 );
282 }
283
284 /**
285 * Explains a {@link OsmApiException} which was thrown because accessing a protected
286 * resource was forbidden (HTTP 403), without OAuth authentication.
287 *
288 * @param e the exception
289 * @return The HTML formatted error message to display
290 */
291 public static String explainFailedAuthorisation(OsmApiException e) {
292 Main.error(e);
293 String header = e.getErrorHeader();
294 String body = e.getErrorBody();
295 String msg;
296 if (header != null) {
297 if (body != null && !header.equals(body)) {
298 msg = header + " (" + body + ')';
299 } else {
300 msg = header;
301 }
302 } else {
303 msg = body;
304 }
305
306 if (msg != null && !msg.isEmpty()) {
307 return tr("<html>"
308 + "Authorisation at the OSM server failed.<br>"
309 + "The server reported the following error:<br>"
310 + "''{0}''"
311 + "</html>",
312 msg
313 );
314 } else {
315 return tr("<html>"
316 + "Authorisation at the OSM server failed.<br>"
317 + "</html>"
318 );
319 }
320 }
321
322 /**
323 * Explains a {@link OsmApiException} which was thrown because accessing a protected
324 * resource was forbidden (HTTP 403), with OAuth authentication.
325 *
326 * @param e the exception
327 * @return The HTML formatted error message to display
328 */
329 public static String explainFailedOAuthAuthorisation(OsmApiException e) {
330 Main.error(e);
331 return tr("<html>"
332 + "Authorisation at the OSM server with the OAuth token ''{0}'' failed.<br>"
333 + "The token is not authorised to access the protected resource<br>"
334 + "''{1}''.<br>"
335 + "Please launch the preferences dialog and retrieve another OAuth token."
336 + "</html>",
337 OAuthAccessTokenHolder.getInstance().getAccessTokenKey(),
338 e.getAccessedUrl() == null ? tr("unknown") : e.getAccessedUrl()
339 );
340 }
341
342 /**
343 * Explains an OSM API exception because of a client timeout (HTTP 408).
344 *
345 * @param e the exception
346 * @return The HTML formatted error message to display
347 */
348 public static String explainClientTimeout(OsmApiException e) {
349 Main.error(e);
350 return tr("<html>"
351 + "Communication with the OSM server ''{0}'' timed out. Please retry later."
352 + "</html>",
353 getUrlFromException(e)
354 );
355 }
356
357 /**
358 * Replies a generic error message for an OSM API exception
359 *
360 * @param e the exception
361 * @return The HTML formatted error message to display
362 */
363 public static String explainGenericOsmApiException(OsmApiException e) {
364 Main.error(e);
365 String errMsg = e.getErrorHeader();
366 if (errMsg == null) {
367 errMsg = e.getErrorBody();
368 }
369 if (errMsg == null) {
370 errMsg = tr("no error message available");
371 }
372 return tr("<html>"
373 + "Communication with the OSM server ''{0}''failed. The server replied<br>"
374 + "the following error code and the following error message:<br>"
375 + "<strong>Error code:<strong> {1}<br>"
376 + "<strong>Error message (untranslated)</strong>: {2}"
377 + "</html>",
378 getUrlFromException(e),
379 e.getResponseCode(),
380 errMsg
381 );
382 }
383
384 /**
385 * Explains an error due to a 409 conflict
386 *
387 * @param e the exception
388 * @return The HTML formatted error message to display
389 */
390 public static String explainConflict(OsmApiException e) {
391 Main.error(e);
392 String msg = e.getErrorHeader();
393 if (msg != null) {
394 Matcher m = Pattern.compile("The changeset (\\d+) was closed at (.*)").matcher(msg);
395 if (m.matches()) {
396 long changesetId = Long.parseLong(m.group(1));
397 Date closeDate = null;
398 try {
399 closeDate = DateUtils.newOsmApiDateTimeFormat().parse(m.group(2));
400 } catch (ParseException ex) {
401 Main.error(tr("Failed to parse date ''{0}'' replied by server.", m.group(2)));
402 Main.error(ex);
403 }
404 if (closeDate == null) {
405 msg = tr(
406 "<html>Closing of changeset <strong>{0}</strong> failed <br>because it has already been closed.",
407 changesetId
408 );
409 } else {
410 msg = tr(
411 "<html>Closing of changeset <strong>{0}</strong> failed<br>"
412 +" because it has already been closed on {1}.",
413 changesetId,
414 DateUtils.formatDateTime(closeDate, DateFormat.DEFAULT, DateFormat.DEFAULT)
415 );
416 }
417 return msg;
418 }
419 msg = tr(
420 "<html>The server reported that it has detected a conflict.<br>" +
421 "Error message (untranslated):<br>{0}</html>",
422 msg
423 );
424 } else {
425 msg = tr(
426 "<html>The server reported that it has detected a conflict.");
427 }
428 return msg.endsWith("</html>") ? msg : (msg + "</html>");
429 }
430
431 /**
432 * Explains an exception thrown during upload because the changeset which data is
433 * uploaded to is already closed.
434 *
435 * @param e the exception
436 * @return The HTML formatted error message to display
437 */
438 public static String explainChangesetClosedException(ChangesetClosedException e) {
439 Main.error(e);
440 return tr(
441 "<html>Failed to upload to changeset <strong>{0}</strong><br>"
442 +"because it has already been closed on {1}.",
443 e.getChangesetId(),
444 e.getClosedOn() == null ? "?" : DateUtils.formatDateTime(e.getClosedOn(), DateFormat.DEFAULT, DateFormat.DEFAULT)
445 );
446 }
447
448 /**
449 * Explains an exception with a generic message dialog
450 *
451 * @param e the exception
452 * @return The HTML formatted error message to display
453 */
454 public static String explainGeneric(Exception e) {
455 String msg = e.getMessage();
456 if (msg == null || msg.trim().isEmpty()) {
457 msg = e.toString();
458 }
459 Main.error(e);
460 return Utils.escapeReservedCharactersHTML(msg);
461 }
462
463 /**
464 * Explains a {@link SecurityException} which has caused an {@link OsmTransferException}.
465 * This is most likely happening when user tries to access the OSM API from within an
466 * applet which wasn't loaded from the API server.
467 *
468 * @param e the exception
469 * @return The HTML formatted error message to display
470 */
471 public static String explainSecurityException(OsmTransferException e) {
472 String apiUrl = e.getUrl();
473 String host = tr("unknown");
474 try {
475 host = new URL(apiUrl).getHost();
476 } catch (MalformedURLException ex) {
477 // shouldn't happen
478 Main.trace(ex);
479 }
480
481 return tr("<html>Failed to open a connection to the remote server<br>" + "''{0}''<br>"
482 + "for security reasons. This is most likely because you are running<br>"
483 + "in an applet and because you did not load your applet from ''{1}''.", apiUrl, host)+"</html>";
484 }
485
486 /**
487 * Explains a {@link SocketException} which has caused an {@link OsmTransferException}.
488 * This is most likely because there's not connection to the Internet or because
489 * the remote server is not reachable.
490 *
491 * @param e the exception
492 * @return The HTML formatted error message to display
493 */
494 public static String explainNestedSocketException(OsmTransferException e) {
495 Main.error(e);
496 return tr("<html>Failed to open a connection to the remote server<br>" + "''{0}''.<br>"
497 + "Please check your internet connection.", e.getUrl())+"</html>";
498 }
499
500 /**
501 * Explains a {@link IOException} which has caused an {@link OsmTransferException}.
502 * This is most likely happening when the communication with the remote server is
503 * interrupted for any reason.
504 *
505 * @param e the exception
506 * @return The HTML formatted error message to display
507 */
508 public static String explainNestedIOException(OsmTransferException e) {
509 IOException ioe = getNestedException(e, IOException.class);
510 Main.error(e);
511 return tr("<html>Failed to upload data to or download data from<br>" + "''{0}''<br>"
512 + "due to a problem with transferring data.<br>"
513 + "Details (untranslated): {1}</html>", e.getUrl(),
514 ioe != null ? ioe.getMessage() : "null");
515 }
516
517 /**
518 * Explains a {@link IllegalDataException} which has caused an {@link OsmTransferException}.
519 * This is most likely happening when JOSM tries to load data in an unsupported format.
520 *
521 * @param e the exception
522 * @return The HTML formatted error message to display
523 */
524 public static String explainNestedIllegalDataException(OsmTransferException e) {
525 IllegalDataException ide = getNestedException(e, IllegalDataException.class);
526 Main.error(e);
527 return tr("<html>Failed to download data. "
528 + "Its format is either unsupported, ill-formed, and/or inconsistent.<br>"
529 + "<br>Details (untranslated): {0}</html>", ide != null ? ide.getMessage() : "null");
530 }
531
532 /**
533 * Explains a {@link OfflineAccessException} which has caused an {@link OsmTransferException}.
534 * This is most likely happening when JOSM tries to access OSM API or JOSM website while in offline mode.
535 *
536 * @param e the exception
537 * @return The HTML formatted error message to display
538 * @since 7434
539 */
540 public static String explainOfflineAccessException(OsmTransferException e) {
541 OfflineAccessException oae = getNestedException(e, OfflineAccessException.class);
542 Main.error(e);
543 return tr("<html>Failed to download data.<br>"
544 + "<br>Details: {0}</html>", oae != null ? oae.getMessage() : "null");
545 }
546
547 /**
548 * Explains a {@link OsmApiException} which was thrown because of an internal server
549 * error in the OSM API server.
550 *
551 * @param e the exception
552 * @return The HTML formatted error message to display
553 */
554 public static String explainInternalServerError(OsmTransferException e) {
555 Main.error(e);
556 return tr("<html>The OSM server<br>" + "''{0}''<br>" + "reported an internal server error.<br>"
557 + "This is most likely a temporary problem. Please try again later.", e.getUrl())+"</html>";
558 }
559
560 /**
561 * Explains a {@link OsmApiException} which was thrown because of a bad request.
562 *
563 * @param e the exception
564 * @return The HTML formatted error message to display
565 */
566 public static String explainBadRequest(OsmApiException e) {
567 String message = tr("The OSM server ''{0}'' reported a bad request.<br>", getUrlFromException(e));
568 String errorHeader = e.getErrorHeader();
569 if (errorHeader != null && (errorHeader.startsWith("The maximum bbox") ||
570 errorHeader.startsWith("You requested too many nodes"))) {
571 message += "<br>"
572 + tr("The area you tried to download is too big or your request was too large."
573 + "<br>Either request a smaller area or use an export file provided by the OSM community.");
574 } else if (errorHeader != null) {
575 message += tr("<br>Error message(untranslated): {0}", errorHeader);
576 }
577 Main.error(e);
578 return "<html>" + message + "</html>";
579 }
580
581 /**
582 * Explains a {@link OsmApiException} which was thrown because of
583 * bandwidth limit exceeded (HTTP error 509)
584 *
585 * @param e the exception
586 * @return The HTML formatted error message to display
587 */
588 public static String explainBandwidthLimitExceeded(OsmApiException e) {
589 Main.error(e);
590 // TODO: Write a proper error message
591 return explainGenericOsmApiException(e);
592 }
593
594 /**
595 * Explains a {@link OsmApiException} which was thrown because a resource wasn't found.
596 *
597 * @param e the exception
598 * @return The HTML formatted error message to display
599 */
600 public static String explainNotFound(OsmApiException e) {
601 String message = tr("The OSM server ''{0}'' does not know about an object<br>"
602 + "you tried to read, update, or delete. Either the respective object<br>"
603 + "does not exist on the server or you are using an invalid URL to access<br>"
604 + "it. Please carefully check the server''s address ''{0}'' for typos.",
605 getUrlFromException(e));
606 Main.error(e);
607 return "<html>" + message + "</html>";
608 }
609
610 /**
611 * Explains a {@link UnknownHostException} which has caused an {@link OsmTransferException}.
612 * This is most likely happening when there is an error in the API URL or when
613 * local DNS services are not working.
614 *
615 * @param e the exception
616 * @return The HTML formatted error message to display
617 */
618 public static String explainNestedUnknownHostException(OsmTransferException e) {
619 String apiUrl = e.getUrl();
620 String host = tr("unknown");
621 try {
622 host = new URL(apiUrl).getHost();
623 } catch (MalformedURLException ex) {
624 // shouldn't happen
625 Main.trace(e);
626 }
627
628 Main.error(e);
629 return tr("<html>Failed to open a connection to the remote server<br>" + "''{0}''.<br>"
630 + "Host name ''{1}'' could not be resolved. <br>"
631 + "Please check the API URL in your preferences and your internet connection.", apiUrl, host)+"</html>";
632 }
633
634 /**
635 * Replies the first nested exception of type <code>nestedClass</code> (including
636 * the root exception <code>e</code>) or null, if no such exception is found.
637 *
638 * @param <T> nested exception type
639 * @param e the root exception
640 * @param nestedClass the type of the nested exception
641 * @return the first nested exception of type <code>nestedClass</code> (including
642 * the root exception <code>e</code>) or null, if no such exception is found.
643 * @since 8470
644 */
645 public static <T> T getNestedException(Exception e, Class<T> nestedClass) {
646 Throwable t = e;
647 while (t != null && !(nestedClass.isInstance(t))) {
648 t = t.getCause();
649 }
650 if (t == null)
651 return null;
652 else if (nestedClass.isInstance(t))
653 return nestedClass.cast(t);
654 return null;
655 }
656
657 /**
658 * Explains an {@link OsmTransferException} to the user.
659 *
660 * @param e the {@link OsmTransferException}
661 * @return The HTML formatted error message to display
662 */
663 public static String explainOsmTransferException(OsmTransferException e) {
664 if (getNestedException(e, SecurityException.class) != null)
665 return explainSecurityException(e);
666 if (getNestedException(e, SocketException.class) != null)
667 return explainNestedSocketException(e);
668 if (getNestedException(e, UnknownHostException.class) != null)
669 return explainNestedUnknownHostException(e);
670 if (getNestedException(e, IOException.class) != null)
671 return explainNestedIOException(e);
672 if (e instanceof OsmApiInitializationException)
673 return explainOsmApiInitializationException((OsmApiInitializationException) e);
674
675 if (e instanceof ChangesetClosedException)
676 return explainChangesetClosedException((ChangesetClosedException) e);
677
678 if (e instanceof OsmApiException) {
679 OsmApiException oae = (OsmApiException) e;
680 if (oae.getResponseCode() == HttpURLConnection.HTTP_PRECON_FAILED)
681 return explainPreconditionFailed(oae);
682 if (oae.getResponseCode() == HttpURLConnection.HTTP_GONE)
683 return explainGoneForUnknownPrimitive(oae);
684 if (oae.getResponseCode() == HttpURLConnection.HTTP_INTERNAL_ERROR)
685 return explainInternalServerError(oae);
686 if (oae.getResponseCode() == HttpURLConnection.HTTP_BAD_REQUEST)
687 return explainBadRequest(oae);
688 if (oae.getResponseCode() == 509)
689 return explainBandwidthLimitExceeded(oae);
690 }
691 return explainGeneric(e);
692 }
693
694 /**
695 * explains the case of an error due to a delete request on an already deleted
696 * {@link OsmPrimitive}, i.e. a HTTP response code 410, where we don't know which
697 * {@link OsmPrimitive} is causing the error.
698 *
699 * @param e the exception
700 * @return The HTML formatted error message to display
701 */
702 public static String explainGoneForUnknownPrimitive(OsmApiException e) {
703 return tr(
704 "<html>The server reports that an object is deleted.<br>"
705 + "<strong>Uploading failed</strong> if you tried to update or delete this object.<br> "
706 + "<strong>Downloading failed</strong> if you tried to download this object.<br>"
707 + "<br>"
708 + "The error message is:<br>" + "{0}"
709 + "</html>", Utils.escapeReservedCharactersHTML(e.getMessage()));
710 }
711
712 /**
713 * Explains an {@link Exception} to the user.
714 *
715 * @param e the {@link Exception}
716 * @return The HTML formatted error message to display
717 */
718 public static String explainException(Exception e) {
719 Main.error(e);
720 if (e instanceof OsmTransferException) {
721 return explainOsmTransferException((OsmTransferException) e);
722 } else {
723 return explainGeneric(e);
724 }
725 }
726
727 static String getUrlFromException(OsmApiException e) {
728 if (e.getAccessedUrl() != null) {
729 try {
730 return new URL(e.getAccessedUrl()).getHost();
731 } catch (MalformedURLException e1) {
732 Main.warn(e1);
733 }
734 }
735 if (e.getUrl() != null) {
736 return e.getUrl();
737 } else {
738 return OsmApi.getOsmApi().getBaseUrl();
739 }
740 }
741}
Note: See TracBrowser for help on using the repository browser.