Search in sources :

Example 1 with GenericUrl

use of com.google.api.client.http.GenericUrl in project elasticsearch by elastic.

the class RetryHttpInitializerWrapperTests method testIOExceptionRetry.

public void testIOExceptionRetry() throws Exception {
    FailThenSuccessBackoffTransport fakeTransport = new FailThenSuccessBackoffTransport(HttpStatusCodes.STATUS_CODE_SERVER_ERROR, 1, true);
    MockGoogleCredential credential = RetryHttpInitializerWrapper.newMockCredentialBuilder().build();
    MockSleeper mockSleeper = new MockSleeper();
    RetryHttpInitializerWrapper retryHttpInitializerWrapper = new RetryHttpInitializerWrapper(credential, mockSleeper, TimeValue.timeValueMillis(500));
    Compute client = new Compute.Builder(fakeTransport, new JacksonFactory(), null).setHttpRequestInitializer(retryHttpInitializerWrapper).setApplicationName("test").build();
    HttpRequest request = client.getRequestFactory().buildRequest("Get", new GenericUrl("http://elasticsearch.com"), null);
    HttpResponse response = request.execute();
    assertThat(mockSleeper.getCount(), equalTo(1));
    assertThat(response.getStatusCode(), equalTo(200));
}
Also used : LowLevelHttpRequest(com.google.api.client.http.LowLevelHttpRequest) HttpRequest(com.google.api.client.http.HttpRequest) MockLowLevelHttpRequest(com.google.api.client.testing.http.MockLowLevelHttpRequest) Compute(com.google.api.services.compute.Compute) MockGoogleCredential(com.google.api.client.googleapis.testing.auth.oauth2.MockGoogleCredential) MockLowLevelHttpResponse(com.google.api.client.testing.http.MockLowLevelHttpResponse) HttpResponse(com.google.api.client.http.HttpResponse) LowLevelHttpResponse(com.google.api.client.http.LowLevelHttpResponse) GenericUrl(com.google.api.client.http.GenericUrl) JacksonFactory(com.google.api.client.json.jackson2.JacksonFactory) MockSleeper(com.google.api.client.testing.util.MockSleeper)

Example 2 with GenericUrl

use of com.google.api.client.http.GenericUrl in project che by eclipse.

the class OAuthAuthenticator method callback.

/**
     * Process callback request.
     *
     * @param requestUrl
     *         request URI. URI should contain OAuth token and OAuth verifier.
     * @return id of authenticated user
     * @throws OAuthAuthenticationException
     *         if authentication failed or {@code requestUrl} does not contain required parameters.
     */
String callback(final URL requestUrl) throws OAuthAuthenticationException {
    try {
        final GenericUrl callbackUrl = new GenericUrl(requestUrl.toString());
        if (callbackUrl.getFirst(OAUTH_TOKEN_PARAM_KEY) == null) {
            throw new OAuthAuthenticationException("Missing oauth_token parameter");
        }
        if (callbackUrl.getFirst(OAUTH_VERIFIER_PARAM_KEY) == null) {
            throw new OAuthAuthenticationException("Missing oauth_verifier parameter");
        }
        final String state = (String) callbackUrl.getFirst(STATE_PARAM_KEY);
        String requestMethod = getParameterFromState(state, REQUEST_METHOD_PARAM_KEY);
        String signatureMethod = getParameterFromState(state, SIGNATURE_METHOD_PARAM_KEY);
        final String oauthTemporaryToken = (String) callbackUrl.getFirst(OAUTH_TOKEN_PARAM_KEY);
        OAuthGetAccessToken getAccessToken;
        if (requestMethod != null && "post".equals(requestMethod.toLowerCase())) {
            getAccessToken = new OAuthPostAccessToken(accessTokenUri);
        } else {
            getAccessToken = new OAuthGetAccessToken(accessTokenUri);
        }
        getAccessToken.consumerKey = clientId;
        getAccessToken.temporaryToken = oauthTemporaryToken;
        getAccessToken.verifier = (String) callbackUrl.getFirst(OAUTH_VERIFIER_PARAM_KEY);
        getAccessToken.transport = httpTransport;
        if (signatureMethod != null && "rsa".equals(signatureMethod.toLowerCase())) {
            getAccessToken.signer = getOAuthRsaSigner();
        } else {
            getAccessToken.signer = getOAuthHmacSigner(clientSecret, sharedTokenSecrets.remove(oauthTemporaryToken));
        }
        final OAuthCredentialsResponse credentials = getAccessToken.execute();
        String userId = getParameterFromState(state, USER_ID_PARAM_KEY);
        credentialsStoreLock.lock();
        try {
            final OAuthCredentialsResponse userId2Credential = credentialsStore.get(userId);
            if (userId2Credential == null) {
                credentialsStore.put(userId, credentials);
            } else {
                userId2Credential.token = credentials.token;
                userId2Credential.tokenSecret = credentials.tokenSecret;
            }
        } finally {
            credentialsStoreLock.unlock();
        }
        return userId;
    } catch (Exception e) {
        throw new OAuthAuthenticationException(e.getMessage());
    }
}
Also used : OAuthGetAccessToken(com.google.api.client.auth.oauth.OAuthGetAccessToken) GenericUrl(com.google.api.client.http.GenericUrl) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) GeneralSecurityException(java.security.GeneralSecurityException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) OAuthCredentialsResponse(com.google.api.client.auth.oauth.OAuthCredentialsResponse)

Example 3 with GenericUrl

use of com.google.api.client.http.GenericUrl in project beam by apache.

the class UploadIdResponseInterceptorTest method testResponseLogs.

/**
   * Check that a response logs with the correct log.
   */
@Test
public void testResponseLogs() throws IOException {
    new UploadIdResponseInterceptor().interceptResponse(buildHttpResponse("abc", null, "type"));
    GenericUrl url = new GenericUrl(HttpTesting.SIMPLE_URL);
    url.put("uploadType", "type");
    String worker = System.getProperty("worker_id");
    expectedLogs.verifyDebug("Upload ID for url " + url + " on worker " + worker + " is abc");
}
Also used : GenericUrl(com.google.api.client.http.GenericUrl) Test(org.junit.Test)

Example 4 with GenericUrl

use of com.google.api.client.http.GenericUrl in project google-cloud-java by GoogleCloudPlatform.

the class HttpStorageRpc method open.

@Override
public String open(StorageObject object, Map<Option, ?> options) {
    try {
        Insert req = storage.objects().insert(object.getBucket(), object);
        GenericUrl url = req.buildHttpRequest().getUrl();
        String scheme = url.getScheme();
        String host = url.getHost();
        String path = "/upload" + url.getRawPath();
        url = new GenericUrl(scheme + "://" + host + path);
        url.set("uploadType", "resumable");
        url.set("name", object.getName());
        for (Option option : options.keySet()) {
            Object content = option.get(options);
            if (content != null) {
                url.set(option.value(), content.toString());
            }
        }
        JsonFactory jsonFactory = storage.getJsonFactory();
        HttpRequestFactory requestFactory = storage.getRequestFactory();
        HttpRequest httpRequest = requestFactory.buildPostRequest(url, new JsonHttpContent(jsonFactory, object));
        HttpHeaders requestHeaders = httpRequest.getHeaders();
        requestHeaders.set("X-Upload-Content-Type", firstNonNull(object.getContentType(), "application/octet-stream"));
        String key = Option.CUSTOMER_SUPPLIED_KEY.getString(options);
        if (key != null) {
            BaseEncoding base64 = BaseEncoding.base64();
            HashFunction hashFunction = Hashing.sha256();
            requestHeaders.set("x-goog-encryption-algorithm", "AES256");
            requestHeaders.set("x-goog-encryption-key", key);
            requestHeaders.set("x-goog-encryption-key-sha256", base64.encode(hashFunction.hashBytes(base64.decode(key)).asBytes()));
        }
        HttpResponse response = httpRequest.execute();
        if (response.getStatusCode() != 200) {
            GoogleJsonError error = new GoogleJsonError();
            error.setCode(response.getStatusCode());
            error.setMessage(response.getStatusMessage());
            throw translate(error);
        }
        return response.getHeaders().getLocation();
    } catch (IOException ex) {
        throw translate(ex);
    }
}
Also used : HttpRequest(com.google.api.client.http.HttpRequest) HttpHeaders(com.google.api.client.http.HttpHeaders) HttpRequestFactory(com.google.api.client.http.HttpRequestFactory) JsonFactory(com.google.api.client.json.JsonFactory) HttpResponse(com.google.api.client.http.HttpResponse) LowLevelHttpResponse(com.google.api.client.http.LowLevelHttpResponse) GenericUrl(com.google.api.client.http.GenericUrl) JsonHttpContent(com.google.api.client.http.json.JsonHttpContent) IOException(java.io.IOException) Insert(com.google.api.services.storage.Storage.Objects.Insert) BaseEncoding(com.google.common.io.BaseEncoding) HashFunction(com.google.common.hash.HashFunction) StorageObject(com.google.api.services.storage.model.StorageObject) GoogleJsonError(com.google.api.client.googleapis.json.GoogleJsonError)

Example 5 with GenericUrl

use of com.google.api.client.http.GenericUrl in project google-cloud-java by GoogleCloudPlatform.

the class HttpBigQueryRpc method write.

@Override
public Job write(String uploadId, byte[] toWrite, int toWriteOffset, long destOffset, int length, boolean last) {
    try {
        GenericUrl url = new GenericUrl(uploadId);
        HttpRequest httpRequest = bigquery.getRequestFactory().buildPutRequest(url, new ByteArrayContent(null, toWrite, toWriteOffset, length));
        httpRequest.setParser(bigquery.getObjectParser());
        long limit = destOffset + length;
        StringBuilder range = new StringBuilder("bytes ");
        range.append(destOffset).append('-').append(limit - 1).append('/');
        if (last) {
            range.append(limit);
        } else {
            range.append('*');
        }
        httpRequest.getHeaders().setContentRange(range.toString());
        int code;
        String message;
        IOException exception = null;
        HttpResponse response = null;
        try {
            response = httpRequest.execute();
            code = response.getStatusCode();
            message = response.getStatusMessage();
        } catch (HttpResponseException ex) {
            exception = ex;
            code = ex.getStatusCode();
            message = ex.getStatusMessage();
        }
        if (!last && code != HTTP_RESUME_INCOMPLETE || last && !(code == HTTP_OK || code == HTTP_CREATED)) {
            if (exception != null) {
                throw exception;
            }
            throw new BigQueryException(code, message);
        }
        return last && response != null ? response.parseAs(Job.class) : null;
    } catch (IOException ex) {
        throw translate(ex);
    }
}
Also used : HttpRequest(com.google.api.client.http.HttpRequest) HttpResponse(com.google.api.client.http.HttpResponse) HttpResponseException(com.google.api.client.http.HttpResponseException) GenericUrl(com.google.api.client.http.GenericUrl) IOException(java.io.IOException) BigQueryException(com.google.cloud.bigquery.BigQueryException) ByteArrayContent(com.google.api.client.http.ByteArrayContent) Job(com.google.api.services.bigquery.model.Job)

Aggregations

GenericUrl (com.google.api.client.http.GenericUrl)28 HttpResponse (com.google.api.client.http.HttpResponse)19 HttpRequest (com.google.api.client.http.HttpRequest)15 IOException (java.io.IOException)15 HttpRequestFactory (com.google.api.client.http.HttpRequestFactory)8 NetHttpTransport (com.google.api.client.http.javanet.NetHttpTransport)7 InputStream (java.io.InputStream)7 HttpTransport (com.google.api.client.http.HttpTransport)6 HttpResponseException (com.google.api.client.http.HttpResponseException)4 LowLevelHttpResponse (com.google.api.client.http.LowLevelHttpResponse)4 JacksonFactory (com.google.api.client.json.jackson2.JacksonFactory)4 File (com.google.api.services.drive.model.File)4 GeneralSecurityException (java.security.GeneralSecurityException)4 MockGoogleCredential (com.google.api.client.googleapis.testing.auth.oauth2.MockGoogleCredential)3 HttpRequestInitializer (com.google.api.client.http.HttpRequestInitializer)3 LowLevelHttpRequest (com.google.api.client.http.LowLevelHttpRequest)3 JsonFactory (com.google.api.client.json.JsonFactory)3 MockLowLevelHttpRequest (com.google.api.client.testing.http.MockLowLevelHttpRequest)3 MockLowLevelHttpResponse (com.google.api.client.testing.http.MockLowLevelHttpResponse)3 MockSleeper (com.google.api.client.testing.util.MockSleeper)3