Java Code Examples for com.google.api.client.http.HttpResponseException#getStatusCode()
The following examples show how to use
com.google.api.client.http.HttpResponseException#getStatusCode() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: PayrollAuApi.java From Xero-Java with MIT License | 6 votes |
/** * Update a Payslip * Update lines on a single payslips * <p><b>200</b> - A successful request - currently returns empty array for JSON * @param xeroTenantId Xero identifier for Tenant * @param payslipID Payslip id for single object * @param payslipLines The payslipLines parameter * @param accessToken Authorization token for user set in header of each request * @return Payslips * @throws IOException if an error occurs while attempting to invoke the API **/ public Payslips updatePayslip(String accessToken, String xeroTenantId, UUID payslipID, List<PayslipLines> payslipLines) throws IOException { try { TypeReference<Payslips> typeRef = new TypeReference<Payslips>() {}; HttpResponse response = updatePayslipForHttpResponse(accessToken, xeroTenantId, payslipID, payslipLines); return apiClient.getObjectMapper().readValue(response.getContent(), typeRef); } catch (HttpResponseException e) { if (logger.isDebugEnabled()) { logger.debug("------------------ HttpResponseException " + e.getStatusCode() + " : updatePayslip -------------------"); logger.debug(e.toString()); } XeroApiExceptionHandler handler = new XeroApiExceptionHandler(); if (e.getStatusCode() == 400 || e.getStatusCode() == 405) { TypeReference<com.xero.models.accounting.Error> errorTypeRef = new TypeReference<com.xero.models.accounting.Error>() {}; com.xero.models.accounting.Error error = apiClient.getObjectMapper().readValue(e.getContent(), errorTypeRef); handler.validationError("Error", error.getMessage()); } else { handler.execute(e); } } catch (IOException ioe) { throw ioe; } return null; }
Example 2
Source File: AsanaError.java From java-asana with MIT License | 6 votes |
public static AsanaError mapException(HttpResponseException exception) throws AsanaError { switch (exception.getStatusCode()) { case ForbiddenError.STATUS: return new ForbiddenError(exception); case InvalidRequestError.STATUS: return new InvalidRequestError(exception); case InvalidTokenError.STATUS: return new InvalidTokenError(exception); case NoAuthorizationError.STATUS: return new NoAuthorizationError(exception); case NotFoundError.STATUS: return new NotFoundError(exception); case PremiumOnlyError.STATUS: return new PremiumOnlyError(exception); case RateLimitEnforcedError.STATUS: return new RateLimitEnforcedError(exception); case ServerError.STATUS: return new ServerError(exception); default: return new AsanaError(exception.getStatusMessage(), exception.getStatusCode(), exception); } }
Example 3
Source File: BaseTransactionalIT.java From steem-java-api-wrapper with GNU General Public License v3.0 | 6 votes |
/** * Create a new TestNet account as described in the TestNet main page * (https://testnet.steem.vc). * * @param username * The account to create. * @param password * The password to set for the <code>username</code>. * @throws IOException * In case something went wrong. * @throws GeneralSecurityException * In case something went wrong. */ private static void createTestNetAccount(String username, String password) throws IOException, GeneralSecurityException { NetHttpTransport.Builder builder = new NetHttpTransport.Builder(); // Disable SSL verification: builder.doNotValidateCertificate(); HttpRequest httpRequest = builder.build().createRequestFactory(new HttpClientRequestInitializer()) .buildPostRequest(new GenericUrl("https://testnet.steem.vc/create"), ByteArrayContent.fromString( "application/x-www-form-urlencoded", "username=" + username + "&password=" + password)); try { httpRequest.execute(); } catch (HttpResponseException e) { if (e.getStatusCode() != 409) { LOGGER.info("Account already existed."); } } }
Example 4
Source File: GcsStorageService.java From front50 with Apache License 2.0 | 6 votes |
private <T> T timeExecute(Id timerId, AbstractGoogleClientRequest<T> request) throws IOException { T result; Clock clock = registry.clock(); long startTime = clock.monotonicTime(); int statusCode = -1; try { result = request.execute(); statusCode = request.getLastStatusCode(); } catch (HttpResponseException e) { statusCode = e.getStatusCode(); throw e; } catch (IOException ioex) { throw ioex; } catch (Exception ex) { throw new IllegalStateException(ex); } finally { long nanos = clock.monotonicTime() - startTime; String status = Integer.toString(statusCode).charAt(0) + "xx"; Id id = timerId.withTags("status", status, "statusCode", Integer.toString(statusCode)); registry.timer(id).record(nanos, TimeUnit.NANOSECONDS); } return result; }
Example 5
Source File: AssetApi.java From Xero-Java with MIT License | 6 votes |
/** * adds a fixed asset * Adds an asset to the system * <p><b>200</b> - return single object - create new asset * <p><b>400</b> - invalid input, object invalid * @param xeroTenantId Xero identifier for Tenant * @param asset Fixed asset you are creating * @param accessToken Authorization token for user set in header of each request * @return Asset * @throws IOException if an error occurs while attempting to invoke the API **/ public Asset createAsset(String accessToken, String xeroTenantId, Asset asset) throws IOException { try { TypeReference<Asset> typeRef = new TypeReference<Asset>() {}; HttpResponse response = createAssetForHttpResponse(accessToken, xeroTenantId, asset); return apiClient.getObjectMapper().readValue(response.getContent(), typeRef); } catch (HttpResponseException e) { if (logger.isDebugEnabled()) { logger.debug("------------------ HttpResponseException " + e.getStatusCode() + " : createAsset -------------------"); logger.debug(e.toString()); } XeroApiExceptionHandler handler = new XeroApiExceptionHandler(); if (e.getStatusCode() == 400) { TypeReference<com.xero.models.assets.Error> errorTypeRef = new TypeReference<com.xero.models.assets.Error>() {}; com.xero.models.assets.Error assetError = apiClient.getObjectMapper().readValue(e.getContent(), errorTypeRef); handler.validationError("Asset",assetError); } else { handler.execute(e); } } catch (IOException ioe) { throw ioe; } return null; }
Example 6
Source File: BankFeedsApi.java From Xero-Java with MIT License | 6 votes |
/** * <p><b>202</b> - Success returns Statements array of objects in response * <p><b>400</b> - Statement failed validation * <p><b>403</b> - Invalid application or feed connection * <p><b>409</b> - Duplicate statement received * <p><b>413</b> - Statement exceeds size limit * <p><b>422</b> - Unprocessable Entity * <p><b>500</b> - Intermittent Xero Error * @param xeroTenantId Xero identifier for Tenant * @param statements Statements array of objects in the body * @param accessToken Authorization token for user set in header of each request * @return Statements * @throws IOException if an error occurs while attempting to invoke the API **/ public Statements createStatements(String accessToken, String xeroTenantId, Statements statements) throws IOException { try { TypeReference<Statements> typeRef = new TypeReference<Statements>() {}; HttpResponse response = createStatementsForHttpResponse(accessToken, xeroTenantId, statements); return apiClient.getObjectMapper().readValue(response.getContent(), typeRef); } catch (HttpResponseException e) { if (logger.isDebugEnabled()) { logger.debug("------------------ HttpResponseException " + e.getStatusCode() + " : createStatements -------------------"); logger.debug(e.toString()); } XeroApiExceptionHandler handler = new XeroApiExceptionHandler(); if (e.getStatusCode() == 400) { TypeReference<Statements> errorTypeRef = new TypeReference<Statements>() {}; Statements bankFeedError = apiClient.getObjectMapper().readValue(e.getContent(), errorTypeRef); handler.validationError("Statements",bankFeedError); } else { handler.execute(e); } } catch (IOException ioe) { throw ioe; } return null; }
Example 7
Source File: BankFeedsApi.java From Xero-Java with MIT License | 6 votes |
/** * create one or more new feed connection * By passing in the FeedConnections array object in the body, you can create one or more new feed connections * <p><b>201</b> - success new feed connection(s)response * <p><b>400</b> - invalid input, object invalid * <p><b>409</b> - failed to create new feed connection(s)response * @param xeroTenantId Xero identifier for Tenant * @param feedConnections Feed Connection(s) array object in the body * @param accessToken Authorization token for user set in header of each request * @return FeedConnections * @throws IOException if an error occurs while attempting to invoke the API **/ public FeedConnections createFeedConnections(String accessToken, String xeroTenantId, FeedConnections feedConnections) throws IOException { try { TypeReference<FeedConnections> typeRef = new TypeReference<FeedConnections>() {}; HttpResponse response = createFeedConnectionsForHttpResponse(accessToken, xeroTenantId, feedConnections); return apiClient.getObjectMapper().readValue(response.getContent(), typeRef); } catch (HttpResponseException e) { if (logger.isDebugEnabled()) { logger.debug("------------------ HttpResponseException " + e.getStatusCode() + " : createFeedConnections -------------------"); logger.debug(e.toString()); } XeroApiExceptionHandler handler = new XeroApiExceptionHandler(); if (e.getStatusCode() == 400) { TypeReference<FeedConnections> errorTypeRef = new TypeReference<FeedConnections>() {}; FeedConnections bankFeedError = apiClient.getObjectMapper().readValue(e.getContent(), errorTypeRef); handler.validationError("FeedConnections",bankFeedError); } else { handler.execute(e); } } catch (IOException ioe) { throw ioe; } return null; }
Example 8
Source File: EmailAccount.java From teammates with GNU General Public License v2.0 | 6 votes |
/** * 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); } } } }
Example 9
Source File: PayrollAuApi.java From Xero-Java with MIT License | 5 votes |
/** * Use this method to create a Payroll Calendars * <p><b>200</b> - A successful request * <p><b>400</b> - invalid input, object invalid - TODO * @param xeroTenantId Xero identifier for Tenant * @param payrollCalendar The payrollCalendar parameter * @param accessToken Authorization token for user set in header of each request * @return PayrollCalendars * @throws IOException if an error occurs while attempting to invoke the API **/ public PayrollCalendars createPayrollCalendar(String accessToken, String xeroTenantId, List<PayrollCalendar> payrollCalendar) throws IOException { try { TypeReference<PayrollCalendars> typeRef = new TypeReference<PayrollCalendars>() {}; HttpResponse response = createPayrollCalendarForHttpResponse(accessToken, xeroTenantId, payrollCalendar); return apiClient.getObjectMapper().readValue(response.getContent(), typeRef); } catch (HttpResponseException e) { if (logger.isDebugEnabled()) { logger.debug("------------------ HttpResponseException " + e.getStatusCode() + " : createPayrollCalendar -------------------"); logger.debug(e.toString()); } XeroApiExceptionHandler handler = new XeroApiExceptionHandler(); if (e.getStatusCode() == 400 || e.getStatusCode() == 405) { TypeReference<PayrollCalendars> objectTypeRef = new TypeReference<PayrollCalendars>() {}; PayrollCalendars object = apiClient.getObjectMapper().readValue(e.getContent(), objectTypeRef); if (object.getPayrollCalendars() == null || object.getPayrollCalendars().isEmpty()) { TypeReference<com.xero.models.accounting.Error> errorTypeRef = new TypeReference<com.xero.models.accounting.Error>() {}; com.xero.models.accounting.Error error = apiClient.getObjectMapper().readValue(e.getContent(), errorTypeRef); handler.validationError("Error", error.getMessage()); } handler.validationError("PayrollCalendars",object); } else { handler.execute(e); } } catch (IOException ioe) { throw ioe; } return null; }
Example 10
Source File: PayrollAuApi.java From Xero-Java with MIT License | 5 votes |
/** * Use this method to create a super fund * <p><b>200</b> - A successful request * <p><b>400</b> - invalid input, object invalid - TODO * @param xeroTenantId Xero identifier for Tenant * @param superFund The superFund parameter * @param accessToken Authorization token for user set in header of each request * @return SuperFunds * @throws IOException if an error occurs while attempting to invoke the API **/ public SuperFunds createSuperfund(String accessToken, String xeroTenantId, List<SuperFund> superFund) throws IOException { try { TypeReference<SuperFunds> typeRef = new TypeReference<SuperFunds>() {}; HttpResponse response = createSuperfundForHttpResponse(accessToken, xeroTenantId, superFund); return apiClient.getObjectMapper().readValue(response.getContent(), typeRef); } catch (HttpResponseException e) { if (logger.isDebugEnabled()) { logger.debug("------------------ HttpResponseException " + e.getStatusCode() + " : createSuperfund -------------------"); logger.debug(e.toString()); } XeroApiExceptionHandler handler = new XeroApiExceptionHandler(); if (e.getStatusCode() == 400 || e.getStatusCode() == 405) { TypeReference<SuperFunds> objectTypeRef = new TypeReference<SuperFunds>() {}; SuperFunds object = apiClient.getObjectMapper().readValue(e.getContent(), objectTypeRef); if (object.getSuperFunds() == null || object.getSuperFunds().isEmpty()) { TypeReference<com.xero.models.accounting.Error> errorTypeRef = new TypeReference<com.xero.models.accounting.Error>() {}; com.xero.models.accounting.Error error = apiClient.getObjectMapper().readValue(e.getContent(), errorTypeRef); handler.validationError("Error", error.getMessage()); } handler.validationError("SuperFunds",object); } else { handler.execute(e); } } catch (IOException ioe) { throw ioe; } return null; }
Example 11
Source File: PayrollAuApi.java From Xero-Java with MIT License | 5 votes |
/** * Use this method to create a timesheet * <p><b>200</b> - A successful request * <p><b>400</b> - invalid input, object invalid - TODO * @param xeroTenantId Xero identifier for Tenant * @param timesheet The timesheet parameter * @param accessToken Authorization token for user set in header of each request * @return Timesheets * @throws IOException if an error occurs while attempting to invoke the API **/ public Timesheets createTimesheet(String accessToken, String xeroTenantId, List<Timesheet> timesheet) throws IOException { try { TypeReference<Timesheets> typeRef = new TypeReference<Timesheets>() {}; HttpResponse response = createTimesheetForHttpResponse(accessToken, xeroTenantId, timesheet); return apiClient.getObjectMapper().readValue(response.getContent(), typeRef); } catch (HttpResponseException e) { if (logger.isDebugEnabled()) { logger.debug("------------------ HttpResponseException " + e.getStatusCode() + " : createTimesheet -------------------"); logger.debug(e.toString()); } XeroApiExceptionHandler handler = new XeroApiExceptionHandler(); if (e.getStatusCode() == 400 || e.getStatusCode() == 405) { TypeReference<Timesheets> objectTypeRef = new TypeReference<Timesheets>() {}; Timesheets object = apiClient.getObjectMapper().readValue(e.getContent(), objectTypeRef); if (object.getTimesheets() == null || object.getTimesheets().isEmpty()) { TypeReference<com.xero.models.accounting.Error> errorTypeRef = new TypeReference<com.xero.models.accounting.Error>() {}; com.xero.models.accounting.Error error = apiClient.getObjectMapper().readValue(e.getContent(), errorTypeRef); handler.validationError("Error", error.getMessage()); } handler.validationError("Timesheets",object); } else { handler.execute(e); } } catch (IOException ioe) { throw ioe; } return null; }
Example 12
Source File: GooglePhotosInterface.java From data-transfer-project with Apache License 2.0 | 5 votes |
private HttpResponse handleHttpResponseException( SupplierWithIO<HttpRequest> httpRequest, HttpResponseException e) throws IOException, InvalidTokenException, PermissionDeniedException { // if the response is "unauthorized", refresh the token and try the request again final int statusCode = e.getStatusCode(); if (statusCode == 401) { monitor.info(() -> "Attempting to refresh authorization token"); // if the credential refresh failed, let the error bubble up via the IOException that gets // thrown credential = credentialFactory.refreshCredential(credential); monitor.info(() -> "Refreshed authorization token successfuly"); // if the second attempt throws an error, then something else is wrong, and we bubble up the // response errors return httpRequest.getWithIO().execute(); } // "The caller does not have permission" is potential error for albums. // "Google Photos is disabled for the user" is potential error for photos. if (statusCode == 403 && (e.getContent().contains("The caller does not have permission") || e.getContent().contains("Google Photos is disabled for the user"))) { throw new PermissionDeniedException("User permission to google photos was denied", e); } else { // something else is wrong, bubble up the error throw new IOException( "Bad status code: " + e.getStatusCode() + " Error: '" + e.getStatusMessage() + "' Content: " + e.getContent()); } }
Example 13
Source File: PayrollAuApi.java From Xero-Java with MIT License | 5 votes |
/** * Use this method to create a PayRun * <p><b>200</b> - A successful request * <p><b>400</b> - invalid input, object invalid - TODO * @param xeroTenantId Xero identifier for Tenant * @param payRun The payRun parameter * @param accessToken Authorization token for user set in header of each request * @return PayRuns * @throws IOException if an error occurs while attempting to invoke the API **/ public PayRuns createPayRun(String accessToken, String xeroTenantId, List<PayRun> payRun) throws IOException { try { TypeReference<PayRuns> typeRef = new TypeReference<PayRuns>() {}; HttpResponse response = createPayRunForHttpResponse(accessToken, xeroTenantId, payRun); return apiClient.getObjectMapper().readValue(response.getContent(), typeRef); } catch (HttpResponseException e) { if (logger.isDebugEnabled()) { logger.debug("------------------ HttpResponseException " + e.getStatusCode() + " : createPayRun -------------------"); logger.debug(e.toString()); } XeroApiExceptionHandler handler = new XeroApiExceptionHandler(); if (e.getStatusCode() == 400 || e.getStatusCode() == 405) { TypeReference<PayRuns> objectTypeRef = new TypeReference<PayRuns>() {}; PayRuns object = apiClient.getObjectMapper().readValue(e.getContent(), objectTypeRef); if (object.getPayRuns() == null || object.getPayRuns().isEmpty()) { TypeReference<com.xero.models.accounting.Error> errorTypeRef = new TypeReference<com.xero.models.accounting.Error>() {}; com.xero.models.accounting.Error error = apiClient.getObjectMapper().readValue(e.getContent(), errorTypeRef); handler.validationError("Error", error.getMessage()); } handler.validationError("PayRuns",object); } else { handler.execute(e); } } catch (IOException ioe) { throw ioe; } return null; }
Example 14
Source File: GerritApiTransportImpl.java From copybara with Apache License 2.0 | 5 votes |
@SuppressWarnings("unchecked") public static <T> T execute(Type responseType, HttpRequest httpRequest) throws IOException, GerritApiException { HttpResponse response; try { response = httpRequest.execute(); } catch (HttpResponseException e) { throw new GerritApiException(e.getStatusCode(), e.getContent(), e.getContent()); } return (T) response.parseAs(responseType); }
Example 15
Source File: ForceOAuthClient.java From salesforce-jdbc with MIT License | 5 votes |
private boolean isBadTokenError(HttpResponseException e) { return ((e.getStatusCode() == HttpStatusCodes.STATUS_CODE_FORBIDDEN) && StringUtils.equalsAnyIgnoreCase(e.getContent(), BAD_TOKEN_SF_ERROR_CODE, MISSING_TOKEN_SF_ERROR_CODE, WRONG_ORG_SF_ERROR_CODE)) || (e.getStatusCode() == HttpStatusCodes.STATUS_CODE_NOT_FOUND && StringUtils.equalsIgnoreCase(e.getContent(), BAD_ID_SF_ERROR_CODE)); }
Example 16
Source File: RemoteGoogleDriveConnector.java From cloudsync with GNU General Public License v2.0 | 5 votes |
private File _getDriveItem(final Item item) throws CloudsyncException, IOException { final String id = item.getRemoteIdentifier(); if (cacheFiles.containsKey(id)) { return cacheFiles.get(id); } File driveItem; try { driveItem = service.files().get(id).execute(); } catch (HttpResponseException e) { if (e.getStatusCode() == 404) { throw new CloudsyncException("Couldn't find remote item '" + item.getPath() + "' [" + id + "]\ntry to run with --nocache"); } throw e; } if (driveItem.getLabels().getTrashed()) { throw new CloudsyncException("Remote item '" + item.getPath() + "' [" + id + "] is trashed\ntry to run with --nocache"); } _addToCache(driveItem, null); return driveItem; }
Example 17
Source File: FirebaseErrorParsingUtils.java From zhcet-web with Apache License 2.0 | 5 votes |
/** * Checks if a firebase token is invalid by checking if it either expired or not forbidden * @param throwable Throwable of firebase execution error * @return TokenStatus denoting status of the token */ public static TokenStatus getTokenStatus(Throwable throwable) { Throwable current = throwable; while (!(current instanceof FirebaseMessagingException) && current != null) { current = current.getCause(); } if (current == null) throw new InvalidThrowableException(throwable); // We have a FirebaseMessagingException FirebaseMessagingException firebaseMessagingException = (FirebaseMessagingException) current; while (!(current instanceof HttpResponseException) && current != null) { current = current.getCause(); } if (current == null) throw new InvalidThrowableException(throwable); // We have a HttpResponseException HttpResponseException httpResponseException = (HttpResponseException) current; int statusCode = httpResponseException.getStatusCode(); Reason reason = new Reason(statusCode, current.getMessage(), httpResponseException.getContent()); boolean isTokenExpired = statusCode == 404 || statusCode == 400; boolean isTokenForbidden = statusCode == 403; if (isTokenExpired || isTokenForbidden) { return new TokenStatus(false, reason); } else { return new TokenStatus(true, reason); } }
Example 18
Source File: PushSubscriber.java From play-work with Apache License 2.0 | 4 votes |
/** * Verifies that the subscription with the name defined in settings file actually exists and * points to a correct topic defined in the same settings file. If the subscription doesn't * exist, it will be created. */ private static void ensureSubscriptionExists(Pubsub client) throws IOException { // First we check if the subscription with this name actually exists. Subscription subscription = null; String topicName = Settings.getSettings().getTopicName(); String subName = Settings.getSettings().getSubscriptionName(); LOG.info("Will be using topic name: " + topicName + ", subscription name: " + subName); try { LOG.info("Trying to get subscription named " + subName); subscription = client .projects() .subscriptions() .get(subName) .execute(); Preconditions.checkArgument( subscription.getTopic().equals(topicName), "Subscription %s already exists but points to a topic %s and not %s." + "Please specify a different subscription name or delete this subscription", subscription.getName(), subscription.getTopic(), topicName); LOG.info("Will be re-using existing subscription: " + subscription.toPrettyString()); } catch (HttpResponseException e) { // Subscription not found if (e.getStatusCode() == HttpStatusCodes.STATUS_CODE_NOT_FOUND) { LOG.info("Subscription doesn't exist, will try to create " + subName); // Creating subscription subscription = client .projects() .subscriptions() .create(subName, new Subscription() .setTopic(topicName) // Name of the topic it subscribes to .setAckDeadlineSeconds(600) .setPushConfig(new PushConfig() // FQDN with valid SSL certificate .setPushEndpoint(Settings.getSettings().getPushEndpoint()))) .execute(); LOG.info("Created: " + subscription.toPrettyString()); } } }
Example 19
Source File: ForceOAuthClient.java From salesforce-jdbc with MIT License | 4 votes |
private boolean isForceInternalError(HttpResponseException e) { return e.getStatusCode() == HttpStatusCodes.STATUS_CODE_NOT_FOUND && StringUtils.equalsIgnoreCase(e.getContent(), INTERNAL_SERVER_ERROR_SF_ERROR_CODE); }
Example 20
Source File: GcsConfigProvider.java From exhibitor with Apache License 2.0 | 4 votes |
private boolean isNotFoundError(HttpResponseException e) { return (e.getStatusCode() == HTTP_NOT_FOUND); }