Search in sources :

Example 31 with HttpHeaders

use of com.google.api.client.http.HttpHeaders in project google-cloud-intellij by GoogleCloudPlatform.

the class CloudDebuggerClient method getClient.

/**
 * Returns a cloud debugger connection given a user email to indicate the credentials to use. The
 * function may return null if the user is not logged in.
 */
@Nullable
private static Debugger getClient(@Nullable final String userEmail, final int timeout) {
    if (Strings.isNullOrEmpty(userEmail)) {
        LOG.warn("unexpected null email in controller initialize.");
        return null;
    }
    final String hashkey = userEmail + timeout;
    Debugger cloudDebuggerClient = debuggerClientsFromUserEmail.get(hashkey);
    if (cloudDebuggerClient == null) {
        try {
            final CredentialedUser user = Services.getLoginService().getAllUsers().get(userEmail);
            final Credential credential = (user != null ? user.getCredential() : null);
            if (credential != null) {
                user.getGoogleLoginState().addLoginListener(new LoginListener() {

                    @Override
                    public void statusChanged(boolean login) {
                        if (!login) {
                            // aggressively remove the cached item on any status change.
                            debuggerClientsFromUserEmail.remove(hashkey);
                        } else {
                        // NOPMD
                        // user logged in, should we do something?
                        }
                    }
                });
                HttpRequestInitializer initializer = new HttpRequestInitializer() {

                    @Override
                    public void initialize(HttpRequest httpRequest) throws IOException {
                        HttpHeaders headers = new HttpHeaders();
                        httpRequest.setConnectTimeout(timeout);
                        httpRequest.setReadTimeout(timeout);
                        httpRequest.setHeaders(headers);
                        credential.initialize(httpRequest);
                    }
                };
                HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
                String userAgent = ServiceManager.getService(PluginInfoService.class).getUserAgent();
                cloudDebuggerClient = new Builder(httpTransport, JSON_FACTORY, initializer).setRootUrl(ROOT_URL).setApplicationName(userAgent).build().debugger();
            }
        } catch (IOException ex) {
            LOG.warn("Error connecting to Cloud Debugger API", ex);
        } catch (GeneralSecurityException ex) {
            LOG.warn("Error connecting to Cloud Debugger API", ex);
        }
        if (cloudDebuggerClient != null) {
            debuggerClientsFromUserEmail.put(hashkey, cloudDebuggerClient);
        }
    }
    return cloudDebuggerClient;
}
Also used : Debugger(com.google.api.services.clouddebugger.v2.Clouddebugger.Debugger) HttpRequest(com.google.api.client.http.HttpRequest) HttpHeaders(com.google.api.client.http.HttpHeaders) Credential(com.google.api.client.auth.oauth2.Credential) Builder(com.google.api.services.clouddebugger.v2.Clouddebugger.Builder) GeneralSecurityException(java.security.GeneralSecurityException) PluginInfoService(com.google.cloud.tools.intellij.service.PluginInfoService) IOException(java.io.IOException) HttpTransport(com.google.api.client.http.HttpTransport) GoogleNetHttpTransport(com.google.api.client.googleapis.javanet.GoogleNetHttpTransport) LoginListener(com.google.gdt.eclipse.login.common.LoginListener) CredentialedUser(com.google.cloud.tools.intellij.login.CredentialedUser) HttpRequestInitializer(com.google.api.client.http.HttpRequestInitializer) Nullable(org.jetbrains.annotations.Nullable)

Example 32 with HttpHeaders

use of com.google.api.client.http.HttpHeaders in project google-cloud-intellij by GoogleCloudPlatform.

the class CloudDebuggerClientTest method testUserAgent.

@Test
public void testUserAgent() throws IOException {
    when(mockInfoService.getUserAgent()).thenReturn("userAgent");
    Debugger client = CloudDebuggerClient.getLongTimeoutClient("foo@example.com");
    HttpRequest httpRequest = client.debuggees().list().buildHttpRequestUsingHead();
    HttpHeaders headers = httpRequest.getHeaders();
    String userAgent = headers.getUserAgent();
    Assert.assertTrue(userAgent.startsWith("userAgent"));
    Assert.assertTrue(userAgent.endsWith("Google-API-Java-Client"));
}
Also used : Debugger(com.google.api.services.clouddebugger.v2.Clouddebugger.Debugger) HttpRequest(com.google.api.client.http.HttpRequest) HttpHeaders(com.google.api.client.http.HttpHeaders) Test(org.junit.Test)

Example 33 with HttpHeaders

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

the class AppIdentityCredentialTest method testAppEngineCredentialWrapper.

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

Example 34 with HttpHeaders

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

the class BatchRequestTest method subtestExecute_checkWriteTo.

private void subtestExecute_checkWriteTo(final String expectedOutput, HttpRequest... requests) throws IOException {
    MockHttpTransport transport = new MockHttpTransport() {

        @Override
        public LowLevelHttpRequest buildRequest(String method, String url) {
            return new MockLowLevelHttpRequest(url) {

                @Override
                public LowLevelHttpResponse execute() throws IOException {
                    assertEquals("multipart/mixed; boundary=__END_OF_PART__", getContentType());
                    ByteArrayOutputStream out = new ByteArrayOutputStream();
                    getStreamingContent().writeTo(out);
                    assertEquals(expectedOutput, out.toString("UTF-8"));
                    MockLowLevelHttpResponse response = new MockLowLevelHttpResponse();
                    response.setStatusCode(200);
                    response.addHeader("Content-Type", "multipart/mixed; boundary=" + RESPONSE_BOUNDARY);
                    String content2 = "{\"name\": \"" + TEST_NAME + "\", \"number\": \"" + TEST_NUM + "\"}";
                    StringBuilder responseContent = new StringBuilder();
                    responseContent.append("--" + RESPONSE_BOUNDARY + "\n").append("Content-Type: application/http\n").append("Content-Transfer-Encoding: binary\n").append("Content-ID: response-1\n\n").append("HTTP/1.1 200 OK\n").append("Content-Type: application/json; charset=UTF-8\n").append("Content-Length: " + content2.length() + "\n\n").append(content2 + "\n\n").append("--" + RESPONSE_BOUNDARY + "--\n\n");
                    response.setContent(responseContent.toString());
                    return response;
                }
            };
        }
    };
    BatchRequest batchRequest = new BatchRequest(transport, null);
    BatchCallback<Void, Void> callback = new BatchCallback<Void, Void>() {

        @Override
        public void onSuccess(Void t, HttpHeaders responseHeaders) {
        }

        @Override
        public void onFailure(Void e, HttpHeaders responseHeaders) {
        }
    };
    for (HttpRequest request : requests) {
        batchRequest.queue(request, Void.class, Void.class, callback);
    }
    batchRequest.execute();
}
Also used : LowLevelHttpRequest(com.google.api.client.http.LowLevelHttpRequest) HttpRequest(com.google.api.client.http.HttpRequest) MockLowLevelHttpRequest(com.google.api.client.testing.http.MockLowLevelHttpRequest) HttpHeaders(com.google.api.client.http.HttpHeaders) MockHttpTransport(com.google.api.client.testing.http.MockHttpTransport) MockLowLevelHttpResponse(com.google.api.client.testing.http.MockLowLevelHttpResponse) ByteArrayOutputStream(java.io.ByteArrayOutputStream) MockLowLevelHttpRequest(com.google.api.client.testing.http.MockLowLevelHttpRequest)

Example 35 with HttpHeaders

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

the class GooglePublicKeysManagerTest method testGetCacheTimeInSec.

public void testGetCacheTimeInSec() throws Exception {
    GooglePublicKeysManager certs = new GooglePublicKeysManager.Builder(new MockHttpTransport(), new JacksonFactory()).build();
    assertEquals(12000, certs.getCacheTimeInSec(new HttpHeaders().setAge(345L).setCacheControl("max-age=" + MAX_AGE)));
    assertEquals(0, certs.getCacheTimeInSec(new HttpHeaders()));
    assertEquals(0, certs.getCacheTimeInSec(new HttpHeaders().setAge(345L)));
    assertEquals(0, certs.getCacheTimeInSec(new HttpHeaders().setAge(345L).setCacheControl("max-age=300")));
}
Also used : HttpHeaders(com.google.api.client.http.HttpHeaders) MockHttpTransport(com.google.api.client.testing.http.MockHttpTransport) JacksonFactory(com.google.api.client.json.jackson2.JacksonFactory)

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