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

The following examples show how to use com.google.api.client.http.HttpRequest#getHeaders() . 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: HttpHealthcareApiClient.java    From beam with Apache License 2.0 6 votes vote down vote up
@Override
public void initialize(HttpRequest request) throws IOException {
  super.initialize(request);
  HttpHeaders requestHeaders = request.getHeaders();
  requestHeaders.setUserAgent(USER_AGENT);
  if (!credentials.hasRequestMetadata()) {
    return;
  }
  URI uri = null;
  if (request.getUrl() != null) {
    uri = request.getUrl().toURI();
  }
  Map<String, List<String>> credentialHeaders = credentials.getRequestMetadata(uri);
  if (credentialHeaders == null) {
    return;
  }
  for (Map.Entry<String, List<String>> entry : credentialHeaders.entrySet()) {
    String headerName = entry.getKey();
    List<String> requestValues = new ArrayList<>(entry.getValue());
    requestHeaders.put(headerName, requestValues);
  }
}
 
Example 2
Source File: AppIdentityCredentialTest.java    From google-api-java-client with Apache License 2.0 6 votes vote down vote up
public void testUsesAppIdentityService() throws IOException {
  final String expectedAccessToken = "ExpectedAccessToken";

  MockAppIdentityService appIdentity = new MockAppIdentityService();
  appIdentity.setAccessTokenText(expectedAccessToken);
  AppIdentityCredential.Builder builder = new AppIdentityCredential.Builder(SCOPES);
  builder.setAppIdentityService(appIdentity);
  AppIdentityCredential appCredential = builder.build();
  HttpTransport transport = new MockHttpTransport();
  HttpRequest request = transport.createRequestFactory().buildRequest(
      "get", null, null);

  appCredential.intercept(request);

  assertEquals(1, appIdentity.getGetAccessTokenCallCount());
  HttpHeaders headers = request.getHeaders();
  String authHeader = headers.getAuthorization();
  Boolean headerContainsToken = authHeader.contains(expectedAccessToken);
  assertTrue(headerContainsToken);
}
 
Example 3
Source File: ReportServiceLogger.java    From googleads-java-lib with Apache License 2.0 6 votes vote down vote up
@VisibleForTesting
RequestInfo buildRequestInfo(HttpRequest request) {
  RequestInfo.Builder requestBuilder = new RequestInfo.Builder();
  if (request != null) {
    requestBuilder.withServiceName("reportdownload").withMethodName(request.getRequestMethod());
    try {
      requestBuilder.withUrl(request.getUrl().toURL().toString());
    } catch (IllegalArgumentException e) {
      requestBuilder.withUrl("Malformed URL: " + request.getUrl());
    }

    if (request.getHeaders() != null) {
      String clientCustomerId =
          request.getHeaders().getFirstHeaderStringValue(CLIENT_CUSTOMER_ID);
      requestBuilder.withContext(CLIENT_CUSTOMER_ID, clientCustomerId);
    }

    // Get the payload from the request.
    requestBuilder.withPayload(extractPayload(request.getHeaders(), request.getContent()));
  }
  return requestBuilder.build();
}
 
Example 4
Source File: FirebaseMessagingClientImplTest.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
private void checkRequestHeader(HttpRequest request) {
  assertEquals("POST", request.getRequestMethod());
  assertEquals(TEST_FCM_URL, request.getUrl().toString());
  HttpHeaders headers = request.getHeaders();
  assertEquals("2", headers.get("X-GOOG-API-FORMAT-VERSION"));
  assertEquals("fire-admin-java/" + SdkUtils.getVersion(), headers.get("X-Firebase-Client"));
}
 
Example 5
Source File: AppIdentityCredentialTest.java    From google-api-java-client with Apache License 2.0 5 votes vote down vote up
public void testAppEngineCredentialWrapper() throws IOException {
  final String expectedAccessToken = "ExpectedAccessToken";
  final Collection<String> emptyScopes = Collections.emptyList();

  HttpTransport transport = new MockHttpTransport();
  JsonFactory jsonFactory = new JacksonFactory();

  MockAppIdentityService appIdentity = new MockAppIdentityService();
  appIdentity.setAccessTokenText(expectedAccessToken);

  AppIdentityCredential.Builder builder = new AppIdentityCredential.Builder(emptyScopes);
  builder.setAppIdentityService(appIdentity);
  AppIdentityCredential appCredential = builder.build();

  GoogleCredential wrapper = new
      AppIdentityCredential.AppEngineCredentialWrapper(appCredential, transport, jsonFactory);

  HttpRequest request = transport.createRequestFactory().buildRequest("get", null, null);

  assertTrue(wrapper.createScopedRequired());
  try {
    wrapper.intercept(request);
    fail("Should not be able to use credential without scopes.");
  } catch (Exception expected) {
  }
  assertEquals(1, appIdentity.getGetAccessTokenCallCount());

  GoogleCredential scopedWrapper = wrapper.createScoped(SCOPES);
  assertNotSame(wrapper, scopedWrapper);
  scopedWrapper.intercept(request);

  assertEquals(2, appIdentity.getGetAccessTokenCallCount());
  HttpHeaders headers = request.getHeaders();
  String authHeader = headers.getAuthorization();
  assertTrue(authHeader.contains(expectedAccessToken));
}
 
Example 6
Source File: URLFetchUtils.java    From appengine-gcs-client with Apache License 2.0 5 votes vote down vote up
HTTPRequestInfo(HttpRequest req) {
  method = req.getRequestMethod();
  url = req.getUrl().toURL();
  long myLength;
  HttpContent content = req.getContent();
  try {
    myLength = content == null ? -1 : content.getLength();
  } catch (IOException e) {
    myLength = -1;
  }
  length = myLength;
  h1 = req.getHeaders();
  h2 = null;
}
 
Example 7
Source File: IcannHttpReporter.java    From nomulus with Apache License 2.0 4 votes vote down vote up
/** Uploads {@code reportBytes} to ICANN, returning whether or not it succeeded. */
public boolean send(byte[] reportBytes, String reportFilename) throws XmlException, IOException {
  validateReportFilename(reportFilename);
  GenericUrl uploadUrl = new GenericUrl(makeUrl(reportFilename));
  HttpRequest request =
      httpTransport
          .createRequestFactory()
          .buildPutRequest(uploadUrl, new ByteArrayContent(CSV_UTF_8.toString(), reportBytes));

  HttpHeaders headers = request.getHeaders();
  headers.setBasicAuthentication(getTld(reportFilename) + "_ry", password);
  headers.setContentType(CSV_UTF_8.toString());
  request.setHeaders(headers);
  request.setFollowRedirects(false);

  HttpResponse response = null;
  logger.atInfo().log(
      "Sending report to %s with content length %d", uploadUrl, request.getContent().getLength());
  boolean success = true;
  try {
    response = request.execute();
    byte[] content;
    try {
      content = ByteStreams.toByteArray(response.getContent());
    } finally {
      response.getContent().close();
    }
    logger.atInfo().log(
        "Received response code %d with content %s",
        response.getStatusCode(), new String(content, UTF_8));
    XjcIirdeaResult result = parseResult(content);
    if (result.getCode().getValue() != 1000) {
      success = false;
      logger.atWarning().log(
          "PUT rejected, status code %s:\n%s\n%s",
          result.getCode(), result.getMsg(), result.getDescription());
    }
  } finally {
    if (response != null) {
      response.disconnect();
    } else {
      success = false;
      logger.atWarning().log("Received null response from ICANN server at %s", uploadUrl);
    }
  }
  return success;
}
 
Example 8
Source File: ReportRequestFactoryHelperTest.java    From googleads-java-lib with Apache License 2.0 4 votes vote down vote up
/** Tests the factory builds the request properly for this test's attributes. */
@Test
public void testGetHttpRequestFactory()
    throws ValidationException, AuthenticationException, IOException {
  final int timeoutFromLibConfig = 42;
  when(adWordsLibConfiguration.getReportDownloadTimeout()).thenReturn(timeoutFromLibConfig);
  AdWordsSession session =
      new AdWordsSession.Builder()
          .withDeveloperToken("foodevtoken")
          .withClientCustomerId("fooclientcustomerid")
          .withOAuth2Credential(credential)
          .withUserAgent("userAgent")
          .withReportingConfiguration(reportingConfiguration)
          .build();
  when(authorizationHeaderProvider.getAuthorizationHeader(session, ENDPOINT_URL.build()))
      .thenReturn("fooauthheader");
  when(userAgentCombiner.getUserAgent(anyString())).thenReturn("foouseragent");
  ReportRequestFactoryHelper helper =
      new ReportRequestFactoryHelper(
          session,
          authorizationHeaderProvider,
          userAgentCombiner,
          transport,
          adWordsLibConfiguration,
          reportResponseInterceptor);
  HttpRequestFactory requestFactory = helper.getHttpRequestFactory(ENDPOINT_URL.build(), version);

  HttpRequest request =
      requestFactory.buildPostRequest(
          ENDPOINT_URL, new AwqlReportBodyProvider("select 1", "csv").getHttpContent());
  HttpHeaders headers = request.getHeaders();
  assertEquals("foodevtoken", headers.get("developerToken"));
  assertEquals("fooauthheader", headers.getAuthorization());
  assertEquals("fooclientcustomerid", headers.get("clientCustomerId"));
  assertTrue((headers.getUserAgent()).contains("foouseragent"));

  if (reportingConfiguration == null) {
    assertFalse(
        "skipReportHeader should not be in the header if no reporting config is set",
        headers.containsKey("skipReportHeader"));
    assertFalse(
        "skipReportSummary should not be in the header if no reporting config is set",
        headers.containsKey("skipReportSummary"));
    assertEquals(
        "connect timeout is incorrect", timeoutFromLibConfig, request.getConnectTimeout());
    assertEquals("read timeout is incorrect", timeoutFromLibConfig, request.getReadTimeout());
  } else {
    Integer expectedTimeout = reportingConfiguration.getReportDownloadTimeout();
    if (expectedTimeout == null) {
      // Should fall back to the library level config value if the reporting config does not have
      // a timeout set.
      expectedTimeout = timeoutFromLibConfig;
    }
    assertEquals(
        "connect timeout is incorrect", expectedTimeout.intValue(), request.getConnectTimeout());
    assertEquals(
        "read timeout is incorrect", expectedTimeout.intValue(), request.getReadTimeout());
    assertEquals(
        "skipReportHeader not equal to the reporting config setting",
        toStringBoolean(reportingConfiguration.isSkipReportHeader()),
        headers.get("skipReportHeader"));
    assertEquals(
        "skipColumnHeader not equal to the reporting config setting",
        toStringBoolean(reportingConfiguration.isSkipColumnHeader()),
        headers.get("skipColumnHeader"));
    assertEquals(
        "skipReportSummary not equal to the reporting config setting",
        toStringBoolean(reportingConfiguration.isSkipReportSummary()),
        headers.get("skipReportSummary"));
    assertEquals(
        "includeZeroImpressions not equal to the reporting config setting",
        toStringBoolean(reportingConfiguration.isIncludeZeroImpressions()),
        headers.get("includeZeroImpressions"));
    assertEquals(
        "useRawEnumValues not equal to the reporting config setting",
        toStringBoolean(reportingConfiguration.isUseRawEnumValues()),
        headers.get("useRawEnumValues"));
  }
}