Search in sources :

Example 11 with HttpHeaders

use of com.google.api.client.http.HttpHeaders in project google-auth-library-java by google.

the class ComputeEngineCredentials method runningOnComputeEngine.

/**
 * Return whether code is running on Google Compute Engine.
 */
static boolean runningOnComputeEngine(HttpTransportFactory transportFactory, DefaultCredentialsProvider provider) {
    // If the environment has requested that we do no GCE checks, return immediately.
    if (Boolean.parseBoolean(provider.getEnv(DefaultCredentialsProvider.NO_GCE_CHECK_ENV_VAR))) {
        return false;
    }
    GenericUrl tokenUrl = new GenericUrl(getMetadataServerUrl(provider));
    for (int i = 1; i <= MAX_COMPUTE_PING_TRIES; ++i) {
        try {
            HttpRequest request = transportFactory.create().createRequestFactory().buildGetRequest(tokenUrl);
            request.setConnectTimeout(COMPUTE_PING_CONNECTION_TIMEOUT_MS);
            HttpResponse response = request.execute();
            try {
                // Internet providers can return a generic response to all requests, so it is necessary
                // to check that metadata header is present also.
                HttpHeaders headers = response.getHeaders();
                return OAuth2Utils.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;
}
Also used : HttpRequest(com.google.api.client.http.HttpRequest) HttpHeaders(com.google.api.client.http.HttpHeaders) SocketTimeoutException(java.net.SocketTimeoutException) HttpResponse(com.google.api.client.http.HttpResponse) GenericUrl(com.google.api.client.http.GenericUrl) IOException(java.io.IOException)

Example 12 with HttpHeaders

use of com.google.api.client.http.HttpHeaders in project google-auth-library-java by google.

the class HttpCredentialsAdapterTest method initialize_noURI.

@Test
public void initialize_noURI() throws IOException {
    final String accessToken = "1/MkSJoj1xsli0AccessToken_NKPY2";
    final String expectedAuthorization = InternalAuthHttpConstants.BEARER_PREFIX + accessToken;
    MockTokenServerTransportFactory tokenServerTransportFactory = new MockTokenServerTransportFactory();
    tokenServerTransportFactory.transport.addClient(CLIENT_ID, CLIENT_SECRET);
    tokenServerTransportFactory.transport.addRefreshToken(REFRESH_TOKEN, accessToken);
    OAuth2Credentials credentials = UserCredentials.newBuilder().setClientId(CLIENT_ID).setClientSecret(CLIENT_SECRET).setRefreshToken(REFRESH_TOKEN).setHttpTransportFactory(tokenServerTransportFactory).build();
    HttpCredentialsAdapter adapter = new HttpCredentialsAdapter(credentials);
    HttpRequestFactory requestFactory = tokenServerTransportFactory.transport.createRequestFactory();
    HttpRequest request = requestFactory.buildGetRequest(null);
    adapter.initialize(request);
    HttpHeaders requestHeaders = request.getHeaders();
    String authorizationHeader = requestHeaders.getAuthorization();
    assertEquals(authorizationHeader, expectedAuthorization);
}
Also used : HttpRequest(com.google.api.client.http.HttpRequest) HttpHeaders(com.google.api.client.http.HttpHeaders) HttpRequestFactory(com.google.api.client.http.HttpRequestFactory) MockTokenServerTransportFactory(com.google.auth.oauth2.GoogleCredentialsTest.MockTokenServerTransportFactory) OAuth2Credentials(com.google.auth.oauth2.OAuth2Credentials) Test(org.junit.Test)

Example 13 with HttpHeaders

use of com.google.api.client.http.HttpHeaders in project google-auth-library-java by google.

the class HttpCredentialsAdapter method initialize.

/**
 * {@inheritDoc}
 *
 * Initialize the HTTP request prior to execution.
 *
 * @param request HTTP request
 */
@Override
public void initialize(HttpRequest request) throws IOException {
    request.setUnsuccessfulResponseHandler(this);
    if (!credentials.hasRequestMetadata()) {
        return;
    }
    HttpHeaders requestHeaders = request.getHeaders();
    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<>();
        requestValues.addAll(entry.getValue());
        requestHeaders.put(headerName, requestValues);
    }
}
Also used : HttpHeaders(com.google.api.client.http.HttpHeaders) ArrayList(java.util.ArrayList) ArrayList(java.util.ArrayList) List(java.util.List) URI(java.net.URI) Map(java.util.Map)

Example 14 with HttpHeaders

use of com.google.api.client.http.HttpHeaders in project google-api-java-client by google.

the class AppIdentityCredentialTest method testUsesAppIdentityService.

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);
}
Also used : HttpRequest(com.google.api.client.http.HttpRequest) MockHttpTransport(com.google.api.client.testing.http.MockHttpTransport) HttpTransport(com.google.api.client.http.HttpTransport) HttpHeaders(com.google.api.client.http.HttpHeaders) MockHttpTransport(com.google.api.client.testing.http.MockHttpTransport) MockAppIdentityService(com.google.api.client.googleapis.extensions.appengine.testing.auth.oauth2.MockAppIdentityService)

Example 15 with HttpHeaders

use of com.google.api.client.http.HttpHeaders in project google-api-java-client by google.

the class HttpRequestContent method writeTo.

@Override
public void writeTo(OutputStream out) throws IOException {
    Writer writer = new OutputStreamWriter(out, getCharset());
    // write method and URL
    writer.write(request.getRequestMethod());
    writer.write(" ");
    writer.write(request.getUrl().build());
    writer.write(" ");
    writer.write(HTTP_VERSION);
    writer.write(NEWLINE);
    // write headers
    HttpHeaders headers = new HttpHeaders();
    headers.fromHttpHeaders(request.getHeaders());
    headers.setAcceptEncoding(null).setUserAgent(null).setContentEncoding(null).setContentType(null).setContentLength(null);
    // analyze the content
    HttpContent content = request.getContent();
    if (content != null) {
        headers.setContentType(content.getType());
        // NOTE: batch does not support gzip encoding
        long contentLength = content.getLength();
        if (contentLength != -1) {
            headers.setContentLength(contentLength);
        }
    }
    HttpHeaders.serializeHeadersForMultipartRequests(headers, null, null, writer);
    // HTTP headers are always terminated with an empty line; RFC 7230 ยง3
    writer.write(NEWLINE);
    writer.flush();
    // write content
    if (content != null) {
        content.writeTo(out);
    }
}
Also used : HttpHeaders(com.google.api.client.http.HttpHeaders) OutputStreamWriter(java.io.OutputStreamWriter) Writer(java.io.Writer) OutputStreamWriter(java.io.OutputStreamWriter) AbstractHttpContent(com.google.api.client.http.AbstractHttpContent) HttpContent(com.google.api.client.http.HttpContent)

Aggregations

HttpHeaders (com.google.api.client.http.HttpHeaders)46 HttpRequest (com.google.api.client.http.HttpRequest)22 IOException (java.io.IOException)21 GenericUrl (com.google.api.client.http.GenericUrl)13 HttpResponse (com.google.api.client.http.HttpResponse)13 HttpRequestFactory (com.google.api.client.http.HttpRequestFactory)10 GoogleJsonError (com.google.api.client.googleapis.json.GoogleJsonError)7 HttpRequestInitializer (com.google.api.client.http.HttpRequestInitializer)6 Test (org.junit.Test)6 HttpContent (com.google.api.client.http.HttpContent)5 Objects (com.google.api.services.storage.model.Objects)5 HttpResponseException (com.google.api.client.http.HttpResponseException)4 HttpTransport (com.google.api.client.http.HttpTransport)4 JsonObjectParser (com.google.api.client.json.JsonObjectParser)4 JacksonFactory (com.google.api.client.json.jackson2.JacksonFactory)4 MockHttpTransport (com.google.api.client.testing.http.MockHttpTransport)4 SocketTimeoutException (java.net.SocketTimeoutException)4 Map (java.util.Map)4 GoogleCredential (com.google.api.client.googleapis.auth.oauth2.GoogleCredential)3 GoogleJsonResponseException (com.google.api.client.googleapis.json.GoogleJsonResponseException)3