com.google.api.client.http.HttpStatusCodes Java Examples
The following examples show how to use
com.google.api.client.http.HttpStatusCodes.
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: DefaultCredentialProviderTest.java From google-api-java-client with Apache License 2.0 | 6 votes |
public void testDefaultCredentialComputeErrorNotFound() throws IOException { MockMetadataServerTransport transport = new MockMetadataServerTransport(ACCESS_TOKEN); transport.setTokenRequestStatusCode(HttpStatusCodes.STATUS_CODE_NOT_FOUND); TestDefaultCredentialProvider testProvider = new TestDefaultCredentialProvider(); Credential defaultCredential = testProvider.getDefaultCredential(transport, JSON_FACTORY); assertNotNull(defaultCredential); try { defaultCredential.refreshToken(); fail("Expected error refreshing token."); } catch (IOException expected) { String message = expected.getMessage(); assertTrue(message.contains(Integer.toString(HttpStatusCodes.STATUS_CODE_NOT_FOUND))); assertTrue(message.contains("scope")); } }
Example #2
Source File: HelloSpanner.java From java-docs-samples with Apache License 2.0 | 6 votes |
@Override public void service(HttpRequest request, HttpResponse response) throws Exception { var writer = new PrintWriter(response.getWriter()); try { DatabaseClient client = getClient(); try (ResultSet rs = client .singleUse() .executeQuery(Statement.of("SELECT SingerId, AlbumId, AlbumTitle FROM Albums"))) { writer.printf("Albums:%n"); while (rs.next()) { writer.printf( "%d %d %s%n", rs.getLong("SingerId"), rs.getLong("AlbumId"), rs.getString("AlbumTitle")); } } catch (SpannerException e) { writer.printf("Error querying database: %s%n", e.getMessage()); response.setStatusCode(HttpStatusCodes.STATUS_CODE_SERVER_ERROR, e.getMessage()); } } catch (Throwable t) { logger.log(Level.SEVERE, "Spanner example failed", t); writer.printf("Error setting up Spanner: %s%n", t.getMessage()); response.setStatusCode(HttpStatusCodes.STATUS_CODE_SERVER_ERROR, t.getMessage()); } }
Example #3
Source File: BqClient.java From digdag with Apache License 2.0 | 6 votes |
void createDataset(String projectId, Dataset dataset) throws IOException { try { client.datasets().insert(projectId, dataset) .execute(); } catch (GoogleJsonResponseException e) { if (e.getStatusCode() == HttpStatusCodes.STATUS_CODE_CONFLICT) { logger.debug("Dataset already exists: {}:{}", dataset.getDatasetReference()); } else { throw e; } } }
Example #4
Source File: InitServlet.java From cloud-pubsub-samples-java with Apache License 2.0 | 6 votes |
/** * Creates a Cloud Pub/Sub topic if it doesn't exist. * * @param client Pubsub client object. * @throws IOException when API calls to Cloud Pub/Sub fails. */ private void setupTopic(final Pubsub client) throws IOException { String fullName = String.format("projects/%s/topics/%s", PubsubUtils.getProjectId(), PubsubUtils.getAppTopicName()); try { client.projects().topics().get(fullName).execute(); } catch (GoogleJsonResponseException e) { if (e.getStatusCode() == HttpStatusCodes.STATUS_CODE_NOT_FOUND) { // Create the topic if it doesn't exist client.projects().topics() .create(fullName, new Topic()) .execute(); } else { throw e; } } }
Example #5
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 #6
Source File: BqClient.java From digdag with Apache License 2.0 | 6 votes |
void createTable(String projectId, Table table) throws IOException { String datasetId = table.getTableReference().getDatasetId(); try { client.tables().insert(projectId, datasetId, table) .execute(); } catch (GoogleJsonResponseException e) { if (e.getStatusCode() == HttpStatusCodes.STATUS_CODE_CONFLICT) { logger.debug("Table already exists: {}:{}.{}", projectId, datasetId, table.getTableReference().getTableId()); } else { throw e; } } }
Example #7
Source File: GoogleCloudStorageTest.java From hadoop-connectors with Apache License 2.0 | 6 votes |
/** Test successful operation of GoogleCloudStorage.delete(2) with generationId. */ @Test public void testDeleteObjectWithGenerationId() throws IOException { int generationId = 65; MockHttpTransport transport = mockTransport(emptyResponse(HttpStatusCodes.STATUS_CODE_NO_CONTENT)); GoogleCloudStorage gcs = mockedGcs(transport); gcs.deleteObjects( ImmutableList.of(new StorageResourceId(BUCKET_NAME, OBJECT_NAME, generationId))); assertThat(trackingHttpRequestInitializer.getAllRequestStrings()) .containsExactly( deleteRequestString( BUCKET_NAME, OBJECT_NAME, generationId, /* replaceGenerationId= */ false)) .inOrder(); }
Example #8
Source File: ApiErrorExtractorTest.java From hadoop-connectors with Apache License 2.0 | 6 votes |
@Before public void setUp() throws Exception { accessDenied = googleJsonResponseException( HttpStatusCodes.STATUS_CODE_FORBIDDEN, "Forbidden", "Forbidden"); statusOk = googleJsonResponseException(HttpStatusCodes.STATUS_CODE_OK, "A reason", "ok"); notFound = googleJsonResponseException( HttpStatusCodes.STATUS_CODE_NOT_FOUND, "Not found", "Not found"); badRange = googleJsonResponseException( ApiErrorExtractor.STATUS_CODE_RANGE_NOT_SATISFIABLE, "Bad range", "Bad range"); alreadyExists = googleJsonResponseException(409, "409", "409"); resourceNotReady = googleJsonResponseException( 400, ApiErrorExtractor.RESOURCE_NOT_READY_REASON, "Resource not ready"); // This works because googleJsonResponseException takes final ErrorInfo ErrorInfo errorInfo = new ErrorInfo(); errorInfo.setReason(ApiErrorExtractor.RATE_LIMITED_REASON); notRateLimited = googleJsonResponseException(POSSIBLE_RATE_LIMIT, errorInfo, ""); errorInfo.setDomain(ApiErrorExtractor.USAGE_LIMITS_DOMAIN); rateLimited = googleJsonResponseException(POSSIBLE_RATE_LIMIT, errorInfo, ""); errorInfo.setDomain(ApiErrorExtractor.GLOBAL_DOMAIN); bigqueryRateLimited = googleJsonResponseException(POSSIBLE_RATE_LIMIT, errorInfo, ""); }
Example #9
Source File: ReportServiceLogger.java From googleads-java-lib with Apache License 2.0 | 6 votes |
/** * Logs the specified request and response information. * * <p>Note that in order to avoid any temptation to consume the contents of the response, this * does <em>not</em> take an {@link com.google.api.client.http.HttpResponse} object, but instead * accepts the status code and message from the response. */ public void logRequest( @Nullable HttpRequest request, int statusCode, @Nullable String statusMessage) { boolean isSuccess = HttpStatusCodes.isSuccess(statusCode); if (!loggerDelegate.isSummaryLoggable(isSuccess) && !loggerDelegate.isDetailsLoggable(isSuccess)) { return; } // Populate the RequestInfo builder from the request. RequestInfo requestInfo = buildRequestInfo(request); // Populate the ResponseInfo builder from the response. ResponseInfo responseInfo = buildResponseInfo(request, statusCode, statusMessage); RemoteCallReturn.Builder remoteCallReturnBuilder = new RemoteCallReturn.Builder().withRequestInfo(requestInfo).withResponseInfo(responseInfo); if (!isSuccess) { remoteCallReturnBuilder.withException( new ReportException(String.format("%s: %s", statusCode, statusMessage))); } RemoteCallReturn remoteCallReturn = remoteCallReturnBuilder.build(); loggerDelegate.logRequestSummary(remoteCallReturn); loggerDelegate.logRequestDetails(remoteCallReturn); }
Example #10
Source File: GcsUtilTest.java From beam with Apache License 2.0 | 6 votes |
@Test public void testNonExistentObjectReturnsEmptyResult() throws IOException { GcsOptions pipelineOptions = gcsOptionsWithTestCredential(); GcsUtil gcsUtil = pipelineOptions.getGcsUtil(); Storage mockStorage = Mockito.mock(Storage.class); gcsUtil.setStorageClient(mockStorage); Storage.Objects mockStorageObjects = Mockito.mock(Storage.Objects.class); Storage.Objects.Get mockStorageGet = Mockito.mock(Storage.Objects.Get.class); GcsPath pattern = GcsPath.fromUri("gs://testbucket/testdirectory/nonexistentfile"); GoogleJsonResponseException expectedException = googleJsonResponseException( HttpStatusCodes.STATUS_CODE_NOT_FOUND, "It don't exist", "Nothing here to see"); when(mockStorage.objects()).thenReturn(mockStorageObjects); when(mockStorageObjects.get(pattern.getBucket(), pattern.getObject())) .thenReturn(mockStorageGet); when(mockStorageGet.execute()).thenThrow(expectedException); assertEquals(Collections.emptyList(), gcsUtil.expand(pattern)); }
Example #11
Source File: GcsUtilTest.java From beam with Apache License 2.0 | 6 votes |
@Test public void testBucketDoesNotExist() throws IOException { GcsOptions pipelineOptions = gcsOptionsWithTestCredential(); GcsUtil gcsUtil = pipelineOptions.getGcsUtil(); Storage mockStorage = Mockito.mock(Storage.class); gcsUtil.setStorageClient(mockStorage); Storage.Buckets mockStorageObjects = Mockito.mock(Storage.Buckets.class); Storage.Buckets.Get mockStorageGet = Mockito.mock(Storage.Buckets.Get.class); BackOff mockBackOff = BackOffAdapter.toGcpBackOff(FluentBackoff.DEFAULT.backoff()); when(mockStorage.buckets()).thenReturn(mockStorageObjects); when(mockStorageObjects.get("testbucket")).thenReturn(mockStorageGet); when(mockStorageGet.execute()) .thenThrow( googleJsonResponseException( HttpStatusCodes.STATUS_CODE_NOT_FOUND, "It don't exist", "Nothing here to see")); assertFalse( gcsUtil.bucketAccessible( GcsPath.fromComponents("testbucket", "testobject"), mockBackOff, new FastNanoClockAndSleeper())); }
Example #12
Source File: GcsUtilTest.java From beam with Apache License 2.0 | 6 votes |
@Test public void testFileSizeWhenFileNotFoundNonBatch() throws Exception { MockLowLevelHttpResponse notFoundResponse = new MockLowLevelHttpResponse(); notFoundResponse.setContent(""); notFoundResponse.setStatusCode(HttpStatusCodes.STATUS_CODE_NOT_FOUND); MockHttpTransport mockTransport = new MockHttpTransport.Builder().setLowLevelHttpResponse(notFoundResponse).build(); GcsOptions pipelineOptions = gcsOptionsWithTestCredential(); GcsUtil gcsUtil = pipelineOptions.getGcsUtil(); gcsUtil.setStorageClient(new Storage(mockTransport, Transport.getJsonFactory(), null)); thrown.expect(FileNotFoundException.class); gcsUtil.fileSize(GcsPath.fromComponents("testbucket", "testobject")); }
Example #13
Source File: DefaultCredentialProviderTest.java From google-api-java-client with Apache License 2.0 | 6 votes |
public void testDefaultCredentialComputeErrorUnexpected() throws IOException { MockMetadataServerTransport transport = new MockMetadataServerTransport(ACCESS_TOKEN); transport.setTokenRequestStatusCode(HttpStatusCodes.STATUS_CODE_SERVER_ERROR); TestDefaultCredentialProvider testProvider = new TestDefaultCredentialProvider(); Credential defaultCredential = testProvider.getDefaultCredential(transport, JSON_FACTORY); assertNotNull(defaultCredential); try { defaultCredential.refreshToken(); fail("Expected error refreshing token."); } catch (IOException expected) { String message = expected.getMessage(); assertTrue(message.contains(Integer.toString(HttpStatusCodes.STATUS_CODE_SERVER_ERROR))); assertTrue(message.contains("Unexpected")); } }
Example #14
Source File: CStoreServiceTest.java From healthcare-dicom-dicomweb-adapter with Apache License 2.0 | 5 votes |
@Test public void testCStoreService_connectionError() throws Exception { basicCStoreServiceTest( true, HttpStatusCodes.STATUS_CODE_OK, // won't be returned due to connectionError Status.ProcessingFailure); }
Example #15
Source File: ApiErrorExtractorTest.java From hadoop-connectors with Apache License 2.0 | 5 votes |
@Test public void isClientError_GoogleJsonErrorWithStatusBadGatewayReturnFalse() throws IOException { IOException withJsonError = googleJsonResponseException( HttpStatusCodes.STATUS_CODE_BAD_GATEWAY, "Bad gateway", "Bad gateway", "Bad gateway"); assertThat(errorExtractor.clientError(withJsonError)).isFalse(); }
Example #16
Source File: ApiErrorExtractorTest.java From hadoop-connectors with Apache License 2.0 | 5 votes |
@Test public void accessDeniedNonRecoverable_GoogleJsonErrorWithAccessNotConfiguredReturnTrue() throws IOException { IOException withJsonError = googleJsonResponseException( HttpStatusCodes.STATUS_CODE_FORBIDDEN, ApiErrorExtractor.ACCESS_NOT_CONFIGURED_REASON, "Forbidden", "Forbidden"); assertThat(errorExtractor.accessDeniedNonRecoverable(withJsonError)).isTrue(); }
Example #17
Source File: ApiErrorExtractorTest.java From hadoop-connectors with Apache License 2.0 | 5 votes |
@Test public void isInternalServerError_GoogleJsonErrorWithStatusBadGatewayReturnTrue() throws IOException { IOException withJsonError = googleJsonResponseException( HttpStatusCodes.STATUS_CODE_BAD_GATEWAY, "Bad gateway", "Bad gateway", "Bad gateway"); assertThat(errorExtractor.internalServerError(withJsonError)).isTrue(); }
Example #18
Source File: ApiErrorExtractorTest.java From hadoop-connectors with Apache License 2.0 | 5 votes |
/** Validates itemNotFound(). */ @Test public void testItemNotFound() { // Check success cases. assertThat(errorExtractor.itemNotFound(notFound)).isTrue(); GoogleJsonError gje = new GoogleJsonError(); gje.setCode(HttpStatusCodes.STATUS_CODE_NOT_FOUND); assertThat(errorExtractor.itemNotFound(new IOException(notFound))).isTrue(); assertThat(errorExtractor.itemNotFound(new IOException(new IOException(notFound)))).isTrue(); // Check failure case. assertThat(errorExtractor.itemNotFound(statusOk)).isFalse(); assertThat(errorExtractor.itemNotFound(new IOException())).isFalse(); assertThat(errorExtractor.itemNotFound(new IOException(new IOException()))).isFalse(); }
Example #19
Source File: RetryHttpInitializer.java From hadoop-connectors with Apache License 2.0 | 5 votes |
@Override public boolean handleResponse(HttpRequest request, HttpResponse response, boolean supportsRetry) throws IOException { if (credential.handleResponse(request, response, supportsRetry)) { // If credential decides it can handle it, the return code or message indicated something // specific to authentication, and no backoff is desired. return true; } if (delegateHandler.handleResponse(request, response, supportsRetry)) { // Otherwise, we defer to the judgement of our internal backoff handler. return true; } if (HttpStatusCodes.isRedirect(response.getStatusCode()) && request.getFollowRedirects() && response.getHeaders() != null && response.getHeaders().getLocation() != null) { // Hack: Reach in and fix any '+' in the URL but still report 'false'. The client library // incorrectly tries to decode '+' into ' ', even though the backend servers treat '+' // as a legitimate path character, and so do not encode it. This is safe to do whether // or not the client library fixes the bug, since %2B will correctly be decoded as '+' // even after the fix. String redirectLocation = response.getHeaders().getLocation(); if (redirectLocation.contains("+")) { String escapedLocation = redirectLocation.replace("+", "%2B"); logger.atFine().log( "Redirect path '%s' contains unescaped '+', replacing with '%%2B': '%s'", redirectLocation, escapedLocation); response.getHeaders().setLocation(escapedLocation); } } return false; }
Example #20
Source File: DefaultCredentialProvider.java From google-api-java-client with Apache License 2.0 | 5 votes |
@Override protected TokenResponse executeRefreshToken() throws IOException { GenericUrl tokenUrl = new GenericUrl(getTokenServerEncodedUrl()); HttpRequest request = getTransport().createRequestFactory().buildGetRequest(tokenUrl); JsonObjectParser parser = new JsonObjectParser(getJsonFactory()); request.setParser(parser); request.getHeaders().set("Metadata-Flavor", "Google"); request.setThrowExceptionOnExecuteError(false); HttpResponse response = request.execute(); int statusCode = response.getStatusCode(); if (statusCode == HttpStatusCodes.STATUS_CODE_OK) { InputStream content = response.getContent(); if (content == null) { // Throw explicitly rather than allow a later null reference as default mock // transports return success codes with empty contents. throw new IOException("Empty content from metadata token server request."); } return parser.parseAndClose(content, response.getContentCharset(), TokenResponse.class); } if (statusCode == HttpStatusCodes.STATUS_CODE_NOT_FOUND) { throw new IOException(String.format("Error code %s trying to get security access token from" + " Compute Engine metadata for the default service account. This may be because" + " the virtual machine instance does not have permission scopes specified.", statusCode)); } throw new IOException(String.format("Unexpected Error code %s trying to get security access" + " token from Compute Engine metadata for the default service account: %s", statusCode, response.parseAsString())); }
Example #21
Source File: GcpUtil.java From digdag with Apache License 2.0 | 5 votes |
static boolean datasetExists(Bigquery bq, String projectId, String datasetId) throws IOException { try { bq.datasets().get(projectId, datasetId).execute(); return true; } catch (GoogleJsonResponseException e) { if (e.getStatusCode() == HttpStatusCodes.STATUS_CODE_NOT_FOUND) { return false; } throw e; } }
Example #22
Source File: TaskQueueNotificationServlet.java From abelana with Apache License 2.0 | 5 votes |
@Override public final void doPost(final HttpServletRequest req, final HttpServletResponse resp) throws IOException { HttpTransport httpTransport; try { Map<Object, Object> params = new HashMap<>(); params.putAll(req.getParameterMap()); params.put("task", req.getHeader("X-AppEngine-TaskName")); httpTransport = GoogleNetHttpTransport.newTrustedTransport(); GoogleCredential credential = GoogleCredential.getApplicationDefault() .createScoped(Collections.singleton("https://www.googleapis.com/auth/userinfo.email")); HttpRequestFactory requestFactory = httpTransport.createRequestFactory(); GenericUrl url = new GenericUrl(ConfigurationConstants.IMAGE_RESIZER_URL); HttpRequest request = requestFactory.buildPostRequest(url, new UrlEncodedContent(params)); credential.initialize(request); HttpResponse response = request.execute(); if (!response.isSuccessStatusCode()) { log("Call to the imageresizer failed: " + response.getContent().toString()); resp.setStatus(HttpStatusCodes.STATUS_CODE_SERVER_ERROR); } else { resp.setStatus(response.getStatusCode()); } } catch (GeneralSecurityException | IOException e) { log("Http request error: " + e.getMessage()); resp.setStatus(HttpStatusCodes.STATUS_CODE_SERVER_ERROR); } }
Example #23
Source File: OAuthHmacCredential.java From android-oauth-client with Apache License 2.0 | 5 votes |
@Override public boolean handleResponse(HttpRequest request, HttpResponse response, boolean supportsRetry) { if (response.getStatusCode() == HttpStatusCodes.STATUS_CODE_UNAUTHORIZED) { // If the token was revoked, we must mark our credential as invalid setAccessToken(null); } // We didn't do anything to fix the problem return false; }
Example #24
Source File: AbstractGoogleJsonClientTest.java From google-api-java-client with Apache License 2.0 | 5 votes |
public void testExecuteUnparsed_error() throws Exception { HttpTransport transport = new MockHttpTransport() { @Override public LowLevelHttpRequest buildRequest(String name, String url) { return new MockLowLevelHttpRequest() { @Override public LowLevelHttpResponse execute() { MockLowLevelHttpResponse result = new MockLowLevelHttpResponse(); result.setStatusCode(HttpStatusCodes.STATUS_CODE_UNAUTHORIZED); result.setContentType(Json.MEDIA_TYPE); result.setContent("{\"error\":{\"code\":401,\"errors\":[{\"domain\":\"global\"," + "\"location\":\"Authorization\",\"locationType\":\"header\"," + "\"message\":\"me\",\"reason\":\"authError\"}],\"message\":\"me\"}}"); return result; } }; } }; JsonFactory jsonFactory = new JacksonFactory(); MockGoogleJsonClient client = new MockGoogleJsonClient.Builder( transport, jsonFactory, HttpTesting.SIMPLE_URL, "", null, false).setApplicationName( "Test Application").build(); MockGoogleJsonClientRequest<String> request = new MockGoogleJsonClientRequest<String>(client, "GET", "foo", null, String.class); try { request.executeUnparsed(); fail("expected " + GoogleJsonResponseException.class); } catch (GoogleJsonResponseException e) { // expected GoogleJsonError details = e.getDetails(); assertEquals("me", details.getMessage()); assertEquals("me", details.getErrors().get(0).getMessage()); } }
Example #25
Source File: BqClient.java From digdag with Apache License 2.0 | 5 votes |
void deleteTable(String projectId, String datasetId, String tableId) throws IOException { try { client.tables().delete(projectId, datasetId, tableId).execute(); } catch (GoogleJsonResponseException e) { if (e.getStatusCode() == HttpStatusCodes.STATUS_CODE_NOT_FOUND) { // Already deleted return; } throw e; } }
Example #26
Source File: GcpUtil.java From digdag with Apache License 2.0 | 5 votes |
static boolean tableExists(Bigquery bq, String projectId, String datasetId, String tableId) throws IOException { try { bq.tables().get(projectId, datasetId, tableId).execute(); return true; } catch (GoogleJsonResponseException e) { if (e.getStatusCode() == HttpStatusCodes.STATUS_CODE_NOT_FOUND) { return false; } throw e; } }
Example #27
Source File: ReportServiceLoggerTest.java From googleads-java-lib with Apache License 2.0 | 5 votes |
@Test public void testBuildInfos_success() { RequestInfo requestInfo = reportServiceLogger.buildRequestInfo(httpRequest); checkRequestInfoAttributes(requestInfo, true); ResponseInfo responseInfo = reportServiceLogger.buildResponseInfo(httpRequest, HttpStatusCodes.STATUS_CODE_OK, null); checkResponseInfoAttributes(responseInfo, HttpStatusCodes.STATUS_CODE_OK, null); }
Example #28
Source File: RestrictedDomainFilter.java From tech-gallery with Apache License 2.0 | 5 votes |
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { // Throws 401 when RestrictedDomainException is handled.. try { chain.doFilter(request, response); } catch (RestrictedDomainException e) { log.log(Level.WARNING, e.getMessage(), e); response.getWriter().print(e.getMessage()); ((HttpServletResponse) response).setStatus(HttpStatusCodes.STATUS_CODE_UNAUTHORIZED); } }
Example #29
Source File: Authorization.java From DisCal-Discord-Bot with GNU Lesser General Public License v3.0 | 5 votes |
public String requestNewAccessToken(GuildSettings settings, AESEncryption encryption) { try { RequestBody body = new FormBody.Builder() .addEncoded("client_id", clientData.getClientId()) .addEncoded("client_secret", clientData.getClientSecret()) .addEncoded("refresh_token", encryption.decrypt(settings.getEncryptedRefreshToken())) .addEncoded("grant_type", "refresh_token") .build(); Request httpRequest = new okhttp3.Request.Builder() .url("https://www.googleapis.com/oauth2/v4/token") .post(body) .header("Content-Type", "application/x-www-form-urlencoded") .build(); Response httpResponse = client.newCall(httpRequest).execute(); if (httpResponse.code() == HttpStatusCodes.STATUS_CODE_OK) { JSONObject autoRefreshResponse = new JSONObject(httpResponse.body().string()); //Update Db data. settings.setEncryptedAccessToken(encryption.encrypt(autoRefreshResponse.getString("access_token"))); DatabaseManager.getManager().updateSettings(settings); //Okay, we can return the access token to be used when this method is called. return autoRefreshResponse.getString("access_token"); } else { //Failed to get OK. Send debug info. Logger.getLogger().debug(null, "Error requesting new access token.", "Status code: " + httpResponse.code() + " | " + httpResponse.message() + " | " + httpResponse.body().string(), true, this.getClass()); return null; } } catch (Exception e) { //Error occurred, lets just log it and return null. Logger.getLogger().exception(null, "Failed to request new access token.", e, true, this.getClass()); return null; } }
Example #30
Source File: GcsUtilTest.java From beam with Apache License 2.0 | 5 votes |
@Test public void testBucketDoesNotExistBecauseOfAccessError() throws IOException { GcsOptions pipelineOptions = gcsOptionsWithTestCredential(); GcsUtil gcsUtil = pipelineOptions.getGcsUtil(); Storage mockStorage = Mockito.mock(Storage.class); gcsUtil.setStorageClient(mockStorage); Storage.Buckets mockStorageObjects = Mockito.mock(Storage.Buckets.class); Storage.Buckets.Get mockStorageGet = Mockito.mock(Storage.Buckets.Get.class); BackOff mockBackOff = BackOffAdapter.toGcpBackOff(FluentBackoff.DEFAULT.backoff()); GoogleJsonResponseException expectedException = googleJsonResponseException( HttpStatusCodes.STATUS_CODE_FORBIDDEN, "Waves hand mysteriously", "These aren't the buckets you're looking for"); when(mockStorage.buckets()).thenReturn(mockStorageObjects); when(mockStorageObjects.get("testbucket")).thenReturn(mockStorageGet); when(mockStorageGet.execute()).thenThrow(expectedException); assertFalse( gcsUtil.bucketAccessible( GcsPath.fromComponents("testbucket", "testobject"), mockBackOff, new FastNanoClockAndSleeper())); }