com.google.api.client.http.HttpRequest Java Examples

The following examples show how to use com.google.api.client.http.HttpRequest. 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 Project: firebase-admin-java   Author: firebase   File: FirebaseRequestInitializerTest.java    License: Apache License 2.0 8 votes vote down vote up
@Test
public void testCredentialsRetryHandler() throws Exception {
  FirebaseApp app = FirebaseApp.initializeApp(new FirebaseOptions.Builder()
      .setCredentials(new MockGoogleCredentials("token"))
      .build());
  RetryConfig retryConfig = RetryConfig.builder()
      .setMaxRetries(MAX_RETRIES)
      .build();
  CountingLowLevelHttpRequest countingRequest = CountingLowLevelHttpRequest.fromStatus(401);
  HttpRequest request = TestUtils.createRequest(countingRequest);
  FirebaseRequestInitializer initializer = new FirebaseRequestInitializer(app, retryConfig);
  initializer.initialize(request);
  request.getHeaders().setAuthorization((String) null);

  try {
    request.execute();
  } catch (HttpResponseException e) {
    assertEquals(401, e.getStatusCode());
  }

  assertEquals("Bearer token", request.getHeaders().getAuthorization());
  assertEquals(MAX_RETRIES + 1, countingRequest.getCount());
}
 
Example #2
Source Project: endpoints-java   Author: cloudendpoints   File: GoogleAuth.java    License: Apache License 2.0 6 votes vote down vote up
@VisibleForTesting
static TokenInfo parseTokenInfo(HttpRequest request)
    throws IOException, ServiceUnavailableException {
  HttpResponse response = request.execute();
  int statusCode = response.getStatusCode();
  TokenInfo info = response.parseAs(TokenInfo.class);
  if (statusCode != 200) {
    String errorDescription = "Unknown error";
    if (info != null && info.errorDescription != null) {
      errorDescription = info.errorDescription;
    }
    errorDescription += " (" + statusCode + ")";
    if (statusCode >= 500) {
      logger.atSevere().log("Error validating access token: %s", errorDescription);
      throw new ServiceUnavailableException("Failed to validate access token");
    }
    logger.atInfo().log("Invalid access token: %s", errorDescription);
    return null;
  }
  if (info == null || Strings.isEmptyOrWhitespace(info.email)) {
    logger.atWarning().log("Access token does not contain email scope");
    return null;
  }
  return info;
}
 
Example #3
Source Project: google-oauth-java-client   Author: googleapis   File: Credential.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 * <p>
 * Default implementation is to try to refresh the access token if there is no access token or if
 * we are 1 minute away from expiration. If token server is unavailable, it will try to use the
 * access token even if has expired. If a 4xx error is encountered while refreshing the token,
 * {@link TokenResponseException} is thrown. If successful, it will call {@link #getMethod()} and
 * {@link AccessMethod#intercept}.
 * </p>
 *
 * <p>
 * Subclasses may override.
 * </p>
 */
public void intercept(HttpRequest request) throws IOException {
  lock.lock();
  try {
    Long expiresIn = getExpiresInSeconds();
    // check if token will expire in a minute
    if (accessToken == null || expiresIn != null && expiresIn <= 60) {
      refreshToken();
      if (accessToken == null) {
        // nothing we can do without an access token
        return;
      }
    }
    method.intercept(request, accessToken);
  } finally {
    lock.unlock();
  }
}
 
Example #4
Source Project: nomulus   Author: google   File: DirectoryGroupsConnectionTest.java    License: Apache License 2.0 6 votes vote down vote up
/** Returns a valid GoogleJsonResponseException for the given status code and error message.  */
private GoogleJsonResponseException makeResponseException(
    final int statusCode,
    final String message) throws Exception {
  HttpTransport transport = new MockHttpTransport() {
    @Override
    public LowLevelHttpRequest buildRequest(String method, String url) {
      return new MockLowLevelHttpRequest() {
        @Override
        public LowLevelHttpResponse execute() {
          MockLowLevelHttpResponse response = new MockLowLevelHttpResponse();
          response.setStatusCode(statusCode);
          response.setContentType(Json.MEDIA_TYPE);
          response.setContent(String.format(
              "{\"error\":{\"code\":%d,\"message\":\"%s\",\"domain\":\"global\","
              + "\"reason\":\"duplicate\"}}",
              statusCode,
              message));
          return response;
        }};
    }};
  HttpRequest request = transport.createRequestFactory()
      .buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL)
      .setThrowExceptionOnExecuteError(false);
  return GoogleJsonResponseException.from(new JacksonFactory(), request.execute());
}
 
Example #5
Source Project: beam   Author: apache   File: RetryHttpInitializerWrapper.java    License: Apache License 2.0 6 votes vote down vote up
/** Initializes the given request. */
@Override
public final void initialize(final HttpRequest request) {
  request.setReadTimeout(2 * ONEMINITUES); // 2 minutes read timeout
  final HttpUnsuccessfulResponseHandler backoffHandler =
      new HttpBackOffUnsuccessfulResponseHandler(new ExponentialBackOff()).setSleeper(sleeper);
  request.setInterceptor(wrappedCredential);
  request.setUnsuccessfulResponseHandler(
      (request1, response, supportsRetry) -> {
        if (wrappedCredential.handleResponse(request1, 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;
        } else if (backoffHandler.handleResponse(request1, response, supportsRetry)) {
          // Otherwise, we defer to the judgement of our internal backoff handler.
          LOG.info("Retrying " + request1.getUrl().toString());
          return true;
        } else {
          return false;
        }
      });
  request.setIOExceptionHandler(
      new HttpBackOffIOExceptionHandler(new ExponentialBackOff()).setSleeper(sleeper));
}
 
Example #6
Source Project: data-transfer-project   Author: google   File: SslHelper.java    License: Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #7
Source Project: android-oauth-client   Author: wuman   File: AuthorizationFlow.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public AuthorizationCodeTokenRequest newTokenRequest(String authorizationCode) {
    return new LenientAuthorizationCodeTokenRequest(getTransport(), getJsonFactory(),
            new GenericUrl(getTokenServerEncodedUrl()), authorizationCode)
            .setClientAuthentication(getClientAuthentication())
            .setScopes(getScopes())
            .setRequestInitializer(
                    new HttpRequestInitializer() {
                        @Override
                        public void initialize(HttpRequest request) throws IOException {
                            HttpRequestInitializer requestInitializer = getRequestInitializer();
                            // If HttpRequestInitializer is set, initialize it as before
                            if (requestInitializer != null) {
                                requestInitializer.initialize(request);
                            }
                            // Also set JSON accept header
                            request.getHeaders().setAccept("application/json");
                        }
                    });
}
 
Example #8
Source Project: firebase-admin-java   Author: firebase   File: RetryUnsuccessfulResponseHandlerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testDoesNotRetryWhenRetryAfterIsTooLong() throws IOException {
  MultipleCallSleeper sleeper = new MultipleCallSleeper();
  RetryUnsuccessfulResponseHandler handler = new RetryUnsuccessfulResponseHandler(
      testRetryConfig(sleeper));
  CountingLowLevelHttpRequest failingRequest = CountingLowLevelHttpRequest.fromStatus(
      503, ImmutableMap.of("retry-after", "121"));
  HttpRequest request = TestUtils.createRequest(failingRequest);
  request.setUnsuccessfulResponseHandler(handler);
  request.setNumberOfRetries(MAX_RETRIES);

  try {
    request.execute();
    fail("No exception thrown for HTTP error");
  } catch (HttpResponseException e) {
    assertEquals(503, e.getStatusCode());
  }

  assertEquals(0, sleeper.getCount());
  assertEquals(1, failingRequest.getCount());
}
 
Example #9
Source Project: endpoints-java   Author: cloudendpoints   File: GoogleAuthTest.java    License: Apache License 2.0 6 votes vote down vote up
private HttpRequest constructHttpRequest(final String content, final int statusCode) throws IOException {
  HttpTransport transport = new MockHttpTransport() {
    @Override
    public LowLevelHttpRequest buildRequest(String method, String url) throws IOException {
      return new MockLowLevelHttpRequest() {
        @Override
        public LowLevelHttpResponse execute() throws IOException {
          MockLowLevelHttpResponse result = new MockLowLevelHttpResponse();
          result.setContentType("application/json");
          result.setContent(content);
          result.setStatusCode(statusCode);
          return result;
        }
      };
    }
  };
  HttpRequest httpRequest = transport.createRequestFactory().buildGetRequest(new GenericUrl("https://google.com")).setParser(new JsonObjectParser(new JacksonFactory()));
  GoogleAuth.configureErrorHandling(httpRequest);
  return httpRequest;
}
 
Example #10
Source Project: java-docs-samples   Author: GoogleCloudPlatform   File: StorageSample.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Fetches the listing of the given bucket.
 *
 * @param bucketName the name of the bucket to list.
 * @return the raw XML containing the listing of the bucket.
 * @throws IOException if there's an error communicating with Cloud Storage.
 * @throws GeneralSecurityException for errors creating https connection.
 */
public static String listBucket(final String bucketName)
    throws IOException, GeneralSecurityException {
  // [START snippet]
  // Build an account credential.
  GoogleCredentials credential =
      GoogleCredentials.getApplicationDefault()
          .createScoped(Collections.singleton(STORAGE_SCOPE));

  // Set up and execute a Google Cloud Storage request.
  String uri = "https://storage.googleapis.com/" + URLEncoder.encode(bucketName, "UTF-8");

  HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
  HttpRequestFactory requestFactory =
      httpTransport.createRequestFactory(new HttpCredentialsAdapter(credential));
  GenericUrl url = new GenericUrl(uri);

  HttpRequest request = requestFactory.buildGetRequest(url);
  HttpResponse response = request.execute();
  String content = response.parseAsString();
  // [END snippet]

  return content;
}
 
Example #11
Source Project: firebase-admin-java   Author: firebase   File: RetryUnsuccessfulResponseHandler.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public boolean handleResponse(
    HttpRequest request, HttpResponse response, boolean supportsRetry) throws IOException {

  if (!supportsRetry) {
    return false;
  }

  int statusCode = response.getStatusCode();
  if (!retryConfig.getRetryStatusCodes().contains(statusCode)) {
    return false;
  }

  try {
    return waitAndRetry(response);
  } catch (InterruptedException e) {
    // ignore
  }
  return false;
}
 
Example #12
Source Project: firebase-admin-java   Author: firebase   File: FirebaseMessagingClientImpl.java    License: Apache License 2.0 6 votes vote down vote up
private String sendSingleRequest(Message message, boolean dryRun) throws IOException {
  HttpRequest request = requestFactory.buildPostRequest(
      new GenericUrl(fcmSendUrl),
      new JsonHttpContent(jsonFactory, message.wrapForTransport(dryRun)));
  setCommonFcmHeaders(request.getHeaders());
  request.setParser(new JsonObjectParser(jsonFactory));
  request.setResponseInterceptor(responseInterceptor);
  HttpResponse response = request.execute();
  try {
    MessagingServiceResponse parsed = new MessagingServiceResponse();
    jsonFactory.createJsonParser(response.getContent()).parseAndClose(parsed);
    return parsed.getMessageId();
  } finally {
    ApiClientUtils.disconnectQuietly(response);
  }
}
 
Example #13
Source Project: slr-toolkit   Author: sebastiangoetz   File: MendeleyClient.java    License: Eclipse Public License 1.0 6 votes vote down vote up
/**
   * This methods is used to delete a Mendeley documents via the DELETE https://api.mendeley.com/documents/{id} endpoint. 
   * @param document Pass the document that needs to be deleted from Mendeley
   */
  public void deleteDocument(MendeleyDocument document ){
  	refreshTokenIfNecessary();
  	
  	HttpRequestFactory requestFactory = new ApacheHttpTransport().createRequestFactory();
  	HttpRequest request;
  	HttpRequest delete_request;
  	
  	Gson gson = new GsonBuilder().create();
  	String json_body = gson.toJson(document);
  	String document_id = document.getId();
  	String resource_url = "https://api.mendeley.com/documents/" + document_id;
  	GenericUrl gen_url = new GenericUrl(resource_url);
  	
try {
	final HttpContent content = new ByteArrayContent("application/json", json_body.getBytes("UTF8") );
	delete_request = requestFactory.buildDeleteRequest(gen_url);
	delete_request.getHeaders().setAuthorization("Bearer " + access_token);
	
	delete_request.getHeaders().setContentType("application/vnd.mendeley-document.1+json");
	String rawResponse = delete_request.execute().parseAsString();
} catch (IOException e) {
	e.printStackTrace();
}
  }
 
Example #14
Source Project: google-api-java-client   Author: googleapis   File: MediaUploadErrorHandler.java    License: Apache License 2.0 6 votes vote down vote up
public boolean handleResponse(HttpRequest request, HttpResponse response, boolean supportsRetry)
    throws IOException {
  boolean handled = originalUnsuccessfulHandler != null
      && originalUnsuccessfulHandler.handleResponse(request, response, supportsRetry);

  // TODO(peleyal): figure out what is best practice - call serverErrorCallback only if the
  // abnormal response was handled, or call it regardless
  if (handled && supportsRetry && response.getStatusCode() / 100 == 5) {
    try {
      uploader.serverErrorCallback();
    } catch (IOException e) {
      LOGGER.log(Level.WARNING, "exception thrown while calling server callback", e);
    }
  }
  return handled;
}
 
Example #15
Source Project: google-oauth-java-client   Author: googleapis   File: DailyMotionSample.java    License: Apache License 2.0 6 votes vote down vote up
private static void run(HttpRequestFactory requestFactory) throws IOException {
  DailyMotionUrl url = new DailyMotionUrl("https://api.dailymotion.com/videos/favorites");
  url.setFields("id,tags,title,url");

  HttpRequest request = requestFactory.buildGetRequest(url);
  VideoFeed videoFeed = request.execute().parseAs(VideoFeed.class);
  if (videoFeed.list.isEmpty()) {
    System.out.println("No favorite videos found.");
  } else {
    if (videoFeed.hasMore) {
      System.out.print("First ");
    }
    System.out.println(videoFeed.list.size() + " favorite videos found:");
    for (Video video : videoFeed.list) {
      System.out.println();
      System.out.println("-----------------------------------------------");
      System.out.println("ID: " + video.id);
      System.out.println("Title: " + video.title);
      System.out.println("Tags: " + video.tags);
      System.out.println("URL: " + video.url);
    }
  }
}
 
Example #16
Source Project: pdi-google-spreadsheet-plugin   Author: GlobalTechnology   File: GoogleSpreadsheet.java    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public static String getAccessToken(String email, KeyStore pks) throws Exception {
    PrivateKey pk = getPrivateKey(pks);
    if (pk != null && !email.equals("")) {
        try {
            GoogleCredential credential = new GoogleCredential.Builder().setTransport(GoogleSpreadsheet.HTTP_TRANSPORT)
                    .setJsonFactory(GoogleSpreadsheet.JSON_FACTORY).setServiceAccountScopes(GoogleSpreadsheet.SCOPES).setServiceAccountId(email)
                    .setServiceAccountPrivateKey(pk).build();

            HttpRequestFactory requestFactory = GoogleSpreadsheet.HTTP_TRANSPORT.createRequestFactory(credential);
            GenericUrl url = new GenericUrl(GoogleSpreadsheet.getSpreadsheetFeedURL().toString());
            HttpRequest request = requestFactory.buildGetRequest(url);
            request.execute();
            return credential.getAccessToken();
        } catch (Exception e) {
            throw new Exception("Error fetching Access Token", e);
        }
    }
    return null;
}
 
Example #17
Source Project: googleads-shopping-samples   Author: googleads   File: LoggingHttpRequestInitializer.java    License: Apache License 2.0 6 votes vote down vote up
public void initialize(HttpRequest request) throws IOException {
  if (wrapped != null) {
    wrapped.initialize(request);
  }
  request.setLoggingEnabled(true);
  request.setCurlLoggingEnabled(false);
  request.setContentLoggingLimit(Integer.MAX_VALUE);
  request.setResponseInterceptor(
      new HttpResponseInterceptor() {
        private HttpResponseInterceptor wrapped = null;

        public void interceptResponse(HttpResponse response) throws IOException {
          if (wrapped != null) {
            wrapped.interceptResponse(response);
          }
          response.setLoggingEnabled(true);
          response.setContentLoggingLimit(Integer.MAX_VALUE);
        }

        public HttpResponseInterceptor setWrapped(HttpResponseInterceptor toWrap) {
          this.wrapped = toWrap;
          return this;
        }
      }.setWrapped(request.getResponseInterceptor()));
}
 
Example #18
Source Project: firebase-admin-java   Author: firebase   File: RetryInitializerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testRetryOnHttpError() throws IOException {
  MockSleeper sleeper = new MockSleeper();
  RetryInitializer initializer = new RetryInitializer(
      retryOnIOAndServiceUnavailableErrors(sleeper));
  CountingLowLevelHttpRequest failingRequest = CountingLowLevelHttpRequest.fromStatus(503);
  HttpRequest request = TestUtils.createRequest(failingRequest);
  initializer.initialize(request);
  final HttpUnsuccessfulResponseHandler retryHandler = request.getUnsuccessfulResponseHandler();

  try {
    request.execute();
    fail("No exception thrown for HTTP error");
  } catch (HttpResponseException e) {
    assertEquals(503, e.getStatusCode());
  }

  assertEquals(MAX_RETRIES, sleeper.getCount());
  assertEquals(MAX_RETRIES + 1, failingRequest.getCount());
  assertSame(retryHandler, request.getUnsuccessfulResponseHandler());
}
 
Example #19
Source Project: firebase-admin-java   Author: firebase   File: FirebaseRequestInitializerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testDefaultSettings() throws Exception {
  FirebaseApp app = FirebaseApp.initializeApp(new FirebaseOptions.Builder()
      .setCredentials(new MockGoogleCredentials("token"))
      .build());
  HttpRequest request = TestUtils.createRequest();

  FirebaseRequestInitializer initializer = new FirebaseRequestInitializer(app);
  initializer.initialize(request);


  assertEquals(0, request.getConnectTimeout());
  assertEquals(0, request.getReadTimeout());
  assertEquals("Bearer token", request.getHeaders().getAuthorization());
  assertEquals(HttpRequest.DEFAULT_NUMBER_OF_RETRIES, request.getNumberOfRetries());
  assertNull(request.getIOExceptionHandler());
  assertTrue(request.getUnsuccessfulResponseHandler() instanceof HttpCredentialsAdapter);
}
 
Example #20
Source Project: datacollector   Author: streamsets   File: Policy.java    License: Apache License 2.0 6 votes vote down vote up
public boolean create(String name, String rules) throws VaultException {
  Map<String, Object> data = new HashMap<>();
  data.put("rules", rules);

  HttpContent content = new JsonHttpContent(getJsonFactory(), data);

  try {
    HttpRequest request = getRequestFactory().buildRequest(
        "POST",
        new GenericUrl(getConf().getAddress() + "/v1/sys/policy/" + name),
        content
    );
    HttpResponse response = request.execute();
    if (!response.isSuccessStatusCode()) {
      LOG.error("Request failed status: {} message: {}", response.getStatusCode(), response.getStatusMessage());
    }

    return response.isSuccessStatusCode();
  } catch (IOException e) {
    LOG.error(e.toString(), e);
    throw new VaultException("Failed to authenticate: " + e.toString(), e);
  }
}
 
Example #21
Source Project: firebase-admin-java   Author: firebase   File: RetryUnsuccessfulResponseHandlerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testDoesNotRetryOnUnspecifiedHttpStatus() throws IOException {
  MultipleCallSleeper sleeper = new MultipleCallSleeper();
  RetryUnsuccessfulResponseHandler handler = new RetryUnsuccessfulResponseHandler(
      testRetryConfig(sleeper));
  CountingLowLevelHttpRequest failingRequest = CountingLowLevelHttpRequest.fromStatus(404);
  HttpRequest request = TestUtils.createRequest(failingRequest);
  request.setUnsuccessfulResponseHandler(handler);
  request.setNumberOfRetries(MAX_RETRIES);

  try {
    request.execute();
    fail("No exception thrown for HTTP error");
  } catch (HttpResponseException e) {
    assertEquals(404, e.getStatusCode());
  }

  assertEquals(0, sleeper.getCount());
  assertEquals(1, failingRequest.getCount());
}
 
Example #22
Source Project: firebase-admin-java   Author: firebase   File: RetryUnsuccessfulResponseHandlerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testRetryOnHttpClientErrorWhenSpecified() throws IOException {
  MultipleCallSleeper sleeper = new MultipleCallSleeper();
  RetryUnsuccessfulResponseHandler handler = new RetryUnsuccessfulResponseHandler(
      testRetryConfig(sleeper));
  CountingLowLevelHttpRequest failingRequest = CountingLowLevelHttpRequest.fromStatus(429);
  HttpRequest request = TestUtils.createRequest(failingRequest);
  request.setUnsuccessfulResponseHandler(handler);
  request.setNumberOfRetries(MAX_RETRIES);

  try {
    request.execute();
    fail("No exception thrown for HTTP error");
  } catch (HttpResponseException e) {
    assertEquals(429, e.getStatusCode());
  }

  assertEquals(MAX_RETRIES, sleeper.getCount());
  assertArrayEquals(new long[]{500, 1000, 2000, 4000}, sleeper.getDelays());
  assertEquals(MAX_RETRIES + 1, failingRequest.getCount());
}
 
Example #23
Source Project: google-api-java-client   Author: googleapis   File: GoogleJsonResponseExceptionTest.java    License: Apache License 2.0 5 votes vote down vote up
public void testFrom_detailsArbitraryXmlContent() throws Exception {
  HttpTransport transport = new ErrorTransport("<foo>", "application/atom+xml; charset=utf-8");
  HttpRequest request =
      transport.createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL);
  request.setThrowExceptionOnExecuteError(false);
  HttpResponse response = request.execute();
  GoogleJsonResponseException ge =
      GoogleJsonResponseException.from(GoogleJsonErrorTest.FACTORY, response);
  assertNull(ge.getDetails());
  assertTrue(
      ge.getMessage(), ge.getMessage().startsWith("403" + StringUtils.LINE_SEPARATOR + "<"));
}
 
Example #24
Source Project: datacollector   Author: streamsets   File: VaultEndpoint.java    License: Apache License 2.0 5 votes vote down vote up
public VaultEndpoint(final VaultConfiguration conf, HttpTransport transport) throws VaultException {
  this.conf = conf;
  requestFactory = transport.createRequestFactory(
      new HttpRequestInitializer() {
        @Override
        public void initialize(HttpRequest request) throws IOException {
          request.setParser(new JsonObjectParser(JSON_FACTORY));
          request.setHeaders(new HttpHeaders().set("X-Vault-Token", conf.getToken()));
          request.setReadTimeout(conf.getReadTimeout());
          request.setConnectTimeout(conf.getOpenTimeout());
        }
      }
  );
}
 
Example #25
Source Project: connector-sdk   Author: google-cloudsearch   File: BaseApiService.java    License: Apache License 2.0 5 votes vote down vote up
/** Initialize {@link HttpRequest} to setup exponential back off and automatic retries. */
@Override
public void initialize(HttpRequest request) throws IOException {
  BackOff backOff = new ExponentialBackOff();
  request.setUnsuccessfulResponseHandler(new LoggingResponseHandler(retryPolicy, backOff));
  request.setIOExceptionHandler(new LoggingIOExceptionHandler(backOff));
}
 
Example #26
Source Project: googleads-java-lib   Author: googleads   File: HttpHandler.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Creates an HTTP request based on the message context.
 *
 * @param msgContext the Axis message context
 * @return a new {@link HttpRequest} with content and headers populated
 */
private HttpRequest createHttpRequest(MessageContext msgContext)
    throws SOAPException, IOException {
  Message requestMessage =
      Preconditions.checkNotNull(
          msgContext.getRequestMessage(), "Null request message on message context");
  
  // Construct the output stream.
  String contentType = requestMessage.getContentType(msgContext.getSOAPConstants());
  ByteArrayOutputStream bos = new ByteArrayOutputStream(BUFFER_SIZE);

  if (msgContext.isPropertyTrue(HTTPConstants.MC_GZIP_REQUEST)) {
    logger.debug("Compressing request");
    try (GZIPOutputStream gzipOs = new GZIPOutputStream(bos, BUFFER_SIZE)) {
      requestMessage.writeTo(gzipOs);
    }
  } else {
    logger.debug("Not compressing request");
    requestMessage.writeTo(bos);
  }

  HttpRequest httpRequest =
      requestFactory.buildPostRequest(
          new GenericUrl(msgContext.getStrProp(MessageContext.TRANS_URL)),
          new ByteArrayContent(contentType, bos.toByteArray()));

  int timeoutMillis = msgContext.getTimeout();
  if (timeoutMillis >= 0) {
    logger.debug("Setting read and connect timeout to {} millis", timeoutMillis);
    // These are not the same, but MessageContext has only one definition of timeout.
    httpRequest.setReadTimeout(timeoutMillis);
    httpRequest.setConnectTimeout(timeoutMillis);
  }

  // Copy the request headers from the message context to the post request.
  setHttpRequestHeaders(msgContext, httpRequest);

  return httpRequest;
}
 
Example #27
Source Project: hadoop-connectors   Author: GoogleCloudDataproc   File: RetryHttpInitializer.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean handleIOException(HttpRequest httpRequest, boolean supportsRetry)
    throws IOException {
  // We sadly don't get anything helpful to see if this is something we want to log. As a result
  // we'll turn down the logging level to debug.
  logger.atFine().log("Encountered an IOException when accessing URL %s", httpRequest.getUrl());
  return delegateIOExceptionHandler.handleIOException(httpRequest, supportsRetry);
}
 
Example #28
Source Project: mutual-tls-ssl   Author: Hakky54   File: GoogleHttpClientServiceShould.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void executeRequest() throws Exception {
    HttpRequestFactory httpRequestFactory = mock(HttpRequestFactory.class);
    HttpRequest httpRequest = mock(HttpRequest.class);
    HttpResponse httpResponse = mock(HttpResponse.class);
    InputStream stream = new ByteArrayInputStream("Hello".getBytes());

    when(httpTransport.createRequestFactory()).thenReturn(httpRequestFactory);
    when(httpRequestFactory.buildGetRequest(any(GenericUrl.class))).thenReturn(httpRequest);
    when(httpRequest.setHeaders(any(HttpHeaders.class))).thenReturn(httpRequest);
    when(httpRequest.execute()).thenReturn(httpResponse);
    when(httpResponse.getContent()).thenReturn(stream);
    when(httpResponse.getStatusCode()).thenReturn(200);

    ArgumentCaptor<GenericUrl> genericUrlArgumentCaptor = ArgumentCaptor.forClass(GenericUrl.class);
    ArgumentCaptor<HttpHeaders> httpHeadersArgumentCaptor = ArgumentCaptor.forClass(HttpHeaders.class);

    ClientResponse clientResponse = victim.executeRequest(HTTP_URL);

    assertThat(clientResponse.getStatusCode()).isEqualTo(200);
    assertThat(clientResponse.getResponseBody()).isEqualTo("Hello");

    verify(httpRequest, times(1)).setHeaders(httpHeadersArgumentCaptor.capture());
    assertThat(httpHeadersArgumentCaptor.getValue().get(HEADER_KEY_CLIENT_TYPE)).isEqualTo(GOOGLE_HTTP_CLIENT.getValue());

    verify(httpRequestFactory, times(1)).buildGetRequest(genericUrlArgumentCaptor.capture());
    assertThat(genericUrlArgumentCaptor.getValue().toString()).isEqualTo(HTTP_URL);
    assertThat(genericUrlArgumentCaptor.getValue().toString()).isEqualTo(HTTP_URL);
}
 
Example #29
Source Project: google-api-java-client   Author: googleapis   File: GoogleJsonResponseExceptionTest.java    License: Apache License 2.0 5 votes vote down vote up
public void testFrom_detailsErrorObject() throws Exception {
  HttpTransport transport = new ErrorTransport("{\"error\": {\"message\": \"invalid_token\"}, \"error_description\": \"Invalid value\"}", Json.MEDIA_TYPE);
  HttpRequest request =
      transport.createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL);
  request.setThrowExceptionOnExecuteError(false);
  HttpResponse response = request.execute();
  GoogleJsonResponseException ge =
      GoogleJsonResponseException.from(GoogleJsonErrorTest.FACTORY, response);
  assertNotNull(ge.getDetails());
  assertEquals("invalid_token", ge.getDetails().getMessage());
  assertTrue(ge.getMessage().contains("403"));
}
 
Example #30
Source Project: java-specialagent   Author: opentracing-contrib   File: GoogleHttpClientTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void failedRequest(final MockTracer tracer) throws IOException {
  final HttpRequestFactory requestFactory = new NetHttpTransport().createRequestFactory();
  final HttpRequest request = requestFactory.buildGetRequest(new GenericUrl("http://localhost:12345"));
  try {
    final int statusCode = request.execute().getStatusCode();
    assertEquals(200, statusCode);
  }
  catch (final ConnectException ignore) {
  }

  final List<MockSpan> spans = tracer.finishedSpans();
  assertEquals(1, spans.size());
  assertEquals(GoogleHttpClientAgentIntercept.COMPONENT_NAME, spans.get(0).tags().get(Tags.COMPONENT.getKey()));
}