Search in sources :

Example 1 with GenericData

use of com.google.api.client.util.GenericData in project google-auth-library-java by google.

the class ComputeEngineCredentials method refreshAccessToken.

/**
 * Refresh the access token by getting it from the GCE metadata server
 */
@Override
public AccessToken refreshAccessToken() throws IOException {
    GenericUrl tokenUrl = new GenericUrl(getTokenServerEncodedUrl());
    HttpRequest request = transportFactory.create().createRequestFactory().buildGetRequest(tokenUrl);
    JsonObjectParser parser = new JsonObjectParser(OAuth2Utils.JSON_FACTORY);
    request.setParser(parser);
    request.getHeaders().set("Metadata-Flavor", "Google");
    request.setThrowExceptionOnExecuteError(false);
    HttpResponse response;
    try {
        response = request.execute();
    } catch (UnknownHostException exception) {
        throw new IOException("ComputeEngineCredentials cannot find the metadata server. This is" + " likely because code is not running on Google Compute Engine.", exception);
    }
    int statusCode = response.getStatusCode();
    if (statusCode == HttpStatusCodes.STATUS_CODE_NOT_FOUND) {
        throw new IOException(String.format("Error code %s trying to get security access token from" + " Compute Engine metadata for the default service account. This may be because" + " the virtual machine instance does not have permission scopes specified.", statusCode));
    }
    if (statusCode != HttpStatusCodes.STATUS_CODE_OK) {
        throw new IOException(String.format("Unexpected Error code %s trying to get security access" + " token from Compute Engine metadata for the default service account: %s", statusCode, response.parseAsString()));
    }
    InputStream content = response.getContent();
    if (content == null) {
        // Mock transports will have success code with empty content by default.
        throw new IOException("Empty content from metadata token server request.");
    }
    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;
    return new AccessToken(accessToken, new Date(expiresAtMilliseconds));
}
Also used : HttpRequest(com.google.api.client.http.HttpRequest) UnknownHostException(java.net.UnknownHostException) ObjectInputStream(java.io.ObjectInputStream) InputStream(java.io.InputStream) HttpResponse(com.google.api.client.http.HttpResponse) GenericUrl(com.google.api.client.http.GenericUrl) IOException(java.io.IOException) GenericData(com.google.api.client.util.GenericData) Date(java.util.Date) JsonObjectParser(com.google.api.client.json.JsonObjectParser)

Example 2 with GenericData

use of com.google.api.client.util.GenericData in project google-auth-library-java by google.

the class UserAuthorizer method getCredentialsFromCode.

/**
 * 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 = transportFactory.create().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);
    return UserCredentials.newBuilder().setClientId(clientId.getClientId()).setClientSecret(clientId.getClientSecret()).setRefreshToken(refreshToken).setAccessToken(accessToken).setHttpTransportFactory(transportFactory).setTokenServerUri(tokenServerUri).build();
}
Also used : HttpRequest(com.google.api.client.http.HttpRequest) HttpRequestFactory(com.google.api.client.http.HttpRequestFactory) UrlEncodedContent(com.google.api.client.http.UrlEncodedContent) HttpResponse(com.google.api.client.http.HttpResponse) GenericUrl(com.google.api.client.http.GenericUrl) URI(java.net.URI) GenericData(com.google.api.client.util.GenericData) Date(java.util.Date) GenericJson(com.google.api.client.json.GenericJson) JsonObjectParser(com.google.api.client.json.JsonObjectParser)

Example 3 with GenericData

use of com.google.api.client.util.GenericData in project google-api-java-client by google.

the class AuthKeyValueParser method parseAndClose.

public <T> T parseAndClose(Reader reader, Class<T> dataClass) throws IOException {
    try {
        ClassInfo classInfo = ClassInfo.of(dataClass);
        T newInstance = Types.newInstance(dataClass);
        BufferedReader breader = new BufferedReader(reader);
        while (true) {
            String line = breader.readLine();
            if (line == null) {
                break;
            }
            int equals = line.indexOf('=');
            String key = line.substring(0, equals);
            String value = line.substring(equals + 1);
            // get the field from the type information
            Field field = classInfo.getField(key);
            if (field != null) {
                Class<?> fieldClass = field.getType();
                Object fieldValue;
                if (fieldClass == boolean.class || fieldClass == Boolean.class) {
                    fieldValue = Boolean.valueOf(value);
                } else {
                    fieldValue = value;
                }
                FieldInfo.setFieldValue(field, newInstance, fieldValue);
            } else if (GenericData.class.isAssignableFrom(dataClass)) {
                GenericData data = (GenericData) newInstance;
                data.set(key, value);
            } else if (Map.class.isAssignableFrom(dataClass)) {
                @SuppressWarnings("unchecked") Map<Object, Object> map = (Map<Object, Object>) newInstance;
                map.put(key, value);
            }
        }
        return newInstance;
    } finally {
        reader.close();
    }
}
Also used : GenericData(com.google.api.client.util.GenericData) Field(java.lang.reflect.Field) BufferedReader(java.io.BufferedReader) Map(java.util.Map) ClassInfo(com.google.api.client.util.ClassInfo)

Example 4 with GenericData

use of com.google.api.client.util.GenericData in project java-docs-samples by GoogleCloudPlatform.

the class BuildIapRequest method getGoogleIdToken.

private static String getGoogleIdToken(String jwt) throws Exception {
    final GenericData tokenRequest = new GenericData().set("grant_type", JWT_BEARER_TOKEN_GRANT_TYPE).set("assertion", jwt);
    final UrlEncodedContent content = new UrlEncodedContent(tokenRequest);
    final HttpRequestFactory requestFactory = httpTransport.createRequestFactory();
    final HttpRequest request = requestFactory.buildPostRequest(new GenericUrl(OAUTH_TOKEN_URI), content).setParser(new JsonObjectParser(JacksonFactory.getDefaultInstance()));
    HttpResponse response;
    String idToken = null;
    response = request.execute();
    GenericData responseData = response.parseAs(GenericData.class);
    idToken = (String) responseData.get("id_token");
    return idToken;
}
Also used : HttpRequest(com.google.api.client.http.HttpRequest) HttpRequestFactory(com.google.api.client.http.HttpRequestFactory) JsonObjectParser(com.google.api.client.json.JsonObjectParser) UrlEncodedContent(com.google.api.client.http.UrlEncodedContent) HttpResponse(com.google.api.client.http.HttpResponse) GenericUrl(com.google.api.client.http.GenericUrl) GenericData(com.google.api.client.util.GenericData)

Example 5 with GenericData

use of com.google.api.client.util.GenericData in project google-api-java-client by google.

the class AuthKeyValueParser method parse.

public <T> T parse(InputStream content, Class<T> dataClass) throws IOException {
    ClassInfo classInfo = ClassInfo.of(dataClass);
    T newInstance = Types.newInstance(dataClass);
    BufferedReader reader = new BufferedReader(new InputStreamReader(content));
    while (true) {
        String line = reader.readLine();
        if (line == null) {
            break;
        }
        int equals = line.indexOf('=');
        String key = line.substring(0, equals);
        String value = line.substring(equals + 1);
        // get the field from the type information
        Field field = classInfo.getField(key);
        if (field != null) {
            Class<?> fieldClass = field.getType();
            Object fieldValue;
            if (fieldClass == boolean.class || fieldClass == Boolean.class) {
                fieldValue = Boolean.valueOf(value);
            } else {
                fieldValue = value;
            }
            FieldInfo.setFieldValue(field, newInstance, fieldValue);
        } else if (GenericData.class.isAssignableFrom(dataClass)) {
            GenericData data = (GenericData) newInstance;
            data.set(key, value);
        } else if (Map.class.isAssignableFrom(dataClass)) {
            @SuppressWarnings("unchecked") Map<Object, Object> map = (Map<Object, Object>) newInstance;
            map.put(key, value);
        }
    }
    return newInstance;
}
Also used : InputStreamReader(java.io.InputStreamReader) GenericData(com.google.api.client.util.GenericData) Field(java.lang.reflect.Field) BufferedReader(java.io.BufferedReader) Map(java.util.Map) ClassInfo(com.google.api.client.util.ClassInfo)

Aggregations

GenericData (com.google.api.client.util.GenericData)8 GenericUrl (com.google.api.client.http.GenericUrl)6 HttpRequest (com.google.api.client.http.HttpRequest)5 HttpResponse (com.google.api.client.http.HttpResponse)5 UrlEncodedContent (com.google.api.client.http.UrlEncodedContent)5 JsonObjectParser (com.google.api.client.json.JsonObjectParser)5 HttpRequestFactory (com.google.api.client.http.HttpRequestFactory)4 Date (java.util.Date)3 ClassInfo (com.google.api.client.util.ClassInfo)2 BufferedReader (java.io.BufferedReader)2 IOException (java.io.IOException)2 Field (java.lang.reflect.Field)2 Map (java.util.Map)2 HttpBackOffIOExceptionHandler (com.google.api.client.http.HttpBackOffIOExceptionHandler)1 HttpBackOffUnsuccessfulResponseHandler (com.google.api.client.http.HttpBackOffUnsuccessfulResponseHandler)1 BackOffRequired (com.google.api.client.http.HttpBackOffUnsuccessfulResponseHandler.BackOffRequired)1 NetHttpTransport (com.google.api.client.http.javanet.NetHttpTransport)1 GenericJson (com.google.api.client.json.GenericJson)1 JsonFactory (com.google.api.client.json.JsonFactory)1 ExponentialBackOff (com.google.api.client.util.ExponentialBackOff)1