private void delete(String url) { HttpHeaders headers = new HttpHeaders(); headers.setAccept("text/turtle"); headers.setCookie(authCookie); try { HttpRequest deleteRequest = factory.buildDeleteRequest(new GenericUrl(url)) .setThrowExceptionOnExecuteError(false); deleteRequest.setHeaders(headers); validateResponse(deleteRequest.execute(), 200); logger.debug("Deleted: {}", url); } catch (IOException e) { throw new IllegalStateException("Couldn't delete: " + url, e); } }
private String makeCall(HttpTransport transport) throws IOException { HttpRequest get = transport.createRequestFactory() .buildPostRequest(new GenericUrl(INRPUT_LOGIN_SERVER), null) .setFollowRedirects(false) .setThrowExceptionOnExecuteError(false); HttpResponse response = get.execute(); if (response.getStatusCode() != 302) { throw new IOException("Unexpected return code: " + response.getStatusCode() + "\nMessage:\n" + response.getStatusMessage()); } String cookieValue = response.getHeaders().getFirstHeaderStringValue("set-cookie"); if (Strings.isNullOrEmpty(cookieValue)) { throw new IOException("Couldn't extract cookie value from headers: " + response.getHeaders()); } return cookieValue; } }
/** Posts a new status for the user, initially marked as private.**/ public void postStatus(String content, String idempotencyKey) throws IOException { ImmutableMap<String, String> formParams = ImmutableMap.of( "status", content, // Default everything to private to avoid a privacy incident "visibility", "private" ); UrlEncodedContent urlEncodedContent = new UrlEncodedContent(formParams); HttpRequest postRequest = TRANSPORT.createRequestFactory() .buildPostRequest( new GenericUrl(baseUrl + POST_URL), urlEncodedContent) .setThrowExceptionOnExecuteError(false); HttpHeaders headers = new HttpHeaders(); headers.setAuthorization("Bearer " + accessToken); if (!Strings.isNullOrEmpty(idempotencyKey)) { // This prevents the same post from being posted twice in the case of network errors headers.set("Idempotency-Key", idempotencyKey); } postRequest.setHeaders(headers); HttpResponse response = postRequest.execute(); validateResponse(postRequest, response, 200); }
@Override public void initialize(HttpRequest request) throws IOException { request.setThrowExceptionOnExecuteError(false); credential.initialize(request); } };
HttpRequest request = getHttpRequestFactory().buildPostRequest(new GenericUrl(URL), content); request.setThrowExceptionOnExecuteError(false); HttpResponse response = request.execute(); switch(response.getStatusCode()) { case HttpStatusCodes.STATUS_CODE_UNAUTHORIZED: return new MyBaseResponse(responseBody); default: throw new RuntimeException("not implemented yet"); }
/** Sets attributes of the request that are common to all requests for this handler. */ @Override public void initialize(HttpRequest httpRequest) throws IOException { // Do not throw if execute fails, since Axis will handle unmarshalling the // fault. httpRequest.setThrowExceptionOnExecuteError(false); // For consistency with the default Axis HTTPSender and CommonsHTTPSender, do not // follow redirects. httpRequest.setFollowRedirects(false); // Retry should be handled by the client. httpRequest.setNumberOfRetries(0); }
/** Sets attributes of the request that are common to all requests for this handler. */ @Override public void initialize(HttpRequest httpRequest) throws IOException { // Do not throw if execute fails, since Axis will handle unmarshalling the // fault. httpRequest.setThrowExceptionOnExecuteError(false); // For consistency with the default Axis HTTPSender and CommonsHTTPSender, do not // follow redirects. httpRequest.setFollowRedirects(false); // Retry should be handled by the client. httpRequest.setNumberOfRetries(0); }
private HttpResponse executeHttpRequest(HttpRequest httpRequest) throws IOException { HttpResponse httpResponse = null; try { httpRequest.setThrowExceptionOnExecuteError(false); return httpResponse = httpRequest.execute(); } finally { if (httpResponse != null) { try { httpResponse.disconnect(); } catch (IOException e) { throw new JDriveSyncException(JDriveSyncException.Reason.IOException, "Failed to disconnect HTTP request: " + e.getMessage(), e); } } } } }
/** * Executes the current request with some minimal common code. * * @param request current request * @return HTTP response */ private HttpResponse executeCurrentRequestWithoutGZip(HttpRequest request) throws IOException { // method override for non-POST verbs new MethodOverride().intercept(request); // don't throw an exception so we can let a custom Google exception be thrown request.setThrowExceptionOnExecuteError(false); // execute the request HttpResponse response = request.execute(); return response; }
boolean originalThrowExceptionOnExecuteError = request.getThrowExceptionOnExecuteError(); if (originalThrowExceptionOnExecuteError) { request.setThrowExceptionOnExecuteError(false); request.setThrowExceptionOnExecuteError(originalThrowExceptionOnExecuteError); if (!originalThrowExceptionOnExecuteError || response.isSuccessStatusCode()) { return response;
/** Create a fake HTTP response object populated with the partContent and the statusCode. */ private HttpResponse getFakeResponse(final int statusCode, final InputStream partContent, List<String> headerNames, List<String> headerValues) throws IOException { HttpRequest request = new FakeResponseHttpTransport( statusCode, partContent, headerNames, headerValues).createRequestFactory() .buildPostRequest(new GenericUrl("http://google.com/"), null); request.setLoggingEnabled(false); request.setThrowExceptionOnExecuteError(false); return request.execute(); }
/** * Gets the report HTTP URL connection given report URL and proper information needed to * authenticate the request. * * @param reportUrl the URL of the report response or download * @return the report HTTP URL connection * @throws AuthenticationException If OAuth authorization fails. */ @VisibleForTesting HttpRequestFactory getHttpRequestFactory(final String reportUrl, String version) throws AuthenticationException { final HttpHeaders httpHeaders = createHeaders(reportUrl, version); return httpTransport.createRequestFactory( request -> { request.setHeaders(httpHeaders); request.setConnectTimeout(reportDownloadTimeout); request.setReadTimeout(reportDownloadTimeout); request.setThrowExceptionOnExecuteError(false); request.setLoggingEnabled(true); request.setResponseInterceptor(responseInterceptor); }); }
/** * Gets the report HTTP URL connection given report URL and proper information needed to * authenticate the request. * * @param reportUrl the URL of the report response or download * @return the report HTTP URL connection * @throws AuthenticationException If OAuth authorization fails. */ @VisibleForTesting HttpRequestFactory getHttpRequestFactory(final String reportUrl, String version) throws AuthenticationException { final HttpHeaders httpHeaders = createHeaders(reportUrl, version); return httpTransport.createRequestFactory( request -> { request.setHeaders(httpHeaders); request.setConnectTimeout(reportDownloadTimeout); request.setReadTimeout(reportDownloadTimeout); request.setThrowExceptionOnExecuteError(false); request.setLoggingEnabled(true); request.setResponseInterceptor(responseInterceptor); }); }
private HttpResponse getMetadataResponse(String url) throws IOException { GenericUrl genericUrl = new GenericUrl(url); HttpRequest request = transportFactory.create().createRequestFactory().buildGetRequest(genericUrl); JsonObjectParser parser = new JsonObjectParser(OAuth2Utils.JSON_FACTORY); request.setParser(parser); request.getHeaders().set("Metadata-Flavor", "Google"); request.setThrowExceptionOnExecuteError(false); HttpResponse response; try { response = request.execute(); } catch (UnknownHostException exception) { throw new IOException("ComputeEngineCredentials cannot find the metadata server. This is" + " likely because code is not running on Google Compute Engine.", exception); } return response; }
private HttpResponse getMetadataResponse(String url) throws IOException { GenericUrl genericUrl = new GenericUrl(url); HttpRequest request = transportFactory.create().createRequestFactory().buildGetRequest(genericUrl); JsonObjectParser parser = new JsonObjectParser(OAuth2Utils.JSON_FACTORY); request.setParser(parser); request.getHeaders().set("Metadata-Flavor", "Google"); request.setThrowExceptionOnExecuteError(false); HttpResponse response; try { response = request.execute(); } catch (UnknownHostException exception) { throw new IOException("ComputeEngineCredentials cannot find the metadata server. This is" + " likely because code is not running on Google Compute Engine.", exception); } return response; }
@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())); } }
MockJsonFactory mockJsonFactory = new MockJsonFactory(); HttpTransport transport = new MockHttpTransport() { @Override public LowLevelHttpRequest buildRequest(String method, String url) throws IOException { return new MockLowLevelHttpRequest() { @Override public LowLevelHttpResponse execute() throws IOException { MockLowLevelHttpResponse response = new MockLowLevelHttpResponse(); response.setStatusCode(408); response.setContent("{\"error\":\"Timeout\"}"); return response; } }; } }; HttpRequest httpRequest = transport.createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL); httpRequest.setThrowExceptionOnExecuteError(false); HttpResponse httpResponse = httpRequest.execute(); GoogleJsonResponseException googleJsonResponseException =
/** * Helper method that asserts that the proper report service logger calls are made for a response * with the specified status code and success status. */ private void testInterceptNonNullResponse(int statusCode) throws IOException { when(lowLevelResponse.getStatusCode()).thenReturn(statusCode); FakeHttpTransport httpTransport = new FakeHttpTransport(); HttpRequest request = httpTransport.createFakeRequestFactory().buildGetRequest(genericUrl); request.setThrowExceptionOnExecuteError(false); HttpResponse response = request.execute(); assertNotNull("Fake transport should have returned a non-null response", response); // Verifies that the expected report service logger call is made. verify(reportServiceLogger).logRequest(request, response.getStatusCode(), response.getStatusMessage()); // Verifies that the interceptor does not try to consume or mutate the response's // input stream, as this would be a violation of the HttpResponseInterceptor contract. verifyZeroInteractions(responseContentStream); }
HttpRequest otherRequest = otherTransport .createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL); otherRequest.setThrowExceptionOnExecuteError(false); HttpResponse otherServiceUnavailableResponse = otherRequest.execute(); return GoogleJsonResponseException.from(jsonFactory, otherServiceUnavailableResponse);
HttpRequest request = transport.createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL); request.setThrowExceptionOnExecuteError(false); HttpResponse response = request.execute(); return GoogleJsonResponseException.from(jsonFactory, response);