public static boolean isRetryable(Throwable t) { if (t instanceof HttpResponseException) { final HttpResponseException e = (HttpResponseException) t; return e.getStatusCode() == 429 || (e.getStatusCode() / 500 == 1); } return t instanceof IOException; } }
@Override @Nullable public BlobDescriptor handleHttpResponseException(HttpResponseException httpResponseException) throws RegistryErrorException, HttpResponseException { if (httpResponseException.getStatusCode() != HttpStatusCodes.STATUS_CODE_NOT_FOUND) { throw httpResponseException; } // Finds a BLOB_UNKNOWN error response code. if (httpResponseException.getContent() == null) { // TODO: The Google HTTP client gives null content for HEAD requests. Make the content never // be null, even for HEAD requests. return null; } ErrorCodes errorCode = ErrorResponseUtil.getErrorCode(httpResponseException); if (errorCode == ErrorCodes.BLOB_UNKNOWN) { return null; } // BLOB_UNKNOWN was not found as a error response code. throw httpResponseException; }
private void deleteIfPresent(String bucket, String path) throws IOException { try { RetryUtils.retry( (RetryUtils.Task<Void>) () -> { storage.delete(bucket, path); return null; }, GoogleUtils::isRetryable, 1, 5 ); } catch (HttpResponseException e) { if (e.getStatusCode() != 404) { throw e; } LOG.debug("Already deleted: [%s] [%s]", bucket, path); } catch (IOException ioe) { throw ioe; } catch (Exception e) { throw new RE(e, "Failed to delete [%s] [%s]", bucket, path); } }
if (httpResponseException.getStatusCode() != HttpStatus.SC_BAD_REQUEST && httpResponseException.getStatusCode() != HttpStatus.SC_UNSUPPORTED_MEDIA_TYPE) { throw httpResponseException;
if (httpResponseException.getStatusCode() == HttpStatusCodes.STATUS_CODE_BAD_REQUEST || httpResponseException.getStatusCode() == HttpStatusCodes.STATUS_CODE_NOT_FOUND || httpResponseException.getStatusCode() == HttpStatusCodes.STATUS_CODE_METHOD_NOT_ALLOWED) { } else if (httpResponseException.getStatusCode() == HttpStatusCodes.STATUS_CODE_FORBIDDEN) { throw new RegistryUnauthorizedException( registryEndpointRequestProperties.getServerUrl(), httpResponseException); } else if (httpResponseException.getStatusCode() == HttpStatusCodes.STATUS_CODE_UNAUTHORIZED) { if (sendCredentials) { } else if (httpResponseException.getStatusCode() == HttpStatusCodes.STATUS_CODE_TEMPORARY_REDIRECT || httpResponseException.getStatusCode() == HttpStatusCodes.STATUS_CODE_MOVED_PERMANENTLY || httpResponseException.getStatusCode() == STATUS_CODE_PERMANENT_REDIRECT) {
private static ExceptionData makeExceptionData(IOException exception, boolean idempotent) { int code = UNKNOWN_CODE; Boolean retryable = null; if (exception instanceof HttpResponseException) { // In cases where an exception is an instance of HttpResponseException, // check the status code to determine whether it's retryable code = ((HttpResponseException) exception).getStatusCode(); retryable = BaseServiceException.isRetryable(code, null, idempotent, Collections.<Error>emptySet()); } return ExceptionData.newBuilder() .setMessage(exception.getMessage()) .setCause(exception) .setRetryable( MoreObjects.firstNonNull( retryable, BaseServiceException.isRetryable(idempotent, exception))) .setCode(code) .setReason(null) .setLocation(null) .setDebugInfo(null) .build(); }
} catch (HttpResponseException ex) { exception = ex; code = ex.getStatusCode(); message = ex.getStatusMessage();
@Override @Nullable public RegistryAuthenticator handleHttpResponseException( HttpResponseException httpResponseException) throws HttpResponseException, RegistryErrorException { // Only valid for status code of '401 Unauthorized'. if (httpResponseException.getStatusCode() != HttpStatusCodes.STATUS_CODE_UNAUTHORIZED) { throw httpResponseException; } // Checks if the 'WWW-Authenticate' header is present. String authenticationMethod = httpResponseException.getHeaders().getAuthenticate(); if (authenticationMethod == null) { throw new RegistryErrorExceptionBuilder(getActionDescription(), httpResponseException) .addReason("'WWW-Authenticate' header not found") .build(); } // Parses the header to retrieve the components. try { return RegistryAuthenticator.fromAuthenticationMethod( authenticationMethod, registryEndpointRequestProperties); } catch (RegistryAuthenticationFailedException ex) { throw new RegistryErrorExceptionBuilder(getActionDescription(), ex) .addReason("Failed get authentication method from 'WWW-Authenticate' header") .build(); } } }
} catch (HttpResponseException ex) { exception = ex; code = ex.getStatusCode(); message = ex.getStatusMessage(); } finally {
private void innerTestCantCopyWithoutUserProject( boolean sourceNormal, boolean destNormal, Path source, Path dest) throws IOException { String sdesc = (sourceNormal ? "normal bucket" : "requester-pays bucket"); String ddesc = (destNormal ? "normal bucket" : "requester-pays bucket"); String description = "Copying from " + sdesc + " to " + ddesc; try { Files.copy(source, dest); Assert.fail("Shouldn't have been able to copy from " + sdesc + " to " + ddesc); // for some reason this throws "GoogleJsonResponseException" instead of "StorageException" // when going from requester pays bucket to requester pays bucket, but otherwise we get a // normal StorageException. } catch (HttpResponseException hex) { Assert.assertEquals(description, hex.getStatusCode(), 400); Assert.assertTrue( description, hex.getMessage() .contains("Bucket is requester pays bucket but no user project provided")); } catch (StorageException ex) { assertIsRequesterPaysException(description, ex); } }
code = ((HttpResponseException) exception).getStatusCode(); retryable = BaseServiceException.isRetryable(code, null, idempotent, retryableErrors);
private static RestDescription loadGoogleAPI(String command, String apiName, String apiVersion) throws IOException { if (!API_NAME_PATTERN.matcher(apiName).matches()) { error(command, "invalid API name: " + apiName); } if (!API_VERSION_PATTERN.matcher(apiVersion).matches()) { error(command, "invalid API version: " + apiVersion); } try { return DISCOVERY.apis().getRest(apiName, apiVersion).execute(); } catch (HttpResponseException e) { if (e.getStatusCode() == 404) { error(command, "API not found: " + apiName); return null; } throw e; } }
System.out.println("done."); } catch (HttpResponseException hre) { if (hre.getStatusCode() == 400) { System.err.println("Unverification failed, because " + "you have not yet removed your verification tokens from the site.");
if (e.getStatusCode() == 404) { if (correlationId != null) { canaryConfigIndex.finishPendingUpdate(credentials, CanaryConfigIndexAction.DELETE, correlationId);
@Override public <T> T loadObject(String accountName, ObjectType objectType, String objectKey) throws IllegalArgumentException, NotFoundException { GoogleNamedAccountCredentials credentials = (GoogleNamedAccountCredentials)accountCredentialsRepository .getOne(accountName) .orElseThrow(() -> new IllegalArgumentException("Unable to resolve account " + accountName + ".")); Storage storage = credentials.getStorage(); String bucketName = credentials.getBucket(); StorageObject item; try { item = resolveSingularItem(objectType, objectKey, credentials, storage, bucketName); } catch (IllegalArgumentException e) { throw new NotFoundException(e.getMessage()); } try { StorageObject storageObject = storage.objects().get(bucketName, item.getName()).execute(); return deserialize(storage, storageObject, objectType.getTypeReference()); } catch (IOException e) { if (e instanceof HttpResponseException) { HttpResponseException hre = (HttpResponseException)e; log.error("Failed to load {} {}: {} {}", objectType.getGroup(), objectKey, hre.getStatusCode(), hre.getStatusMessage()); if (hre.getStatusCode() == 404) { throw new NotFoundException("No file at path " + item.getName() + "."); } } throw new IllegalStateException(e); } }
storage.buckets().get(bucketName).execute(); } catch (HttpResponseException e) { if (e.getStatusCode() == 404) { log.warn("Bucket {} does not exist. Creating it in project {}.", bucketName, projectName);
/** * Triggers the authentication process for the associated {@code username}. */ public void getUserAuthenticated() throws IOException { // assume user is authenticated before service = new GmailServiceMaker(username).makeGmailService(); while (true) { try { // touch one API endpoint to check authentication getListOfUnreadEmailOfUser(); break; } catch (HttpResponseException e) { if (e.getStatusCode() == HttpStatusCodes.STATUS_CODE_FORBIDDEN || e.getStatusCode() == HttpStatusCodes.STATUS_CODE_UNAUTHORIZED || e.getStatusCode() == HttpStatusCodes.STATUS_CODE_BAD_REQUEST) { System.out.println(e.getMessage()); // existing credential missing or not working, should do authentication for the account again service = new GmailServiceMaker(username, true).makeGmailService(); } else { throw new IOException(e); } } } }
@Override public boolean shouldRetry(IOException e) { if (e instanceof HttpResponseException) { HttpResponseException httpException = (HttpResponseException) e; // TODO: Find what we should do for 500 codes that are not always transient. return httpException.getStatusCode() / 100 == 5; } return false; } };
private void handleError(String instanceId, Exception e) throws FirebaseInstanceIdException { String msg = "Error while invoking instance ID service."; if (e instanceof HttpResponseException) { int statusCode = ((HttpResponseException) e).getStatusCode(); if (ERROR_CODES.containsKey(statusCode)) { msg = String.format("Instance ID \"%s\": %s", instanceId, ERROR_CODES.get(statusCode)); } } throw new FirebaseInstanceIdException(msg, e); }
private static void appendResponse(HttpResponseException exception, StringBuilder b) { b.append(exception.getStatusCode()).append(" with "); Long contentLength = exception.getHeaders().getContentLength(); b.append(contentLength != null ? contentLength : Long.valueOf(0)); b.append(" bytes of content"); HttpHeaders headers = exception.getHeaders(); for (String name : headers.keySet()) { b.append('\n').append(name).append(": ").append(headers.get(name)); } b.append('\n').append(exception.getContent()).append('\n'); }