com.google.api.client.http.UrlEncodedContent

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

1. 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);
    }
}

2. ClientParametersAuthenticationTest#test()

View license
public void test() throws Exception {
    HttpRequest request = new MockHttpTransport().createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL);
    ClientParametersAuthentication auth = new ClientParametersAuthentication(CLIENT_ID, CLIENT_SECRET);
    assertEquals(CLIENT_ID, auth.getClientId());
    assertEquals(CLIENT_SECRET, auth.getClientSecret());
    auth.intercept(request);
    UrlEncodedContent content = (UrlEncodedContent) request.getContent();
    @SuppressWarnings("unchecked") Map<String, ?> data = (Map<String, ?>) content.getData();
    assertEquals(CLIENT_ID, data.get("client_id"));
    assertEquals(CLIENT_SECRET, data.get("client_secret"));
}

3. ClientParametersAuthenticationTest#test_noSecret()

View license
public void test_noSecret() throws Exception {
    HttpRequest request = new MockHttpTransport().createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL);
    ClientParametersAuthentication auth = new ClientParametersAuthentication(CLIENT_ID, null);
    assertEquals(CLIENT_ID, auth.getClientId());
    assertNull(auth.getClientSecret());
    auth.intercept(request);
    UrlEncodedContent content = (UrlEncodedContent) request.getContent();
    @SuppressWarnings("unchecked") Map<String, ?> data = (Map<String, ?>) content.getData();
    assertEquals(CLIENT_ID, data.get("client_id"));
    assertNull(data.get("client_secret"));
}

4. MethodOverrideTest#testInterceptMaxLength()

View license
public void testInterceptMaxLength() throws IOException {
    HttpTransport transport = new MockHttpTransport();
    GenericUrl url = new GenericUrl(HttpTesting.SIMPLE_URL);
    url.set("a", "foo");
    HttpRequest request = transport.createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL);
    new MethodOverride().intercept(request);
    assertEquals(HttpMethods.GET, request.getRequestMethod());
    assertNull(request.getHeaders().get(MethodOverride.HEADER));
    assertNull(request.getContent());
    char[] arr = new char[MethodOverride.MAX_URL_LENGTH];
    Arrays.fill(arr, 'x');
    url.set("a", new String(arr));
    request.setUrl(url);
    new MethodOverride().intercept(request);
    assertEquals(HttpMethods.POST, request.getRequestMethod());
    assertEquals(HttpMethods.GET, request.getHeaders().get(MethodOverride.HEADER));
    assertEquals(HttpTesting.SIMPLE_GENERIC_URL, request.getUrl());
    char[] arr2 = new char[arr.length + 2];
    Arrays.fill(arr2, 'x');
    arr2[0] = 'a';
    arr2[1] = '=';
    UrlEncodedContent content = (UrlEncodedContent) request.getContent();
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    content.writeTo(out);
    assertEquals(new String(arr2), out.toString());
}

5. 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;
}

6. 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;
}

7. 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;
}