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));
}
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();
}
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();
}
}
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;
}
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;
}
Aggregations