001// License: GPL. For details, see LICENSE file. 002package org.openstreetmap.josm.tools; 003 004import static org.openstreetmap.josm.tools.I18n.tr; 005import static org.openstreetmap.josm.tools.I18n.trn; 006 007import java.io.IOException; 008import java.net.HttpURLConnection; 009import java.net.MalformedURLException; 010import java.net.SocketException; 011import java.net.URL; 012import java.net.UnknownHostException; 013import java.time.Instant; 014import java.time.ZoneId; 015import java.time.format.FormatStyle; 016import java.util.Arrays; 017import java.util.Collection; 018import java.util.List; 019import java.util.Objects; 020import java.util.Optional; 021import java.util.TreeSet; 022import java.util.regex.Matcher; 023import java.util.regex.Pattern; 024 025import org.openstreetmap.josm.data.oauth.OAuthAccessTokenHolder; 026import org.openstreetmap.josm.data.osm.Node; 027import org.openstreetmap.josm.data.osm.OsmPrimitive; 028import org.openstreetmap.josm.data.osm.OsmPrimitiveType; 029import org.openstreetmap.josm.data.osm.Relation; 030import org.openstreetmap.josm.data.osm.Way; 031import org.openstreetmap.josm.gui.help.HelpUtil; 032import org.openstreetmap.josm.io.ChangesetClosedException; 033import org.openstreetmap.josm.io.IllegalDataException; 034import org.openstreetmap.josm.io.MissingOAuthAccessTokenException; 035import org.openstreetmap.josm.io.OfflineAccessException; 036import org.openstreetmap.josm.io.OsmApi; 037import org.openstreetmap.josm.io.OsmApiException; 038import org.openstreetmap.josm.io.OsmApiInitializationException; 039import org.openstreetmap.josm.io.OsmTransferException; 040import org.openstreetmap.josm.io.auth.CredentialsManager; 041import org.openstreetmap.josm.tools.date.DateUtils; 042 043/** 044 * Utilities for exception handling. 045 * @since 2097 046 */ 047public final class ExceptionUtil { 048 049 /** 050 * Error messages sent by the OSM API when a user has been blocked/suspended. 051 */ 052 private static final List<String> OSM_API_BLOCK_MESSAGES = Arrays.asList( 053 "You have an urgent message on the OpenStreetMap web site. " + 054 "You need to read the message before you will be able to save your edits.", 055 "Your access to the API has been blocked. Please log-in to the web interface to find out more.", 056 "Your access to the API is temporarily suspended. Please log-in to the web interface to view the Contributor Terms." + 057 " You do not need to agree, but you must view them."); 058 059 private ExceptionUtil() { 060 // Hide default constructor for utils classes 061 } 062 063 /** 064 * Explains an exception caught during OSM API initialization. 065 * 066 * @param e the exception 067 * @return The HTML formatted error message to display 068 */ 069 public static String explainOsmApiInitializationException(OsmApiInitializationException e) { 070 Logging.error(e); 071 return tr( 072 "<html>Failed to initialize communication with the OSM server {0}.<br>" 073 + "Check the server URL in your preferences and your internet connection.", 074 OsmApi.getOsmApi().getServerUrl())+"</html>"; 075 } 076 077 /** 078 * Explains a {@link OsmApiException} which was thrown because accessing a protected 079 * resource was forbidden. 080 * 081 * @param e the exception 082 * @return The HTML formatted error message to display 083 */ 084 public static String explainMissingOAuthAccessTokenException(MissingOAuthAccessTokenException e) { 085 Logging.error(e); 086 if (e.isClientIdMissing()) { 087 return tr( 088 "<html>Failed to authenticate at the OSM server ''{0}''.<br>" 089 + "JOSM cannot obtain an OAuth Access Token for this server, because it has no OAuth Client ID for it.<br>" 090 + "Please register an OAuth 2.0 application on the server, and enter its Client ID in the OAuth<br>" 091 + "settings of the Preferences Dialog; or enter an Access Token obtained outside JOSM there." 092 + "</html>", 093 e.getClientIdMissingFor() 094 ); 095 } 096 return tr( 097 "<html>Failed to authenticate at the OSM server ''{0}''.<br>" 098 + "You are using OAuth to authenticate but currently there is no<br>" 099 + "OAuth Access Token configured.<br>" 100 + "Please open the Preferences Dialog and generate or enter an Access Token." 101 + "</html>", 102 OsmApi.getOsmApi().getServerUrl() 103 ); 104 } 105 106 /** 107 * Parses a precondition failure response from the server and attempts to get more information about it 108 * @param msg The message from the server 109 * @return The OSM primitive that caused the problem and a collection of primitives that e.g. refer to it 110 */ 111 public static Pair<OsmPrimitive, Collection<OsmPrimitive>> parsePreconditionFailed(String msg) { 112 if (msg == null) 113 return null; 114 final String ids = "(\\d+(?:,\\d+)*)"; 115 final Collection<OsmPrimitive> refs = new TreeSet<>(); // error message can contain several times the same way 116 Matcher m; 117 m = Pattern.compile(".*Node (\\d+) is still used by relations? " + ids + ".*").matcher(msg); 118 if (m.matches()) { 119 OsmPrimitive n = new Node(Long.parseLong(m.group(1))); 120 for (String s : m.group(2).split(",", -1)) { 121 refs.add(new Relation(Long.parseLong(s))); 122 } 123 return Pair.create(n, refs); 124 } 125 m = Pattern.compile(".*Node (\\d+) is still used by ways? " + ids + ".*").matcher(msg); 126 if (m.matches()) { 127 OsmPrimitive n = new Node(Long.parseLong(m.group(1))); 128 for (String s : m.group(2).split(",", -1)) { 129 refs.add(new Way(Long.parseLong(s))); 130 } 131 return Pair.create(n, refs); 132 } 133 m = Pattern.compile(".*The relation (\\d+) is used in relations? " + ids + ".*").matcher(msg); 134 if (m.matches()) { 135 OsmPrimitive n = new Relation(Long.parseLong(m.group(1))); 136 for (String s : m.group(2).split(",", -1)) { 137 refs.add(new Relation(Long.parseLong(s))); 138 } 139 return Pair.create(n, refs); 140 } 141 m = Pattern.compile(".*Way (\\d+) is still used by relations? " + ids + ".*").matcher(msg); 142 if (m.matches()) { 143 OsmPrimitive n = new Way(Long.parseLong(m.group(1))); 144 for (String s : m.group(2).split(",", -1)) { 145 refs.add(new Relation(Long.parseLong(s))); 146 } 147 return Pair.create(n, refs); 148 } 149 m = Pattern.compile(".*Way ([-]*\\d+) requires the nodes with id in " + ids + ".*").matcher(msg); 150 // ... ", which either do not exist, or are not visible" 151 if (m.matches()) { 152 OsmPrimitive n = OsmPrimitiveType.WAY.newInstance(Long.parseLong(m.group(1)), true); 153 for (String s : m.group(2).split(",", -1)) { 154 refs.add(new Node(Long.parseLong(s))); 155 } 156 return Pair.create(n, refs); 157 } 158 m = Pattern.compile(".*Relation ([-]*\\d+) requires the nodes with id in " + ids + ".*").matcher(msg); 159 // ... ", which either do not exist, or are not visible" 160 if (m.matches()) { 161 OsmPrimitive n = OsmPrimitiveType.RELATION.newInstance(Long.parseLong(m.group(1)), true); 162 for (String s : m.group(2).split(",", -1)) { 163 refs.add(new Node(Long.parseLong(s))); 164 } 165 return Pair.create(n, refs); 166 } 167 m = Pattern.compile(".*Relation ([-]*\\d+) requires the ways with id in " + ids + ".*").matcher(msg); 168 // ... ", which either do not exist, or are not visible" 169 if (m.matches()) { 170 OsmPrimitive n = OsmPrimitiveType.RELATION.newInstance(Long.parseLong(m.group(1)), true); 171 for (String s : m.group(2).split(",", -1)) { 172 refs.add(new Way(Long.parseLong(s))); 173 } 174 return Pair.create(n, refs); 175 } 176 return null; 177 } 178 179 /** 180 * Explains an upload error due to a violated precondition, i.e. a HTTP return code 412 181 * 182 * @param e the exception 183 * @return The HTML formatted error message to display 184 */ 185 public static String explainPreconditionFailed(OsmApiException e) { 186 Logging.error(e); 187 Pair<OsmPrimitive, Collection<OsmPrimitive>> conflict = parsePreconditionFailed(e.getErrorHeader()); 188 if (conflict != null) { 189 OsmPrimitive firstRefs = conflict.b.iterator().next(); 190 String objId = Long.toString(conflict.a.getUniqueId()); 191 Collection<Long> refIds = Utils.transform(conflict.b, OsmPrimitive::getId); 192 String refIdsString = refIds.size() == 1 ? refIds.iterator().next().toString() : refIds.toString(); 193 if (conflict.a instanceof Node) { 194 if (firstRefs instanceof Way) { 195 return "<html>" + trn( 196 "<strong>Failed</strong> to delete <strong>node {0}</strong>." 197 + " It is still referred to by way {1}.<br>" 198 + "Please load the way, remove the reference to the node, and upload again.", 199 "<strong>Failed</strong> to delete <strong>node {0}</strong>." 200 + " It is still referred to by ways {1}.<br>" 201 + "Please load the ways, remove the reference to the node, and upload again.", 202 conflict.b.size(), objId, refIdsString) + "</html>"; 203 } else if (firstRefs instanceof Relation) { 204 return "<html>" + trn( 205 "<strong>Failed</strong> to delete <strong>node {0}</strong>." 206 + " It is still referred to by relation {1}.<br>" 207 + "Please load the relation, remove the reference to the node, and upload again.", 208 "<strong>Failed</strong> to delete <strong>node {0}</strong>." 209 + " It is still referred to by relations {1}.<br>" 210 + "Please load the relations, remove the reference to the node, and upload again.", 211 conflict.b.size(), objId, refIdsString) + "</html>"; 212 } else { 213 throw new IllegalStateException(); 214 } 215 } else if (conflict.a instanceof Way) { 216 if (firstRefs instanceof Node) { 217 // way p1 requires nodes 218 return "<html>" + trn( 219 "<strong>Failed</strong> to upload <strong>way {0}</strong>." 220 + " It refers to deleted node {1}.<br>" 221 + "Please load the node, remove the reference in the way, and upload again.", 222 "<strong>Failed</strong> to upload <strong>way {0}</strong>." 223 + " It refers to deleted nodes {1}.<br>" 224 + "Please load the nodes, remove the reference in the way, and upload again.", 225 conflict.b.size(), objId, refIdsString) + "</html>"; 226 } else if (firstRefs instanceof Relation) { 227 // way is used by relation 228 return "<html>" + trn( 229 "<strong>Failed</strong> to delete <strong>way {0}</strong>." 230 + " It is still referred to by relation {1}.<br>" 231 + "Please load the relation, remove the reference to the way, and upload again.", 232 "<strong>Failed</strong> to delete <strong>way {0}</strong>." 233 + " It is still referred to by relations {1}.<br>" 234 + "Please load the relations, remove the reference to the way, and upload again.", 235 conflict.b.size(), objId, refIdsString) + "</html>"; 236 } else { 237 throw new IllegalStateException(); 238 } 239 } else if (conflict.a instanceof Relation) { 240 if (firstRefs instanceof Node) { 241 return "<html>" + trn( 242 "<strong>Failed</strong> to upload <strong>relation {0}</strong>." 243 + " it refers to deleted node {1}.<br>" 244 + "Please load the node, remove the reference in the relation, and upload again.", 245 "<strong>Failed</strong> to upload <strong>relation {0}</strong>." 246 + " it refers to deleted nodes {1}.<br>" 247 + "Please load the nodes, remove the reference in the relation, and upload again.", 248 conflict.b.size(), objId, refIdsString) + "</html>"; 249 } else if (firstRefs instanceof Way) { 250 return "<html>" + trn( 251 "<strong>Failed</strong> to upload <strong>relation {0}</strong>." 252 + " It refers to deleted way {1}.<br>" 253 + "Please load the way, remove the reference in the relation, and upload again.", 254 "<strong>Failed</strong> to upload <strong>relation {0}</strong>." 255 + " It refers to deleted ways {1}.<br>" 256 + "Please load the ways, remove the reference in the relation, and upload again.", 257 conflict.b.size(), objId, refIdsString) + "</html>"; 258 } else if (firstRefs instanceof Relation) { 259 return "<html>" + trn( 260 "<strong>Failed</strong> to delete <strong>relation {0}</strong>." 261 + " It is still referred to by relation {1}.<br>" 262 + "Please load the relation, remove the reference to the relation, and upload again.", 263 "<strong>Failed</strong> to delete <strong>relation {0}</strong>." 264 + " It is still referred to by relations {1}.<br>" 265 + "Please load the relations, remove the reference to the relation, and upload again.", 266 conflict.b.size(), objId, refIdsString) + "</html>"; 267 } else { 268 throw new IllegalStateException(); 269 } 270 } else { 271 throw new IllegalStateException(); 272 } 273 } else { 274 return tr( 275 "<html>Uploading to the server <strong>failed</strong> because your current<br>" 276 + "dataset violates a precondition.<br>" + "The error message is:<br>" + "{0}" + "</html>", 277 Utils.escapeReservedCharactersHTML(e.getMessage())); 278 } 279 } 280 281 /** 282 * Explains a {@link OsmApiException} which was thrown because the authentication at 283 * the OSM server failed, with basic authentication. 284 * 285 * @param e the exception 286 * @return The HTML formatted error message to display 287 */ 288 public static String explainFailedBasicAuthentication(OsmApiException e) { 289 Logging.error(e); 290 return tr("<html>" 291 + "Authentication at the OSM server with the username ''{0}'' failed.<br>" 292 + "Please check the username and the password in the JOSM preferences." 293 + "</html>", 294 e.getLogin() != null ? e.getLogin() : CredentialsManager.getInstance().getUsername() 295 ); 296 } 297 298 /** 299 * Explains a {@link OsmApiException} which was thrown because the authentication at 300 * the OSM server failed, with OAuth authentication. 301 * 302 * @param e the exception 303 * @return The HTML formatted error message to display 304 */ 305 public static String explainFailedOAuthAuthentication(OsmApiException e) { 306 Logging.error(e); 307 return tr("<html>" 308 + "Authentication at the OSM server with the OAuth token ''{0}'' failed.<br>" 309 + "Please launch the preferences dialog and retrieve another OAuth token." 310 + "</html>", 311 OAuthAccessTokenHolder.getInstance().getAccessToken(e.getUrl(), OsmApi.getAuthMethodVersion()) 312 ); 313 } 314 315 /** 316 * Explains a {@link OsmApiException} which was thrown because accessing a protected 317 * resource was forbidden (HTTP 403), without OAuth authentication. 318 * 319 * @param e the exception 320 * @return The HTML formatted error message to display 321 */ 322 public static String explainFailedAuthorisation(OsmApiException e) { 323 Logging.error(e); 324 String msg = e.getDisplayMessage(); 325 326 if (!Utils.isEmpty(msg)) { 327 return tr("<html>" 328 + "Authorisation at the OSM server failed.<br>" 329 + "The server reported the following error:<br>" 330 + "''{0}''" 331 + "</html>", 332 msg 333 ); 334 } else { 335 return tr("<html>" 336 + "Authorisation at the OSM server failed.<br>" 337 + "</html>" 338 ); 339 } 340 } 341 342 /** 343 * Explains a {@link OsmApiException} which was thrown because accessing a protected 344 * resource was forbidden (HTTP 403), with OAuth authentication. 345 * 346 * @param e the exception 347 * @return The HTML formatted error message to display 348 */ 349 public static String explainFailedOAuthAuthorisation(OsmApiException e) { 350 Logging.error(e); 351 return tr("<html>" 352 + "Authorisation at the OSM server with the OAuth token ''{0}'' failed.<br>" 353 + "The token is not authorised to access the protected resource<br>" 354 + "''{1}''.<br>" 355 + "Please launch the preferences dialog and retrieve another OAuth token." 356 + "</html>", 357 OAuthAccessTokenHolder.getInstance().getAccessToken(e.getUrl(), OsmApi.getAuthMethodVersion()), 358 e.getAccessedUrl() == null ? tr("unknown") : e.getAccessedUrl() 359 ); 360 } 361 362 /** 363 * Explains an OSM API exception because of a client timeout (HTTP 408). 364 * 365 * @param e the exception 366 * @return The HTML formatted error message to display 367 */ 368 public static String explainClientTimeout(OsmApiException e) { 369 Logging.error(e); 370 return tr("<html>" 371 + "Communication with the OSM server ''{0}'' timed out. Please retry later." 372 + "</html>", 373 getUrlFromException(e) 374 ); 375 } 376 377 /** 378 * Replies a generic error message for an OSM API exception 379 * 380 * @param e the exception 381 * @return The HTML formatted error message to display 382 */ 383 public static String explainGenericOsmApiException(OsmApiException e) { 384 Logging.error(e); 385 return tr("<html>" 386 + "Communication with the OSM server ''{0}''failed. The server replied<br>" 387 + "the following error code and the following error message:<br>" 388 + "<strong>Error code:<strong> {1}<br>" 389 + "<strong>Error message (untranslated)</strong>: {2}" 390 + "</html>", 391 getUrlFromException(e), 392 e.getResponseCode(), 393 Optional.ofNullable(Optional.ofNullable(e.getErrorHeader()).orElseGet(e::getErrorBody)) 394 .orElse(tr("no error message available")) 395 ); 396 } 397 398 /** 399 * Explains an error due to a 409 conflict 400 * 401 * @param e the exception 402 * @return The HTML formatted error message to display 403 */ 404 public static String explainConflict(OsmApiException e) { 405 Logging.error(e); 406 String msg = e.getErrorHeader(); 407 if (msg != null) { 408 Matcher m = Pattern.compile("The changeset (\\d+) was closed at (.*)").matcher(msg); 409 if (m.matches()) { 410 long changesetId = Long.parseLong(m.group(1)); 411 Instant closeDate = null; 412 try { 413 closeDate = DateUtils.parseInstant(m.group(2)); 414 } catch (UncheckedParseException ex) { 415 Logging.error(tr("Failed to parse date ''{0}'' replied by server.", m.group(2))); 416 Logging.error(ex); 417 } 418 if (closeDate == null) { 419 msg = tr( 420 "<html>Closing of changeset <strong>{0}</strong> failed <br>because it has already been closed.", 421 changesetId 422 ); 423 } else { 424 msg = tr( 425 "<html>Closing of changeset <strong>{0}</strong> failed<br>" 426 +" because it has already been closed on {1}.", 427 changesetId, 428 formatClosedOn(closeDate) 429 ); 430 } 431 return msg; 432 } 433 msg = tr( 434 "<html>The server reported that it has detected a conflict.<br>" + 435 "Error message (untranslated):<br>{0}</html>", 436 msg 437 ); 438 } else { 439 msg = tr( 440 "<html>The server reported that it has detected a conflict."); 441 } 442 return msg.endsWith("</html>") ? msg : (msg + "</html>"); 443 } 444 445 /** 446 * Explains an exception thrown during upload because the changeset which data is 447 * uploaded to is already closed. 448 * 449 * @param e the exception 450 * @return The HTML formatted error message to display 451 */ 452 public static String explainChangesetClosedException(ChangesetClosedException e) { 453 Logging.error(e); 454 return tr( 455 "<html>Failed to upload to changeset <strong>{0}</strong><br>" 456 +"because it has already been closed on {1}.", 457 e.getChangesetId(), 458 e.getClosedOn() == null ? "?" : formatClosedOn(e.getClosedOn()) 459 ); 460 } 461 462 private static String formatClosedOn(Instant closedOn) { 463 return DateUtils.getDateTimeFormatter(FormatStyle.SHORT, FormatStyle.SHORT).format(closedOn.atZone(ZoneId.systemDefault())); 464 } 465 466 /** 467 * Explains an exception with a generic message dialog 468 * 469 * @param e the exception 470 * @return The HTML formatted error message to display 471 */ 472 public static String explainGeneric(Exception e) { 473 String msg = e.getMessage(); 474 if (Utils.isStripEmpty(msg)) { 475 msg = e.toString(); 476 } 477 Logging.error(e); 478 return Utils.escapeReservedCharactersHTML(msg); 479 } 480 481 /** 482 * Explains a {@link SecurityException} which has caused an {@link OsmTransferException}. 483 * This is most likely happening when user tries to access the OSM API from within an 484 * applet which wasn't loaded from the API server. 485 * 486 * @param e the exception 487 * @return The HTML formatted error message to display 488 */ 489 public static String explainSecurityException(OsmTransferException e) { 490 String apiUrl = e.getUrl(); 491 String host = tr("unknown"); 492 try { 493 host = new URL(apiUrl).getHost(); 494 } catch (MalformedURLException ex) { 495 // shouldn't happen 496 Logging.trace(ex); 497 } 498 499 return tr("<html>Failed to open a connection to the remote server<br>" + "''{0}''<br>" 500 + "for security reasons. This is most likely because you are running<br>" 501 + "in an applet and because you did not load your applet from ''{1}''.", apiUrl, host)+"</html>"; 502 } 503 504 /** 505 * Explains a {@link SocketException} which has caused an {@link OsmTransferException}. 506 * This is most likely because there's not connection to the Internet or because 507 * the remote server is not reachable. 508 * 509 * @param e the exception 510 * @return The HTML formatted error message to display 511 */ 512 public static String explainNestedSocketException(OsmTransferException e) { 513 Logging.error(e); 514 return tr("<html>Failed to open a connection to the remote server<br>" + "''{0}''.<br>" 515 + "Please check your internet connection.", e.getUrl())+"</html>"; 516 } 517 518 /** 519 * Explains a {@link IOException} which has caused an {@link OsmTransferException}. 520 * This is most likely happening when the communication with the remote server is 521 * interrupted for any reason. 522 * 523 * @param e the exception 524 * @return The HTML formatted error message to display 525 */ 526 public static String explainNestedIOException(OsmTransferException e) { 527 IOException ioe = getNestedException(e, IOException.class); 528 Logging.error(e); 529 return tr("<html>Failed to upload data to or download data from<br>" + "''{0}''<br>" 530 + "due to a problem with transferring data.<br>" 531 + "Details (untranslated): {1}</html>", 532 e != null ? e.getUrl() : "null", 533 ioe != null ? ioe.getMessage() : "null"); 534 } 535 536 /** 537 * Explains a {@link IllegalDataException} which has caused an {@link OsmTransferException}. 538 * This is most likely happening when JOSM tries to load data in an unsupported format. 539 * 540 * @param e the exception 541 * @return The HTML formatted error message to display 542 */ 543 public static String explainNestedIllegalDataException(OsmTransferException e) { 544 IllegalDataException ide = getNestedException(e, IllegalDataException.class); 545 Logging.error(e); 546 return tr("<html>Failed to download data. " 547 + "Its format is either unsupported, ill-formed, and/or inconsistent.<br>" 548 + "<br>Details (untranslated): {0}</html>", ide != null ? ide.getMessage() : "null"); 549 } 550 551 /** 552 * Explains a {@link OfflineAccessException} which has caused an {@link OsmTransferException}. 553 * This is most likely happening when JOSM tries to access OSM API or JOSM website while in offline mode. 554 * 555 * @param e the exception 556 * @return The HTML formatted error message to display 557 * @since 7434 558 */ 559 public static String explainOfflineAccessException(OsmTransferException e) { 560 OfflineAccessException oae = getNestedException(e, OfflineAccessException.class); 561 Logging.error(e); 562 return tr("<html>Failed to download data.<br>" 563 + "<br>Details: {0}</html>", oae != null ? oae.getMessage() : "null"); 564 } 565 566 /** 567 * Explains a {@link OsmApiException} which was thrown because of an internal server 568 * error in the OSM API server. 569 * 570 * @param e the exception 571 * @return The HTML formatted error message to display 572 */ 573 public static String explainInternalServerError(OsmTransferException e) { 574 Logging.error(e); 575 return tr("<html>The OSM server<br>" + "''{0}''<br>" + "reported an internal server error.<br>" 576 + "This is most likely a temporary problem. Please try again later.", e.getUrl())+"</html>"; 577 } 578 579 /** 580 * Explains a {@link OsmApiException} which was thrown because of a bad request. 581 * 582 * @param e the exception 583 * @return The HTML formatted error message to display 584 */ 585 public static String explainBadRequest(OsmApiException e) { 586 String message = tr("The OSM server ''{0}'' reported a bad request.<br>", getUrlFromException(e)); 587 String errorHeader = e.getErrorHeader(); 588 if (errorHeader != null && (errorHeader.startsWith("The maximum bbox") || 589 errorHeader.startsWith("You requested too many nodes"))) { 590 message += "<br>" 591 + tr("The area you tried to download is too big or your request was too large." 592 + "<br>Either request a smaller area or use an export file provided by the OSM community." 593 + "<br><br>Downloading a smaller area is <em>recommended</em>!" 594 + "<br><br>Advanced users can use one of the following options:" 595 + "<br><ul>" 596 + "<li><a href=\"{0}\">Overpass</a></li>" 597 + "<li><a href=\"{1}\">Geofabrik</a></li>" 598 + "<li><a href=\"{2}\">OSM Planet File</a></li>" 599 + "</ul>", HelpUtil.getHelpTopicUrl("/Help/Action/Download#DownloadfromOverpassAPI"), 600 "https://www.geofabrik.de/data/download.html", 601 "https://planet.openstreetmap.org/"); 602 } else if (errorHeader != null) { 603 message += tr("<br>Error message(untranslated): {0}", errorHeader); 604 } 605 Logging.error(e); 606 return "<html>" + message + "</html>"; 607 } 608 609 /** 610 * Explains a {@link OsmApiException} which was thrown because of 611 * bandwidth limit exceeded (HTTP error 509) 612 * 613 * @param e the exception 614 * @return The HTML formatted error message to display 615 */ 616 public static String explainBandwidthLimitExceeded(OsmApiException e) { 617 Logging.error(e); 618 // TODO: Write a proper error message 619 return explainGenericOsmApiException(e); 620 } 621 622 /** 623 * Explains a {@link OsmApiException} which was thrown because a resource wasn't found. 624 * 625 * @param e the exception 626 * @return The HTML formatted error message to display 627 */ 628 public static String explainNotFound(OsmApiException e) { 629 String message = tr("The OSM server ''{0}'' does not know about an object<br>" 630 + "you tried to read, update, or delete. Either the respective object<br>" 631 + "does not exist on the server or you are using an invalid URL to access<br>" 632 + "it. Please carefully check the server''s address ''{0}'' for typos.", 633 getUrlFromException(e)); 634 Logging.error(e); 635 return "<html>" + message + "</html>"; 636 } 637 638 /** 639 * Explains a {@link UnknownHostException} which has caused an {@link OsmTransferException}. 640 * This is most likely happening when there is an error in the API URL or when 641 * local DNS services are not working. 642 * 643 * @param e the exception 644 * @return The HTML formatted error message to display 645 */ 646 public static String explainNestedUnknownHostException(OsmTransferException e) { 647 String apiUrl = e.getUrl(); 648 String host = tr("unknown"); 649 try { 650 host = new URL(apiUrl).getHost(); 651 } catch (MalformedURLException ex) { 652 // shouldn't happen 653 Logging.trace(e); 654 } 655 656 Logging.error(e); 657 return tr("<html>Failed to open a connection to the remote server<br>" + "''{0}''.<br>" 658 + "Host name ''{1}'' could not be resolved. <br>" 659 + "Please check the API URL in your preferences and your internet connection.", apiUrl, host)+"</html>"; 660 } 661 662 /** 663 * Replies the first nested exception of type <code>nestedClass</code> (including 664 * the root exception <code>e</code>) or null, if no such exception is found. 665 * 666 * @param <T> nested exception type 667 * @param e the root exception 668 * @param nestedClass the type of the nested exception 669 * @return the first nested exception of type <code>nestedClass</code> (including 670 * the root exception <code>e</code>) or null, if no such exception is found. 671 * @since 8470 672 */ 673 public static <T> T getNestedException(Exception e, Class<T> nestedClass) { 674 Throwable t = e; 675 while (t != null && !nestedClass.isInstance(t)) { 676 t = t.getCause(); 677 } 678 if (t == null) 679 return null; 680 else if (nestedClass.isInstance(t)) 681 return nestedClass.cast(t); 682 return null; 683 } 684 685 /** 686 * Explains an {@link OsmTransferException} to the user. 687 * 688 * @param e the {@link OsmTransferException} 689 * @return The HTML formatted error message to display 690 */ 691 public static String explainOsmTransferException(OsmTransferException e) { 692 Objects.requireNonNull(e, "e"); 693 if (getNestedException(e, SecurityException.class) != null) 694 return explainSecurityException(e); 695 if (getNestedException(e, SocketException.class) != null) 696 return explainNestedSocketException(e); 697 if (getNestedException(e, UnknownHostException.class) != null) 698 return explainNestedUnknownHostException(e); 699 if (getNestedException(e, IOException.class) != null) 700 return explainNestedIOException(e); 701 if (e instanceof OsmApiInitializationException) 702 return explainOsmApiInitializationException((OsmApiInitializationException) e); 703 704 if (e instanceof ChangesetClosedException) 705 return explainChangesetClosedException((ChangesetClosedException) e); 706 707 if (e instanceof OsmApiException) { 708 OsmApiException oae = (OsmApiException) e; 709 if (oae.getResponseCode() == HttpURLConnection.HTTP_PRECON_FAILED) 710 return explainPreconditionFailed(oae); 711 if (oae.getResponseCode() == HttpURLConnection.HTTP_GONE) 712 return explainGoneForUnknownPrimitive(oae); 713 if (oae.getResponseCode() == HttpURLConnection.HTTP_INTERNAL_ERROR) 714 return explainInternalServerError(oae); 715 if (oae.getResponseCode() == HttpURLConnection.HTTP_BAD_REQUEST) 716 return explainBadRequest(oae); 717 if (oae.getResponseCode() == 509) 718 return explainBandwidthLimitExceeded(oae); 719 } 720 return explainGeneric(e); 721 } 722 723 /** 724 * explains the case of an error due to a delete request on an already deleted 725 * {@link OsmPrimitive}, i.e. a HTTP response code 410, where we don't know which 726 * {@link OsmPrimitive} is causing the error. 727 * 728 * @param e the exception 729 * @return The HTML formatted error message to display 730 */ 731 public static String explainGoneForUnknownPrimitive(OsmApiException e) { 732 return tr( 733 "<html>The server reports that an object is deleted.<br>" 734 + "<strong>Uploading failed</strong> if you tried to update or delete this object.<br> " 735 + "<strong>Downloading failed</strong> if you tried to download this object.<br>" 736 + "<br>" 737 + "The error message is:<br>" + "{0}" 738 + "</html>", Utils.escapeReservedCharactersHTML(e.getMessage())); 739 } 740 741 /** 742 * Explains an {@link Exception} to the user. 743 * 744 * @param e the {@link Exception} 745 * @return The HTML formatted error message to display 746 */ 747 public static String explainException(Exception e) { 748 Logging.error(e); 749 if (e instanceof OsmTransferException) { 750 return explainOsmTransferException((OsmTransferException) e); 751 } else { 752 return explainGeneric(e); 753 } 754 } 755 756 /** 757 * Determines if the OSM API exception has been thrown because user has been blocked or suspended. 758 * @param e OSM API exception 759 * @return {@code true} if the OSM API exception has been thrown because user has been blocked or suspended 760 * @since 15084 761 */ 762 public static boolean isUserBlocked(OsmApiException e) { 763 return OSM_API_BLOCK_MESSAGES.contains(e.getErrorHeader()); 764 } 765 766 static String getUrlFromException(OsmApiException e) { 767 if (e.getAccessedUrl() != null) { 768 try { 769 return new URL(e.getAccessedUrl()).getHost(); 770 } catch (MalformedURLException e1) { 771 Logging.warn(e1); 772 } 773 } 774 if (e.getUrl() != null) { 775 return e.getUrl(); 776 } else { 777 return OsmApi.getOsmApi().getBaseUrl(); 778 } 779 } 780}