Search in sources :

Example 11 with GenericUrl

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

the class OAuthAuthenticator method getAuthenticateUrl.

/**
     * Create authentication URL.
     *
     * @param requestUrl
     *         URL of current HTTP request. This parameter required to be able determine URL for redirection after
     *         authentication. If URL contains query parameters they will be copied to 'state' parameter and returned to
     *         callback method.
     * @param requestMethod
     *         HTTP request method that will be used to request temporary token
     * @param signatureMethod
     *         OAuth signature algorithm
     * @return URL for authentication.
     * @throws OAuthAuthenticationException
     *         if authentication failed.
     */
String getAuthenticateUrl(final URL requestUrl, @Nullable final String requestMethod, @Nullable final String signatureMethod) throws OAuthAuthenticationException {
    try {
        final GenericUrl callbackUrl = new GenericUrl(redirectUri);
        callbackUrl.put(STATE_PARAM_KEY, requestUrl.getQuery());
        OAuthGetTemporaryToken temporaryToken;
        if (requestMethod != null && "post".equals(requestMethod.toLowerCase())) {
            temporaryToken = new OAuthPostTemporaryToken(requestTokenUri);
        } else {
            temporaryToken = new OAuthGetTemporaryToken(requestTokenUri);
        }
        if (signatureMethod != null && "rsa".equals(signatureMethod.toLowerCase())) {
            temporaryToken.signer = getOAuthRsaSigner();
        } else {
            temporaryToken.signer = getOAuthHmacSigner(null, null);
        }
        temporaryToken.consumerKey = clientId;
        temporaryToken.callback = callbackUrl.build();
        temporaryToken.transport = httpTransport;
        final OAuthCredentialsResponse credentialsResponse = temporaryToken.execute();
        final OAuthAuthorizeTemporaryTokenUrl authorizeTemporaryTokenUrl = new OAuthAuthorizeTemporaryTokenUrl(authorizeTokenUri);
        authorizeTemporaryTokenUrl.temporaryToken = credentialsResponse.token;
        sharedTokenSecrets.put(credentialsResponse.token, credentialsResponse.tokenSecret);
        return authorizeTemporaryTokenUrl.build();
    } catch (Exception e) {
        throw new OAuthAuthenticationException(e.getMessage());
    }
}
Also used : OAuthGetTemporaryToken(com.google.api.client.auth.oauth.OAuthGetTemporaryToken) GenericUrl(com.google.api.client.http.GenericUrl) OAuthAuthorizeTemporaryTokenUrl(com.google.api.client.auth.oauth.OAuthAuthorizeTemporaryTokenUrl) 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 12 with GenericUrl

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

the class GceMetadataService method metadata.

public String metadata(String metadataPath) throws IOException, URISyntaxException {
    // Forcing Google Token API URL as set in GCE SDK to
    //      http://metadata/computeMetadata/v1/instance/service-accounts/default/token
    // See https://developers.google.com/compute/docs/metadata#metadataserver
    final URI urlMetadataNetwork = new URI(GCE_HOST.get(settings)).resolve("/computeMetadata/v1/instance/").resolve(metadataPath);
    logger.debug("get metadata from [{}]", urlMetadataNetwork);
    HttpHeaders headers;
    try {
        // hack around code messiness in GCE code
        // TODO: get this fixed
        headers = Access.doPrivileged(HttpHeaders::new);
        GenericUrl genericUrl = Access.doPrivileged(() -> new GenericUrl(urlMetadataNetwork));
        // This is needed to query meta data: https://cloud.google.com/compute/docs/metadata
        headers.put("Metadata-Flavor", "Google");
        HttpResponse response = Access.doPrivilegedIOException(() -> getGceHttpTransport().createRequestFactory().buildGetRequest(genericUrl).setHeaders(headers).execute());
        String metadata = response.parseAsString();
        logger.debug("metadata found [{}]", metadata);
        return metadata;
    } catch (Exception e) {
        throw new IOException("failed to fetch metadata from [" + urlMetadataNetwork + "]", e);
    }
}
Also used : HttpHeaders(com.google.api.client.http.HttpHeaders) HttpResponse(com.google.api.client.http.HttpResponse) GenericUrl(com.google.api.client.http.GenericUrl) IOException(java.io.IOException) URI(java.net.URI) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) GeneralSecurityException(java.security.GeneralSecurityException)

Example 13 with GenericUrl

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

the class RetryHttpInitializerWrapperTests method testRetryWaitTooLong.

public void testRetryWaitTooLong() throws Exception {
    TimeValue maxWaitTime = TimeValue.timeValueMillis(10);
    int maxRetryTimes = 50;
    FailThenSuccessBackoffTransport fakeTransport = new FailThenSuccessBackoffTransport(HttpStatusCodes.STATUS_CODE_SERVER_ERROR, maxRetryTimes);
    JsonFactory jsonFactory = new JacksonFactory();
    MockGoogleCredential credential = RetryHttpInitializerWrapper.newMockCredentialBuilder().build();
    MockSleeper oneTimeSleeper = new MockSleeper() {

        @Override
        public void sleep(long millis) throws InterruptedException {
            Thread.sleep(maxWaitTime.getMillis());
            // important number, use this to get count
            super.sleep(0);
        }
    };
    RetryHttpInitializerWrapper retryHttpInitializerWrapper = new RetryHttpInitializerWrapper(credential, oneTimeSleeper, maxWaitTime);
    Compute client = new Compute.Builder(fakeTransport, jsonFactory, null).setHttpRequestInitializer(retryHttpInitializerWrapper).setApplicationName("test").build();
    HttpRequest request1 = client.getRequestFactory().buildRequest("Get", new GenericUrl("http://elasticsearch.com"), null);
    try {
        request1.execute();
        fail("Request should fail if wait too long");
    } catch (HttpResponseException e) {
        assertThat(e.getStatusCode(), equalTo(HttpStatusCodes.STATUS_CODE_SERVER_ERROR));
        // should only retry once.
        assertThat(oneTimeSleeper.getCount(), lessThan(maxRetryTimes));
    }
}
Also used : LowLevelHttpRequest(com.google.api.client.http.LowLevelHttpRequest) HttpRequest(com.google.api.client.http.HttpRequest) MockLowLevelHttpRequest(com.google.api.client.testing.http.MockLowLevelHttpRequest) JsonFactory(com.google.api.client.json.JsonFactory) MockGoogleCredential(com.google.api.client.googleapis.testing.auth.oauth2.MockGoogleCredential) HttpResponseException(com.google.api.client.http.HttpResponseException) GenericUrl(com.google.api.client.http.GenericUrl) JacksonFactory(com.google.api.client.json.jackson2.JacksonFactory) Compute(com.google.api.services.compute.Compute) TimeValue(org.elasticsearch.common.unit.TimeValue) MockSleeper(com.google.api.client.testing.util.MockSleeper)

Example 14 with GenericUrl

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

the class RetryHttpInitializerWrapperTests method testSimpleRetry.

public void testSimpleRetry() throws Exception {
    FailThenSuccessBackoffTransport fakeTransport = new FailThenSuccessBackoffTransport(HttpStatusCodes.STATUS_CODE_SERVER_ERROR, 3);
    MockGoogleCredential credential = RetryHttpInitializerWrapper.newMockCredentialBuilder().build();
    MockSleeper mockSleeper = new MockSleeper();
    RetryHttpInitializerWrapper retryHttpInitializerWrapper = new RetryHttpInitializerWrapper(credential, mockSleeper, TimeValue.timeValueSeconds(5));
    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(3));
    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 15 with GenericUrl

use of com.google.api.client.http.GenericUrl in project openhab1-addons by openhab.

the class GCalGoogleOAuth method getCredential.

/**
     * <p>
     * Perform OAuth2 authorization with Google server based on provided client_id and client_secret and
     * stores credential in local persistent store.
     * </p>
     *
     * @param newCredential If true try to obtain new credential (user interaction required)
     * @return Authorization credential object.
     */
public static Credential getCredential(boolean newCredential) {
    Credential credential = null;
    try {
        File tokenPath = null;
        String userdata = System.getProperty("smarthome.userdata");
        if (StringUtils.isEmpty(userdata)) {
            tokenPath = new File("etc");
        } else {
            tokenPath = new File(userdata);
        }
        File tokenFile = new File(tokenPath, TOKEN_PATH);
        FileDataStoreFactory fileDataStoreFactory = new FileDataStoreFactory(tokenFile);
        DataStore<StoredCredential> datastore = fileDataStoreFactory.getDataStore("gcal_oauth2_token");
        credential = loadCredential("openhab", datastore);
        if (credential == null && newCredential) {
            if (StringUtils.isBlank(client_id) || StringUtils.isBlank(client_secret)) {
                logger.warn("OAuth2 credentials are not provided");
                return null;
            }
            GenericUrl genericUrl = new GenericUrl("https://accounts.google.com/o/oauth2/device/code");
            Map<String, String> mapData = new HashMap<String, String>();
            mapData.put("client_id", client_id);
            mapData.put("scope", CalendarScopes.CALENDAR);
            UrlEncodedContent content = new UrlEncodedContent(mapData);
            HttpRequestFactory requestFactory = HTTP_TRANSPORT.createRequestFactory(new HttpRequestInitializer() {

                @Override
                public void initialize(HttpRequest request) {
                    request.setParser(new JsonObjectParser(JSON_FACTORY));
                }
            });
            HttpRequest postRequest = requestFactory.buildPostRequest(genericUrl, content);
            Device device = postRequest.execute().parseAs(Device.class);
            // no access token/secret specified so display the authorisation URL in the log
            logger.info("################################################################################################");
            logger.info("# Google-Integration: U S E R   I N T E R A C T I O N   R E Q U I R E D !!");
            logger.info("# 1. Open URL '{}'", device.verification_url);
            logger.info("# 2. Type provided code {} ", device.user_code);
            logger.info("# 3. Grant openHAB access to your Google calendar");
            logger.info("# 4. openHAB will automatically detect the permiossions and complete the authentication process");
            logger.info("# NOTE: You will only have {} mins before openHAB gives up waiting for the access!!!", device.expires_in);
            logger.info("################################################################################################");
            if (logger.isDebugEnabled()) {
                logger.debug("Got access code");
                logger.debug("user code : {}", device.user_code);
                logger.debug("device code : {}", device.device_code);
                logger.debug("expires in: {}", device.expires_in);
                logger.debug("interval : {}", device.interval);
                logger.debug("verification_url : {}", device.verification_url);
            }
            mapData = new HashMap<String, String>();
            mapData.put("client_id", client_id);
            mapData.put("client_secret", client_secret);
            mapData.put("code", device.device_code);
            mapData.put("grant_type", "http://oauth.net/grant_type/device/1.0");
            content = new UrlEncodedContent(mapData);
            postRequest = requestFactory.buildPostRequest(new GenericUrl("https://accounts.google.com/o/oauth2/token"), content);
            DeviceToken deviceToken;
            do {
                deviceToken = postRequest.execute().parseAs(DeviceToken.class);
                if (deviceToken.access_token != null) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("Got access token");
                        logger.debug("device access token: {}", deviceToken.access_token);
                        logger.debug("device token_type: {}", deviceToken.token_type);
                        logger.debug("device refresh_token: {}", deviceToken.refresh_token);
                        logger.debug("device expires_in: {}", deviceToken.expires_in);
                    }
                    break;
                }
                logger.debug("waiting for {} seconds", device.interval);
                Thread.sleep(device.interval * 1000);
            } while (true);
            StoredCredential dataCredential = new StoredCredential();
            dataCredential.setAccessToken(deviceToken.access_token);
            dataCredential.setRefreshToken(deviceToken.refresh_token);
            dataCredential.setExpirationTimeMilliseconds((long) deviceToken.expires_in * 1000);
            datastore.set(TOKEN_STORE_USER_ID, dataCredential);
            credential = loadCredential(TOKEN_STORE_USER_ID, datastore);
        }
    } catch (Exception e) {
        logger.warn("getCredential got exception: {}", e.getMessage());
    }
    return credential;
}
Also used : HttpRequest(com.google.api.client.http.HttpRequest) Credential(com.google.api.client.auth.oauth2.Credential) StoredCredential(com.google.api.client.auth.oauth2.StoredCredential) HashMap(java.util.HashMap) HttpRequestFactory(com.google.api.client.http.HttpRequestFactory) StoredCredential(com.google.api.client.auth.oauth2.StoredCredential) UrlEncodedContent(com.google.api.client.http.UrlEncodedContent) GenericUrl(com.google.api.client.http.GenericUrl) IOException(java.io.IOException) FileDataStoreFactory(com.google.api.client.util.store.FileDataStoreFactory) JsonObjectParser(com.google.api.client.json.JsonObjectParser) HttpRequestInitializer(com.google.api.client.http.HttpRequestInitializer) File(java.io.File)

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