Java Code Examples for com.google.api.client.http.HttpRequest#setThrowExceptionOnExecuteError()

The following examples show how to use com.google.api.client.http.HttpRequest#setThrowExceptionOnExecuteError() . 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: ReportResponseInterceptorTest.java    From googleads-java-lib with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
}
 
Example 2
Source File: MediaHttpUploader.java    From google-api-java-client with Apache License 2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example 3
Source File: GoogleJsonResponseExceptionTest.java    From google-api-java-client with Apache License 2.0 5 votes vote down vote up
public void testFrom_errorEmptyContentButWithJsonContentType() throws Exception {
  HttpTransport transport = new ErrorTransport(null, 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);
  assertNull(ge.getDetails());
  assertEquals("403", ge.getMessage());
}
 
Example 4
Source File: GoogleJsonResponseExceptionTest.java    From google-api-java-client with 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 5
Source File: GoogleJsonResponseExceptionTest.java    From google-api-java-client with Apache License 2.0 5 votes vote down vote up
public void testFrom_detailsArbitraryJsonContent() throws Exception {
  HttpTransport transport = new ErrorTransport("{\"foo\":\"bar\"}", 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);
  assertNull(ge.getDetails());
  assertEquals("403", ge.getMessage());
}
 
Example 6
Source File: GoogleJsonResponseExceptionTest.java    From google-api-java-client with Apache License 2.0 5 votes vote down vote up
public void testFrom_detailsMissingContent() throws Exception {
  HttpTransport transport = new ErrorTransport(null, 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);
  assertNull(ge.getDetails());
  assertEquals("403", ge.getMessage());
}
 
Example 7
Source File: GoogleJsonResponseExceptionTest.java    From google-api-java-client with Apache License 2.0 5 votes vote down vote up
public void testFrom_withDetails() throws Exception {
  HttpTransport transport = new ErrorTransport();
  HttpRequest request =
      transport.createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL);
  request.setThrowExceptionOnExecuteError(false);
  HttpResponse response = request.execute();
  GoogleJsonResponseException ge =
      GoogleJsonResponseException.from(GoogleJsonErrorTest.FACTORY, response);
  assertEquals(GoogleJsonErrorTest.ERROR, GoogleJsonErrorTest.FACTORY.toString(ge.getDetails()));
  assertTrue(
      ge.getMessage(), ge.getMessage().startsWith("403" + StringUtils.LINE_SEPARATOR + "{"));
}
 
Example 8
Source File: GoogleJsonResponseExceptionTest.java    From google-api-java-client with Apache License 2.0 5 votes vote down vote up
public void testFrom_noDetails() throws Exception {
  HttpTransport transport = new MockHttpTransport();
  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());
  assertEquals("200", ge.getMessage());
}
 
Example 9
Source File: HttpHandler.java    From googleads-java-lib with Apache License 2.0 5 votes vote down vote up
/** 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);
}
 
Example 10
Source File: BatchUnparsedResponse.java    From google-api-java-client with Apache License 2.0 5 votes vote down vote up
/** 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();
}
 
Example 11
Source File: GoogleJsonResponseExceptionTest.java    From google-api-java-client with 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 12
Source File: DefaultCredentialProvider.java    From google-api-java-client with Apache License 2.0 5 votes vote down vote up
@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 13
Source File: GoogleJsonErrorTest.java    From google-api-java-client with Apache License 2.0 5 votes vote down vote up
public void testParse() throws Exception {
  HttpTransport transport = new ErrorTransport();
  HttpRequest request =
      transport.createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL);
  request.setThrowExceptionOnExecuteError(false);
  HttpResponse response = request.execute();
  GoogleJsonError errorResponse = GoogleJsonError.parse(FACTORY, response);
  assertEquals(ERROR, FACTORY.toString(errorResponse));
}
 
Example 14
Source File: ApiErrorExtractorTest.java    From hadoop-connectors with Apache License 2.0 5 votes vote down vote up
private static GoogleJsonResponseException googleJsonResponseException(
    int status, ErrorInfo errorInfo, String httpStatusString) throws IOException {
  final JsonFactory jsonFactory = new JacksonFactory();
  HttpTransport transport =
      new MockHttpTransport() {
        @Override
        public LowLevelHttpRequest buildRequest(String method, String url) throws IOException {
          errorInfo.setFactory(jsonFactory);
          GoogleJsonError jsonError = new GoogleJsonError();
          jsonError.setCode(status);
          jsonError.setErrors(Collections.singletonList(errorInfo));
          jsonError.setMessage(httpStatusString);
          jsonError.setFactory(jsonFactory);
          GenericJson errorResponse = new GenericJson();
          errorResponse.set("error", jsonError);
          errorResponse.setFactory(jsonFactory);
          return new MockLowLevelHttpRequest()
              .setResponse(
                  new MockLowLevelHttpResponse()
                      .setContent(errorResponse.toPrettyString())
                      .setContentType(Json.MEDIA_TYPE)
                      .setStatusCode(status));
        }
      };
  HttpRequest request =
      transport.createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL);
  request.setThrowExceptionOnExecuteError(false);
  HttpResponse response = request.execute();
  return GoogleJsonResponseException.from(jsonFactory, response);
}
 
Example 15
Source File: GoogleJsonResponseExceptionTest.java    From google-api-java-client with Apache License 2.0 5 votes vote down vote up
public void testFrom_detailsErrorString() throws Exception {
  HttpTransport transport = new ErrorTransport("{\"error\": \"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);
  assertNull(ge.getDetails());
  assertTrue(ge.getMessage().contains("403"));
  assertTrue(ge.getMessage().contains("invalid_token"));
}
 
Example 16
Source File: PackageUtilTest.java    From beam with Apache License 2.0 5 votes vote down vote up
/** Builds a fake GoogleJsonResponseException for testing API error handling. */
private static GoogleJsonResponseException googleJsonResponseException(
    final int status, final String reason, final String message) throws IOException {
  final JsonFactory jsonFactory = new JacksonFactory();
  HttpTransport transport =
      new MockHttpTransport() {
        @Override
        public LowLevelHttpRequest buildRequest(String method, String url) throws IOException {
          ErrorInfo errorInfo = new ErrorInfo();
          errorInfo.setReason(reason);
          errorInfo.setMessage(message);
          errorInfo.setFactory(jsonFactory);
          GenericJson error = new GenericJson();
          error.set("code", status);
          error.set("errors", Arrays.asList(errorInfo));
          error.setFactory(jsonFactory);
          GenericJson errorResponse = new GenericJson();
          errorResponse.set("error", error);
          errorResponse.setFactory(jsonFactory);
          return new MockLowLevelHttpRequest()
              .setResponse(
                  new MockLowLevelHttpResponse()
                      .setContent(errorResponse.toPrettyString())
                      .setContentType(Json.MEDIA_TYPE)
                      .setStatusCode(status));
        }
      };
  HttpRequest request =
      transport.createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL);
  request.setThrowExceptionOnExecuteError(false);
  HttpResponse response = request.execute();
  return GoogleJsonResponseException.from(jsonFactory, response);
}
 
Example 17
Source File: GcsUtilTest.java    From beam with Apache License 2.0 5 votes vote down vote up
/** Builds a fake GoogleJsonResponseException for testing API error handling. */
private static GoogleJsonResponseException googleJsonResponseException(
    final int status, final String reason, final String message) throws IOException {
  final JsonFactory jsonFactory = new JacksonFactory();
  HttpTransport transport =
      new MockHttpTransport() {
        @Override
        public LowLevelHttpRequest buildRequest(String method, String url) throws IOException {
          ErrorInfo errorInfo = new ErrorInfo();
          errorInfo.setReason(reason);
          errorInfo.setMessage(message);
          errorInfo.setFactory(jsonFactory);
          GenericJson error = new GenericJson();
          error.set("code", status);
          error.set("errors", Arrays.asList(errorInfo));
          error.setFactory(jsonFactory);
          GenericJson errorResponse = new GenericJson();
          errorResponse.set("error", error);
          errorResponse.setFactory(jsonFactory);
          return new MockLowLevelHttpRequest()
              .setResponse(
                  new MockLowLevelHttpResponse()
                      .setContent(errorResponse.toPrettyString())
                      .setContentType(Json.MEDIA_TYPE)
                      .setStatusCode(status));
        }
      };
  HttpRequest request =
      transport.createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL);
  request.setThrowExceptionOnExecuteError(false);
  HttpResponse response = request.execute();
  return GoogleJsonResponseException.from(jsonFactory, response);
}
 
Example 18
Source File: CoreSocketFactoryTest.java    From cloud-sql-jdbc-socket-factory with Apache License 2.0 5 votes vote down vote up
private static GoogleJsonResponseException fakeGoogleJsonResponseException(
    int status, ErrorInfo errorInfo, String message) throws IOException {
  final JsonFactory jsonFactory = new JacksonFactory();
  HttpTransport transport =
      new MockHttpTransport() {
        @Override
        public LowLevelHttpRequest buildRequest(String method, String url) throws IOException {
          errorInfo.setFactory(jsonFactory);
          GoogleJsonError jsonError = new GoogleJsonError();
          jsonError.setCode(status);
          jsonError.setErrors(Collections.singletonList(errorInfo));
          jsonError.setMessage(message);
          jsonError.setFactory(jsonFactory);
          GenericJson errorResponse = new GenericJson();
          errorResponse.set("error", jsonError);
          errorResponse.setFactory(jsonFactory);
          return new MockLowLevelHttpRequest()
              .setResponse(
                  new MockLowLevelHttpResponse()
                      .setContent(errorResponse.toPrettyString())
                      .setContentType(Json.MEDIA_TYPE)
                      .setStatusCode(status));
        }
      };
  HttpRequest request =
      transport.createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL);
  request.setThrowExceptionOnExecuteError(false);
  HttpResponse response = request.execute();
  return GoogleJsonResponseException.from(jsonFactory, response);
}
 
Example 19
Source File: SplunkHttpSinkTask.java    From kafka-connect-splunk with Apache License 2.0 4 votes vote down vote up
@Override
  public void start(Map<String, String> map) {
    this.config = new SplunkHttpSinkConnectorConfig(map);

    java.util.logging.Logger logger = java.util.logging.Logger.getLogger(HttpTransport.class.getName());
    logger.addHandler(new RequestLoggingHandler(log));
    if (this.config.curlLoggingEnabled) {
      logger.setLevel(Level.ALL);
    } else {
      logger.setLevel(Level.WARNING);
    }

    log.info("Starting...");

    NetHttpTransport.Builder transportBuilder = new NetHttpTransport.Builder();

    if (!this.config.validateCertificates) {
      log.warn("Disabling ssl certificate verification.");
      try {
        transportBuilder.doNotValidateCertificate();
      } catch (GeneralSecurityException e) {
        throw new IllegalStateException("Exception thrown calling transportBuilder.doNotValidateCertificate()", e);
      }
    }

    if (this.config.hasTrustStorePath) {
      log.info("Loading trust store from {}.", this.config.trustStorePath);
      try (FileInputStream inputStream = new FileInputStream(this.config.trustStorePath)) {
        transportBuilder.trustCertificatesFromJavaKeyStore(inputStream, this.config.trustStorePassword);
      } catch (GeneralSecurityException | IOException ex) {
        throw new IllegalStateException("Exception thrown while setting up trust certificates.", ex);
      }
    }

    this.transport = transportBuilder.build();
    final String authHeaderValue = String.format("Splunk %s", this.config.authToken);
    final JsonObjectParser jsonObjectParser = new JsonObjectParser(jsonFactory);

    final String userAgent = String.format("kafka-connect-splunk/%s", version());
    final boolean curlLogging = this.config.curlLoggingEnabled;
    this.httpRequestInitializer = new HttpRequestInitializer() {
      @Override
      public void initialize(HttpRequest httpRequest) throws IOException {
        httpRequest.getHeaders().setAuthorization(authHeaderValue);
        httpRequest.getHeaders().setAccept(Json.MEDIA_TYPE);
        httpRequest.getHeaders().setUserAgent(userAgent);
        httpRequest.setParser(jsonObjectParser);
        httpRequest.setEncoding(new GZipEncoding());
        httpRequest.setThrowExceptionOnExecuteError(false);
        httpRequest.setConnectTimeout(config.connectTimeout);
        httpRequest.setReadTimeout(config.readTimeout);
        httpRequest.setCurlLoggingEnabled(curlLogging);
//        httpRequest.setLoggingEnabled(curlLogging);
      }
    };

    this.httpRequestFactory = this.transport.createRequestFactory(this.httpRequestInitializer);

    this.eventCollectorUrl = new GenericUrl();
    this.eventCollectorUrl.setRawPath("/services/collector/event");
    this.eventCollectorUrl.setPort(this.config.splunkPort);
    this.eventCollectorUrl.setHost(this.config.splunkHost);

    if (this.config.ssl) {
      this.eventCollectorUrl.setScheme("https");
    } else {
      this.eventCollectorUrl.setScheme("http");
    }

    log.info("Setting Splunk Http Event Collector Url to {}", this.eventCollectorUrl);
  }
 
Example 20
Source File: ReposiliteIntegrationTest.java    From reposilite with Apache License 2.0 4 votes vote down vote up
protected HttpResponse getAuthenticated(String uri, String username, String password) throws IOException {
    HttpRequest request = requestFactory.buildGetRequest(url(uri));
    request.setThrowExceptionOnExecuteError(false);
    request.getHeaders().setBasicAuthentication(username, password);
    return request.execute();
}