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 File: FirebaseRequestInitializerTest.java    From firebase-admin-java with 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 File: GoogleAuth.java    From endpoints-java with Apache License 2.0 7 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 File: GoogleAuthTest.java    From endpoints-java with 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 #4
Source File: RetryUnsuccessfulResponseHandlerTest.java    From firebase-admin-java with 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 #5
Source File: RetryInitializerTest.java    From firebase-admin-java with 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 #6
Source File: FirebaseRequestInitializerTest.java    From firebase-admin-java with 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 #7
Source File: Credential.java    From google-oauth-java-client with 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 #8
Source File: LoggingHttpRequestInitializer.java    From googleads-shopping-samples with 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 #9
Source File: Policy.java    From datacollector with 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 #10
Source File: GoogleSpreadsheet.java    From pdi-google-spreadsheet-plugin with 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 #11
Source File: DailyMotionSample.java    From google-oauth-java-client with 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 #12
Source File: DirectoryGroupsConnectionTest.java    From nomulus with 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 #13
Source File: MendeleyClient.java    From slr-toolkit with 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 File: RetryUnsuccessfulResponseHandlerTest.java    From firebase-admin-java with 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 #15
Source File: StorageSample.java    From java-docs-samples with 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 #16
Source File: RetryUnsuccessfulResponseHandlerTest.java    From firebase-admin-java with 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 #17
Source File: AuthorizationFlow.java    From android-oauth-client with 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 #18
Source File: RetryUnsuccessfulResponseHandler.java    From firebase-admin-java with 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 #19
Source File: SslHelper.java    From data-transfer-project with 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 #20
Source File: RetryHttpInitializerWrapper.java    From beam with 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 #21
Source File: FirebaseMessagingClientImpl.java    From firebase-admin-java with 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 #22
Source File: MediaUploadErrorHandler.java    From google-api-java-client with 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 #23
Source File: StorageSample.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@Override
protected void doGet(final HttpServletRequest req, final HttpServletResponse resp)
    throws IOException {

  try {
    AppIdentityCredential credential = new AppIdentityCredential(Arrays.asList(STORAGE_SCOPE));

    // Set up and execute Google Cloud Storage request.
    String bucketName = req.getRequestURI();
    if (bucketName.equals("/")) {
      resp.sendError(
          HTTP_NOT_FOUND, "No bucket specified - append /bucket-name to the URL and retry.");
      return;
    }
    // Remove any trailing slashes, if found.
    // [START snippet]
    String cleanBucketName = bucketName.replaceAll("/$", "");
    String uri = GCS_URI + cleanBucketName;
    HttpRequestFactory requestFactory = HTTP_TRANSPORT.createRequestFactory(credential);
    GenericUrl url = new GenericUrl(uri);
    HttpRequest request = requestFactory.buildGetRequest(url);
    HttpResponse response = request.execute();
    String content = response.parseAsString();
    // [END snippet]

    // Display the output XML.
    resp.setContentType("text/xml");
    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(resp.getOutputStream()));
    String formattedContent = content.replaceAll("(<ListBucketResult)", XSL + "$1");
    writer.append(formattedContent);
    writer.flush();
    resp.setStatus(HTTP_OK);
  } catch (Throwable e) {
    resp.sendError(HTTP_NOT_FOUND, e.getMessage());
  }
}
 
Example #24
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 #25
Source File: TestUtils.java    From endpoints-java with Apache License 2.0 5 votes vote down vote up
@Override
public boolean handleResponse(HttpRequest request, HttpResponse response, boolean supportsRetry)
    throws IOException {
  System.out.println(response.getStatusCode());
  BufferedReader in = new BufferedReader(new InputStreamReader(response.getContent()));
  String line;
  while ((line = in.readLine()) != null) {
    System.out.println(line);
  }
  return false;
}
 
Example #26
Source File: CloudClientLibGenerator.java    From endpoints-java with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
InputStream postRequest(String url, String boundary, String content) throws IOException {
  HttpRequestFactory requestFactory = new NetHttpTransport().createRequestFactory();
  HttpRequest request = requestFactory.buildPostRequest(new GenericUrl(url),
      ByteArrayContent.fromString("multipart/form-data; boundary=" + boundary, content));
  request.setReadTimeout(60000);  // 60 seconds is the max App Engine request time
  HttpResponse response = request.execute();
  if (response.getStatusCode() >= 300) {
    throw new IOException("Client Generation failed at server side: " + response.getContent());
  } else {
    return response.getContent();
  }
}
 
Example #27
Source File: OAuth2Utils.java    From google-api-java-client with Apache License 2.0 5 votes vote down vote up
static boolean runningOnComputeEngine(HttpTransport transport,
    SystemEnvironmentProvider environment) {
  // If the environment has requested that we do no GCE checks, return immediately.
  if (Boolean.parseBoolean(environment.getEnv("NO_GCE_CHECK"))) {
    return false;
  }

  GenericUrl tokenUrl = new GenericUrl(getMetadataServerUrl(environment));
  for (int i = 1; i <= MAX_COMPUTE_PING_TRIES; ++i) {
    try {
      HttpRequest request = transport.createRequestFactory().buildGetRequest(tokenUrl);
      request.setConnectTimeout(COMPUTE_PING_CONNECTION_TIMEOUT_MS);
      request.getHeaders().set("Metadata-Flavor", "Google");
      HttpResponse response = request.execute();
      try {
        HttpHeaders headers = response.getHeaders();
        return headersContainValue(headers, "Metadata-Flavor", "Google");
      } finally {
        response.disconnect();
      }
    } catch (SocketTimeoutException expected) {
      // Ignore logging timeouts which is the expected failure mode in non GCE environments.
    } catch (IOException e) {
      LOGGER.log(
          Level.WARNING,
          "Failed to detect whether we are running on Google Compute Engine.",
          e);
    }
  }
  return false;
}
 
Example #28
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 #29
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 #30
Source File: VerifyIapRequestHeader.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
boolean verifyJwtForComputeEngine(
    HttpRequest request, long projectNumber, long backendServiceId) throws Exception {
  // Check for iap jwt header in incoming request
  String jwtToken = request.getHeaders()
      .getFirstHeaderStringValue("x-goog-iap-jwt-assertion");
  if (jwtToken == null) {
    return false;
  }
  return verifyJwt(
      jwtToken,
      String.format(
          "/projects/%s/global/backendServices/%s",
          Long.toUnsignedString(projectNumber), Long.toUnsignedString(backendServiceId)));
}