com.google.api.client.http.HttpRequestFactory

Here are the examples of the java api class com.google.api.client.http.HttpRequestFactory taken from open source projects.

1. CredentialTest#subtestRefreshToken_request()

View license
private void subtestRefreshToken_request(AccessTokenTransport transport, int expectedCalls) throws Exception {
    Credential credential = new Credential.Builder(BearerToken.queryParameterAccessMethod()).setTransport(transport).setJsonFactory(JSON_FACTORY).setTokenServerUrl(TOKEN_SERVER_URL).setClientAuthentication(new BasicAuthentication(CLIENT_ID, CLIENT_SECRET)).build().setRefreshToken(REFRESH_TOKEN).setAccessToken(ACCESS_TOKEN);
    HttpRequestFactory requestFactory = transport.createRequestFactory(credential);
    HttpRequest request = requestFactory.buildDeleteRequest(HttpTesting.SIMPLE_GENERIC_URL);
    request.setThrowExceptionOnExecuteError(false);
    request.execute();
    assertEquals(expectedCalls, transport.calls);
}

2. HttpCredentialsAdapterTest#initialize_populatesOAuth2Credentials()

View license
@Test
public void initialize_populatesOAuth2Credentials() throws IOException {
    final String accessToken = "1/MkSJoj1xsli0AccessToken_NKPY2";
    final String expectedAuthorization = InternalAuthHttpConstants.BEARER_PREFIX + accessToken;
    MockTokenServerTransport transport = new MockTokenServerTransport();
    transport.addClient(CLIENT_ID, CLIENT_SECRET);
    transport.addRefreshToken(REFRESH_TOKEN, accessToken);
    OAuth2Credentials credentials = new UserCredentials(CLIENT_ID, CLIENT_SECRET, REFRESH_TOKEN, null, transport, null);
    HttpCredentialsAdapter adapter = new HttpCredentialsAdapter(credentials);
    HttpRequestFactory requestFactory = transport.createRequestFactory();
    HttpRequest request = requestFactory.buildGetRequest(new GenericUrl("http://foo"));
    adapter.initialize(request);
    HttpHeaders requestHeaders = request.getHeaders();
    String authorizationHeader = requestHeaders.getAuthorization();
    assertEquals(authorizationHeader, expectedAuthorization);
}

3. HttpCredentialsAdapterTest#initialize_noURI()

View license
@Test
public void initialize_noURI() throws IOException {
    final String accessToken = "1/MkSJoj1xsli0AccessToken_NKPY2";
    final String expectedAuthorization = InternalAuthHttpConstants.BEARER_PREFIX + accessToken;
    MockTokenServerTransport transport = new MockTokenServerTransport();
    transport.addClient(CLIENT_ID, CLIENT_SECRET);
    transport.addRefreshToken(REFRESH_TOKEN, accessToken);
    OAuth2Credentials credentials = new UserCredentials(CLIENT_ID, CLIENT_SECRET, REFRESH_TOKEN, null, transport, null);
    HttpCredentialsAdapter adapter = new HttpCredentialsAdapter(credentials);
    HttpRequestFactory requestFactory = transport.createRequestFactory();
    HttpRequest request = requestFactory.buildGetRequest(null);
    adapter.initialize(request);
    HttpHeaders requestHeaders = request.getHeaders();
    String authorizationHeader = requestHeaders.getAuthorization();
    assertEquals(authorizationHeader, expectedAuthorization);
}

4. GooglePlusSample#run()

View license
private static void run() throws IOException {
    HttpRequestFactory requestFactory = HTTP_TRANSPORT.createRequestFactory(new HttpRequestInitializer() {

        @Override
        public void initialize(HttpRequest request) {
            request.setParser(new JsonObjectParser(JSON_FACTORY));
        }
    });
    PlusUrl url = PlusUrl.listPublicActivities(USER_ID).setMaxResults(MAX_RESULTS);
    url.put("fields", "items(id,url,object(content,plusoners/totalItems))");
    HttpRequest request = requestFactory.buildGetRequest(url);
    parseResponse(request.execute());
}

5. LocalDevelopmentDatastore#clear()

View license
/**
   * Clears all data in the Datastore.
   *
   * @throws LocalDevelopmentDatastoreException
   */
public void clear() throws LocalDevelopmentDatastoreException {
    HttpRequestFactory client = remoteRpc.getHttpRequestFactory();
    try {
        Map<String, String> params = new HashMap<String, String>();
        params.put("action", "Clear Datastore");
        UrlEncodedContent content = new UrlEncodedContent(params);
        GenericUrl url = new GenericUrl(host + "/_ah/admin/datastore");
        HttpResponse httpResponse = client.buildPostRequest(url, content).execute();
        if (!httpResponse.isSuccessStatusCode()) {
            throw new LocalDevelopmentDatastoreException("Clear Datastore returned http status " + httpResponse.getStatusCode());
        }
    } catch (IOException e) {
        throw new LocalDevelopmentDatastoreException("Exception trying to clear the dev datastore", e);
    }
}

6. LocalDevelopmentDatastore#stopDatastoreInternal()

View license
void stopDatastoreInternal() throws LocalDevelopmentDatastoreException {
    // No need to kill the process we started, this function will take care of it.
    HttpRequestFactory client = remoteRpc.getHttpRequestFactory();
    Map<String, String> params = new HashMap<String, String>();
    UrlEncodedContent content = new UrlEncodedContent(params);
    GenericUrl url = new GenericUrl(host + "/_ah/admin/quit");
    try {
        HttpResponse httpResponse = client.buildPostRequest(url, content).execute();
        if (!httpResponse.isSuccessStatusCode()) {
            throw new LocalDevelopmentDatastoreException("Request to shutdown local datastore returned http error code " + httpResponse.getStatusCode());
        }
    } catch (IOException e) {
        throw new LocalDevelopmentDatastoreException("Exception trying to stop the dev datastore", e);
    }
}

7. DatastoreFactoryTest#makeClient_WithCredential()

View license
/**
   * Specifying a credential, but not a transport, the factory will use the
   * transport from the credential.
   */
@Test
public void makeClient_WithCredential() {
    NetHttpTransport transport = new NetHttpTransport();
    GoogleCredential credential = new GoogleCredential.Builder().setTransport(transport).build();
    DatastoreOptions options = new DatastoreOptions.Builder().projectId(PROJECT_ID).credential(credential).build();
    HttpRequestFactory f = factory.makeClient(options);
    assertEquals(transport, f.getTransport());
}

8. DatastoreFactoryTest#makeClient_WithCredentialTransport()

View license
/**
   * Specifying both credential and transport, the factory will use the
   * transport specified and not the one in the credential.
   */
@Test
public void makeClient_WithCredentialTransport() {
    NetHttpTransport credTransport = new NetHttpTransport();
    NetHttpTransport transport = new NetHttpTransport();
    GoogleCredential credential = new GoogleCredential.Builder().setTransport(credTransport).build();
    DatastoreOptions options = new DatastoreOptions.Builder().projectId(PROJECT_ID).credential(credential).transport(transport).build();
    HttpRequestFactory f = factory.makeClient(options);
    assertNotSame(credTransport, f.getTransport());
    assertEquals(transport, f.getTransport());
}

9. DatastoreFactoryTest#makeClient_Default()

View license
/**
   * Without specifying a credential or transport, the factory will create
   * a default transport on its own.
   */
@Test
public void makeClient_Default() {
    DatastoreOptions options = new DatastoreOptions.Builder().projectId(PROJECT_ID).build();
    HttpRequestFactory f = factory.makeClient(options);
    assertNotNull(f.getTransport());
    assertTrue(f.getTransport() instanceof NetHttpTransport);
}

10. HttpRequestIT#executeAsync()

Project: pinpoint
Source File: HttpRequestIT.java
View license
@Test
public void executeAsync() throws Exception {
    HttpTransport NET_HTTP_TRANSPORT = new NetHttpTransport();
    HttpRequestFactory requestFactory = NET_HTTP_TRANSPORT.createRequestFactory(new HttpRequestInitializer() {

        @Override
        public void initialize(HttpRequest request) {
        }
    });
    GenericUrl url = new GenericUrl("http://google.com");
    HttpRequest request = null;
    HttpResponse response = null;
    try {
        request = requestFactory.buildGetRequest(url);
        response = request.executeAsync().get();
        response.disconnect();
    } catch (IOException ignored) {
    } finally {
        if (response != null) {
            response.disconnect();
        }
    }
    Method executeAsyncMethod = HttpRequest.class.getDeclaredMethod("executeAsync", Executor.class);
    Method callMethod = Callable.class.getDeclaredMethod("call");
    Method executeMethod = HttpRequest.class.getDeclaredMethod("execute");
    PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance();
    verifier.printCache();
    // async
    verifier.verifyTrace(Expectations.async(Expectations.event("GOOGLE_HTTP_CLIENT_INTERNAL", executeAsyncMethod), Expectations.event("ASYNC", "Asynchronous Invocation")));
}

11. HttpRequestIT#execute()

Project: pinpoint
Source File: HttpRequestIT.java
View license
@Test
public void execute() throws Exception {
    HttpTransport NET_HTTP_TRANSPORT = new NetHttpTransport();
    HttpRequestFactory requestFactory = NET_HTTP_TRANSPORT.createRequestFactory(new HttpRequestInitializer() {

        @Override
        public void initialize(HttpRequest request) {
        }
    });
    GenericUrl url = new GenericUrl("http://google.com");
    HttpRequest request = null;
    HttpResponse response = null;
    try {
        request = requestFactory.buildGetRequest(url);
        response = request.execute();
        response.disconnect();
    } catch (IOException ignored) {
    } finally {
        if (response != null) {
            response.disconnect();
        }
    }
    Method executeMethod = HttpRequest.class.getDeclaredMethod("execute");
    PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance();
    verifier.printCache();
    verifier.verifyTrace(Expectations.event("GOOGLE_HTTP_CLIENT_INTERNAL", executeMethod));
}

12. CredentialTest#subtestConstructor_expired()

View license
private HttpRequest subtestConstructor_expired(Credential.AccessMethod method, final CheckAuth checkAuth) throws Exception {
    final Credential credential = new Credential.Builder(method).setTransport(new AccessTokenTransport()).setJsonFactory(JSON_FACTORY).setTokenServerUrl(TOKEN_SERVER_URL).setClientAuthentication(new BasicAuthentication(CLIENT_ID, CLIENT_SECRET)).build().setAccessToken(ACCESS_TOKEN).setRefreshToken(REFRESH_TOKEN);
    class MyTransport extends MockHttpTransport {

        boolean resetAccessToken;

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

                @Override
                public LowLevelHttpResponse execute() {
                    MockLowLevelHttpResponse response = new MockLowLevelHttpResponse();
                    if (!checkAuth.checkAuth(this)) {
                        response.setStatusCode(HttpStatusCodes.STATUS_CODE_UNAUTHORIZED);
                        if (resetAccessToken) {
                            credential.setAccessToken(NEW_ACCESS_TOKEN);
                        }
                    }
                    return response;
                }
            };
        }
    }
    MyTransport transport = new MyTransport();
    HttpRequestFactory requestFactory = transport.createRequestFactory(credential);
    HttpRequest request = requestFactory.buildDeleteRequest(HttpTesting.SIMPLE_GENERIC_URL);
    request.execute();
    credential.setAccessToken(ACCESS_TOKEN);
    transport.resetAccessToken = true;
    request.execute();
    return request;
}

13. CredentialTest#subtestConstructor()

View license
private HttpRequest subtestConstructor(Credential credential) throws Exception {
    MockHttpTransport transport = new MockHttpTransport();
    HttpRequestFactory requestFactory = transport.createRequestFactory(credential);
    HttpRequest request = requestFactory.buildDeleteRequest(HttpTesting.SIMPLE_GENERIC_URL);
    request.execute();
    return request;
}

14. TokenRequest#executeUnparsed()

View license
/**
   * Executes request for an access token, and returns the HTTP response.
   *
   * <p>
   * To execute and parse the response to {@link TokenResponse}, instead use {@link #execute()}.
   * </p>
   *
   * <p>
   * Callers should call {@link HttpResponse#disconnect} when the returned HTTP response object is
   * no longer needed. However, {@link HttpResponse#disconnect} does not have to be called if the
   * response stream is properly closed. Example usage:
   * </p>
   *
   * <pre>
     HttpResponse response = tokenRequest.executeUnparsed();
     try {
       // process the HTTP response object
     } finally {
       response.disconnect();
     }
   * </pre>
   *
   * @return successful access token response, which can then be parsed directly using
   *         {@link HttpResponse#parseAs(Class)} or some other parsing method
   * @throws TokenResponseException for an error response
   */
public final HttpResponse executeUnparsed() throws IOException {
    // must set clientAuthentication as last execute interceptor in case it needs to sign request
    HttpRequestFactory requestFactory = transport.createRequestFactory(new HttpRequestInitializer() {

        public void initialize(HttpRequest request) throws IOException {
            if (requestInitializer != null) {
                requestInitializer.initialize(request);
            }
            final HttpExecuteInterceptor interceptor = request.getInterceptor();
            request.setInterceptor(new HttpExecuteInterceptor() {

                public void intercept(HttpRequest request) throws IOException {
                    if (interceptor != null) {
                        interceptor.intercept(request);
                    }
                    if (clientAuthentication != null) {
                        clientAuthentication.intercept(request);
                    }
                }
            });
        }
    });
    // make request
    HttpRequest request = requestFactory.buildPostRequest(tokenServerUrl, new UrlEncodedContent(this));
    request.setParser(new JsonObjectParser(jsonFactory));
    request.setThrowExceptionOnExecuteError(false);
    HttpResponse response = request.execute();
    if (response.isSuccessStatusCode()) {
        return response;
    }
    throw TokenResponseException.from(jsonFactory, response);
}

15. AbstractOAuthGetToken#execute()

View license
/**
   * Executes the HTTP request for a temporary or long-lived token.
   *
   * @return OAuth credentials response object
   */
public final OAuthCredentialsResponse execute() throws IOException {
    HttpRequestFactory requestFactory = transport.createRequestFactory();
    HttpRequest request = requestFactory.buildRequest(usePost ? HttpMethods.POST : HttpMethods.GET, this, null);
    createParameters().intercept(request);
    HttpResponse response = request.execute();
    response.setContentLoggingLimit(0);
    OAuthCredentialsResponse oauthResponse = new OAuthCredentialsResponse();
    UrlEncodedParser.parse(response.parseAsString(), oauthResponse);
    return oauthResponse;
}

16. DailyMotionSample#run()

View license
private static void run() throws Exception {
    HttpRequestFactory requestFactory = HTTP_TRANSPORT.createRequestFactory(new HttpRequestInitializer() {

        @Override
        public void initialize(HttpRequest request) {
            request.setParser(new JsonObjectParser(JSON_FACTORY));
        }
    });
    DailyMotionUrl url = new DailyMotionUrl("https://api.dailymotion.com/videos/");
    url.fields = "id,tags,title,url";
    HttpRequest request = requestFactory.buildGetRequest(url);
    VideoFeed videoFeed = request.execute().parseAs(VideoFeed.class);
    if (videoFeed.list.isEmpty()) {
        System.out.println("No videos found.");
    } else {
        if (videoFeed.hasMore) {
            System.out.print("First ");
        }
        System.out.println(videoFeed.list.size() + " videos found:");
        for (Video video : videoFeed.list) {
            System.out.println();
            System.out.println("-----------------------------------------------");
            System.out.println("ID: " + video.id);
            System.out.println("Title: " + video.title);
            System.out.println("Tags: " + video.tags);
            System.out.println("URL: " + video.url);
        }
    }
}

17. DatastoreFactoryTest#makeClient_WithTransport()

View license
/**
   * Specifying a transport, but not a credential, the factory will use the
   * transport specified.
   */
@Test
public void makeClient_WithTransport() {
    NetHttpTransport transport = new NetHttpTransport();
    DatastoreOptions options = new DatastoreOptions.Builder().projectId(PROJECT_ID).transport(transport).build();
    HttpRequestFactory f = factory.makeClient(options);
    assertEquals(transport, f.getTransport());
}

18. LenientAuthorizationCodeTokenRequest#executeLeniently()

View license
/**
     * Executes request for an access token, and returns the HTTP response.
     * <p>
     * To execute and parse the response to {@link TokenResponse}, instead use
     * {@link #execute()}.
     * </p>
     * <p>
     * Callers should call {@link HttpResponse#disconnect} when the returned
     * HTTP response object is no longer needed. However,
     * {@link HttpResponse#disconnect} does not have to be called if the
     * response stream is properly closed. Example usage:
     * </p>
     * 
     * <pre>
     * HttpResponse response = tokenRequest.executeUnparsed();
     * try {
     *     // process the HTTP response object
     * } finally {
     *     response.disconnect();
     * }
     * </pre>
     * 
     * @return successful access token response, which can then be parsed
     *         directly using {@link HttpResponse#parseAs(Class)} or some other
     *         parsing method
     * @throws TokenResponseException for an error response
     */
private TokenResponse executeLeniently() throws IOException {
    // must set clientAuthentication as last execute interceptor in case it
    // needs to sign request
    HttpRequestFactory requestFactory = getTransport().createRequestFactory(new HttpRequestInitializer() {

        public void initialize(HttpRequest request) throws IOException {
            if (getRequestInitializer() != null) {
                getRequestInitializer().initialize(request);
            }
            final HttpExecuteInterceptor interceptor = request.getInterceptor();
            request.setInterceptor(new HttpExecuteInterceptor() {

                public void intercept(HttpRequest request) throws IOException {
                    if (interceptor != null) {
                        interceptor.intercept(request);
                    }
                    if (getClientAuthentication() != null) {
                        getClientAuthentication().intercept(request);
                    }
                }
            });
        }
    });
    // make request
    HttpRequest request = requestFactory.buildPostRequest(getTokenServerUrl(), new UrlEncodedContent(this));
    request.setParser(new JsonObjectParser(getJsonFactory()));
    request.setThrowExceptionOnExecuteError(false);
    HttpResponse response = request.execute();
    if (response.isSuccessStatusCode()) {
        if (!HttpResponseUtils.hasMessageBody(response)) {
            return null;
        }
        // check and see if status code is 200 but has error response
        String responseContent = HttpResponseUtils.parseAsStringWithoutClosing(response);
        TokenResponse tokenResponse = response.getRequest().getParser().parseAndClose(new StringReader(responseContent), TokenResponse.class);
        if (tokenResponse.containsKey("error")) {
            throw LenientTokenResponseException.from(getJsonFactory(), response, responseContent);
        }
        return response.getRequest().getParser().parseAndClose(new StringReader(responseContent), TokenResponse.class);
    }
    throw TokenResponseException.from(getJsonFactory(), response);
}

19. DatastoreFactory#newRemoteRpc()

View license
protected RemoteRpc newRemoteRpc(DatastoreOptions options) {
    checkNotNull(options);
    HttpRequestFactory client = makeClient(options);
    return new RemoteRpc(client, options.getInitializer(), buildProjectEndpoint(options));
}

20. HttpCredentialsAdapterTest#initialize_populatesOAuth2Credentials_handle401()

View license
@Test
public void initialize_populatesOAuth2Credentials_handle401() throws IOException {
    final String accessToken = "1/MkSJoj1xsli0AccessToken_NKPY2";
    final String accessToken2 = "2/MkSJoj1xsli0AccessToken_NKPY2";
    final MockTokenServerTransport tokenServerTransport = new MockTokenServerTransport();
    tokenServerTransport.addClient(CLIENT_ID, CLIENT_SECRET);
    tokenServerTransport.addRefreshToken(REFRESH_TOKEN, accessToken);
    OAuth2Credentials credentials = new UserCredentials(CLIENT_ID, CLIENT_SECRET, REFRESH_TOKEN, null, tokenServerTransport, null);
    credentials.refresh();
    HttpCredentialsAdapter adapter = new HttpCredentialsAdapter(credentials);
    HttpTransport primaryHttpTransport = new MockTokenCheckingTransport(tokenServerTransport, REFRESH_TOKEN);
    HttpRequestFactory requestFactory = primaryHttpTransport.createRequestFactory();
    HttpRequest request = requestFactory.buildGetRequest(new GenericUrl("http://foo"));
    adapter.initialize(request);
    // now switch out the access token so that the original one is invalid,
    //   requiring a refresh of the access token
    tokenServerTransport.addRefreshToken(REFRESH_TOKEN, accessToken2);
    HttpResponse response = request.execute();
    // make sure that the request is successful despite the invalid access token
    assertEquals(200, response.getStatusCode());
    assertEquals(MockTokenCheckingTransport.SUCCESS_CONTENT, response.parseAsString());
}

21. UserCredentials#refreshAccessToken()

View license
/**
   * Refreshes the OAuth2 access token by getting a new access token from the refresh token
   */
@Override
public AccessToken refreshAccessToken() throws IOException {
    if (refreshToken == null) {
        throw new IllegalStateException("UserCredentials instance cannot refresh because there is no" + " refresh token.");
    }
    GenericData tokenRequest = new GenericData();
    tokenRequest.set("client_id", clientId);
    tokenRequest.set("client_secret", clientSecret);
    tokenRequest.set("refresh_token", refreshToken);
    tokenRequest.set("grant_type", GRANT_TYPE);
    UrlEncodedContent content = new UrlEncodedContent(tokenRequest);
    HttpRequestFactory requestFactory = transport.createRequestFactory();
    HttpRequest request = requestFactory.buildPostRequest(new GenericUrl(tokenServerUri), content);
    request.setParser(new JsonObjectParser(OAuth2Utils.JSON_FACTORY));
    HttpResponse response = request.execute();
    GenericData responseData = response.parseAs(GenericData.class);
    String accessToken = OAuth2Utils.validateString(responseData, "access_token", PARSE_ERROR_PREFIX);
    int expiresInSeconds = OAuth2Utils.validateInt32(responseData, "expires_in", PARSE_ERROR_PREFIX);
    long expiresAtMilliseconds = clock.currentTimeMillis() + expiresInSeconds * 1000;
    AccessToken access = new AccessToken(accessToken, new Date(expiresAtMilliseconds));
    return access;
}

22. UserAuthorizer#revokeAuthorization()

View license
/**
   * Revokes the authorization for tokens stored for the user.
   * @param userId Application's identifier for the end user.
   * @throws IOException An error calling the revoke API or deleting the state.
   */
public void revokeAuthorization(String userId) throws IOException {
    Preconditions.checkNotNull(userId);
    if (tokenStore == null) {
        throw new IllegalStateException("Method cannot be called if token store is not specified.");
    }
    String tokenData = tokenStore.load(userId);
    if (tokenData == null) {
        return;
    }
    IOException deleteTokenException = null;
    try {
        // Delete the stored version first. If token reversion fails it is less harmful to have an
        // non revoked token to hold on to a potentially revoked token.
        tokenStore.delete(userId);
    } catch (IOException e) {
        deleteTokenException = e;
    }
    GenericJson tokenJson = OAuth2Utils.parseJson(tokenData);
    String accessTokenValue = OAuth2Utils.validateOptionalString(tokenJson, "access_token", TOKEN_STORE_ERROR);
    String refreshToken = OAuth2Utils.validateOptionalString(tokenJson, "refresh_token", TOKEN_STORE_ERROR);
    // If both tokens are present, either can be used
    String revokeToken = (refreshToken != null) ? refreshToken : accessTokenValue;
    GenericUrl revokeUrl = new GenericUrl(OAuth2Utils.TOKEN_REVOKE_URI);
    revokeUrl.put("token", revokeToken);
    HttpRequestFactory requestFactory = transport.createRequestFactory();
    HttpRequest tokenRequest = requestFactory.buildGetRequest(revokeUrl);
    tokenRequest.execute();
    if (deleteTokenException != null) {
        throw deleteTokenException;
    }
}

23. UserAuthorizer#getCredentialsFromCode()

View license
/**
   * Returns a UserCredentials instance by exchanging an OAuth2 authorization code for tokens.
   *
   * @param code Code returned from OAuth2 consent prompt.
   * @param baseUri The URI to resolve the OAuth2 callback URI relative to.
   * @return the UserCredentials instance created from the authorization code.
   * @throws IOException An error from the server API call to get the tokens.
   */
public UserCredentials getCredentialsFromCode(String code, URI baseUri) throws IOException {
    Preconditions.checkNotNull(code);
    URI resolvedCallbackUri = getCallbackUri(baseUri);
    GenericData tokenData = new GenericData();
    tokenData.put("code", code);
    tokenData.put("client_id", clientId.getClientId());
    tokenData.put("client_secret", clientId.getClientSecret());
    tokenData.put("redirect_uri", resolvedCallbackUri);
    tokenData.put("grant_type", "authorization_code");
    UrlEncodedContent tokenContent = new UrlEncodedContent(tokenData);
    HttpRequestFactory requestFactory = transport.createRequestFactory();
    HttpRequest tokenRequest = requestFactory.buildPostRequest(new GenericUrl(tokenServerUri), tokenContent);
    tokenRequest.setParser(new JsonObjectParser(OAuth2Utils.JSON_FACTORY));
    HttpResponse tokenResponse = tokenRequest.execute();
    GenericJson parsedTokens = tokenResponse.parseAs(GenericJson.class);
    String accessTokenValue = OAuth2Utils.validateString(parsedTokens, "access_token", FETCH_TOKEN_ERROR);
    int expiresInSecs = OAuth2Utils.validateInt32(parsedTokens, "expires_in", FETCH_TOKEN_ERROR);
    Date expirationTime = new Date(new Date().getTime() + expiresInSecs * 1000);
    AccessToken accessToken = new AccessToken(accessTokenValue, expirationTime);
    String refreshToken = OAuth2Utils.validateOptionalString(parsedTokens, "refresh_token", FETCH_TOKEN_ERROR);
    UserCredentials credentials = new UserCredentials(clientId.getClientId(), clientId.getClientSecret(), refreshToken, accessToken, transport, tokenServerUri);
    return credentials;
}

24. ServiceAccountCredentials#refreshAccessToken()

View license
/**
   * Refreshes the OAuth2 access token by getting a new access token using a JSON Web Token (JWT).
   */
@Override
public AccessToken refreshAccessToken() throws IOException {
    if (createScopedRequired()) {
        throw new IOException("Scopes not configured for service account. Scoped should be specifed" + " by calling createScoped or passing scopes to constructor.");
    }
    JsonWebSignature.Header header = new JsonWebSignature.Header();
    header.setAlgorithm("RS256");
    header.setType("JWT");
    header.setKeyId(privateKeyId);
    JsonWebToken.Payload payload = new JsonWebToken.Payload();
    long currentTime = clock.currentTimeMillis();
    payload.setIssuer(clientEmail);
    payload.setAudience(OAuth2Utils.TOKEN_SERVER_URI.toString());
    payload.setIssuedAtTimeSeconds(currentTime / 1000);
    payload.setExpirationTimeSeconds(currentTime / 1000 + 3600);
    payload.setSubject(null);
    payload.put("scope", Joiner.on(' ').join(scopes));
    JsonFactory jsonFactory = OAuth2Utils.JSON_FACTORY;
    String assertion = null;
    try {
        assertion = JsonWebSignature.signUsingRsaSha256(privateKey, jsonFactory, header, payload);
    } catch (GeneralSecurityException e) {
        throw OAuth2Utils.exceptionWithCause(new IOException("Error signing service account access token request with private key."), e);
    }
    GenericData tokenRequest = new GenericData();
    tokenRequest.set("grant_type", GRANT_TYPE);
    tokenRequest.set("assertion", assertion);
    UrlEncodedContent content = new UrlEncodedContent(tokenRequest);
    HttpRequestFactory requestFactory = transport.createRequestFactory();
    HttpRequest request = requestFactory.buildPostRequest(new GenericUrl(tokenServerUri), content);
    request.setParser(new JsonObjectParser(jsonFactory));
    HttpResponse response;
    try {
        response = request.execute();
    } catch (IOException e) {
        throw OAuth2Utils.exceptionWithCause(new IOException("Error getting access token for service account: "), e);
    }
    GenericData responseData = response.parseAs(GenericData.class);
    String accessToken = OAuth2Utils.validateString(responseData, "access_token", PARSE_ERROR_PREFIX);
    int expiresInSeconds = OAuth2Utils.validateInt32(responseData, "expires_in", PARSE_ERROR_PREFIX);
    long expiresAtMilliseconds = clock.currentTimeMillis() + expiresInSeconds * 1000;
    AccessToken access = new AccessToken(accessToken, new Date(expiresAtMilliseconds));
    return access;
}

25. AbstractGoogleClientRequest#initializeMediaDownload()

View license
/** Initializes the media HTTP downloader. */
protected final void initializeMediaDownload() {
    HttpRequestFactory requestFactory = abstractGoogleClient.getRequestFactory();
    this.downloader = new MediaHttpDownloader(requestFactory.getTransport(), requestFactory.getInitializer());
}

26. AbstractGoogleClientRequest#initializeMediaUpload()

View license
/**
   * Initializes the media HTTP uploader based on the media content.
   *
   * @param mediaContent media content
   */
protected final void initializeMediaUpload(AbstractInputStreamContent mediaContent) {
    HttpRequestFactory requestFactory = abstractGoogleClient.getRequestFactory();
    this.uploader = new MediaHttpUploader(mediaContent, requestFactory.getTransport(), requestFactory.getInitializer());
    this.uploader.setInitiationRequestMethod(requestMethod);
    if (httpContent != null) {
        this.uploader.setMetadata(httpContent);
    }
}