Here are the examples of the java api class com.google.api.client.auth.oauth2.Credential taken from open source projects.
1. FileCredentialStoreTest#testStoreCredentials()
Project: google-oauth-java-client
File: FileCredentialStoreTest.java
File: FileCredentialStoreTest.java
public void testStoreCredentials() throws Exception { Credential expected = createCredential(); File file = createTempFile(); file.delete(); FileCredentialStore store = new FileCredentialStore(file, JSON_FACTORY); store = new FileCredentialStore(file, JSON_FACTORY); store.store(USER_ID, expected); store = new FileCredentialStore(file, JSON_FACTORY); Credential actual = createEmptyCredential(); boolean loaded = store.load(USER_ID, actual); assertTrue(loaded); assertEquals(ACCESS_TOKEN, actual.getAccessToken()); assertEquals(REFRESH_TOKEN, actual.getRefreshToken()); assertEquals(EXPIRES_IN, actual.getExpirationTimeMilliseconds().longValue()); }
2. DefaultCredentialProviderTest#testDefaultCredentialCaches()
Project: google-api-java-client
File: DefaultCredentialProviderTest.java
File: DefaultCredentialProviderTest.java
public void testDefaultCredentialCaches() throws IOException { HttpTransport transport = new MockHttpTransport(); TestDefaultCredentialProvider testProvider = new TestDefaultCredentialProvider(); testProvider.addType(DefaultCredentialProvider.APP_ENGINE_CREDENTIAL_CLASS, MockAppEngineCredential.class); testProvider.addType(GAE_SIGNAL_CLASS, MockAppEngineSystemProperty.class); Credential firstCall = testProvider.getDefaultCredential(transport, JSON_FACTORY); assertNotNull(firstCall); Credential secondCall = testProvider.getDefaultCredential(transport, JSON_FACTORY); assertSame(firstCall, secondCall); }
3. FileCredentialStoreTest#testMigrateTo()
Project: google-oauth-java-client
File: FileCredentialStoreTest.java
File: FileCredentialStoreTest.java
public void testMigrateTo() throws Exception { // create old store File file = createTempFile(); FileCredentialStore store = new FileCredentialStore(file, JSON_FACTORY); Credential expected = createCredential(); store.store(USER_ID, expected); // migrate to new store File dataDir = Files.createTempDir(); dataDir.deleteOnExit(); FileDataStoreFactory newFactory = new FileDataStoreFactory(dataDir); store.migrateTo(newFactory); // check new store DataStore<StoredCredential> newStore = newFactory.getDataStore(StoredCredential.DEFAULT_DATA_STORE_ID); assertEquals(ImmutableSet.of(USER_ID), newStore.keySet()); StoredCredential actual = newStore.get(USER_ID); assertEquals(expected.getAccessToken(), actual.getAccessToken()); assertEquals(expected.getRefreshToken(), actual.getRefreshToken()); assertEquals(expected.getExpirationTimeMilliseconds(), actual.getExpirationTimeMilliseconds()); }
4. FileCredentialStoreTest#createCredential()
Project: google-oauth-java-client
File: FileCredentialStoreTest.java
File: FileCredentialStoreTest.java
private Credential createCredential() { Credential access = new Credential.Builder(BearerToken.queryParameterAccessMethod()).setTransport(new AccessTokenTransport()).setJsonFactory(JSON_FACTORY).setTokenServerUrl(TOKEN_SERVER_URL).setClientAuthentication(new BasicAuthentication(CLIENT_ID, CLIENT_SECRET)).build().setAccessToken(ACCESS_TOKEN).setRefreshToken(REFRESH_TOKEN).setExpirationTimeMilliseconds(EXPIRES_IN); return access; }
5. AppEngineCredentialStoreTest#testMigrateTo()
Project: google-oauth-java-client
File: AppEngineCredentialStoreTest.java
File: AppEngineCredentialStoreTest.java
public void testMigrateTo() throws Exception { // create old store AppEngineCredentialStore store = new AppEngineCredentialStore(); Credential expected = createCredential(); store.store(USER_ID, expected); // migrate to new store AppEngineDataStoreFactory newFactory = new AppEngineDataStoreFactory(); store.migrateTo(newFactory); // check new store DataStore<StoredCredential> newStore = newFactory.getDataStore(StoredCredential.DEFAULT_DATA_STORE_ID); assertEquals(ImmutableSet.of(USER_ID), newStore.keySet()); StoredCredential actual = newStore.get(USER_ID); assertEquals(expected.getAccessToken(), actual.getAccessToken()); assertEquals(expected.getRefreshToken(), actual.getRefreshToken()); assertEquals(expected.getExpirationTimeMilliseconds(), actual.getExpirationTimeMilliseconds()); }
6. DefaultCredentialProviderTest#testDefaultCredentialComputeErrorUnexpected()
Project: google-api-java-client
File: DefaultCredentialProviderTest.java
File: DefaultCredentialProviderTest.java
public void testDefaultCredentialComputeErrorUnexpected() throws IOException { MockMetadataServerTransport transport = new MockMetadataServerTransport(ACCESS_TOKEN); transport.setTokenRequestStatusCode(HttpStatusCodes.STATUS_CODE_SERVER_ERROR); TestDefaultCredentialProvider testProvider = new TestDefaultCredentialProvider(); Credential defaultCredential = testProvider.getDefaultCredential(transport, JSON_FACTORY); assertNotNull(defaultCredential); try { defaultCredential.refreshToken(); fail("Expected error refreshing token."); } catch (IOException expected) { String message = expected.getMessage(); assertTrue(message.contains(Integer.toString(HttpStatusCodes.STATUS_CODE_SERVER_ERROR))); assertTrue(message.contains("Unexpected")); } }
7. DefaultCredentialProviderTest#testDefaultCredentialComputeErrorNotFound()
Project: google-api-java-client
File: DefaultCredentialProviderTest.java
File: DefaultCredentialProviderTest.java
public void testDefaultCredentialComputeErrorNotFound() throws IOException { MockMetadataServerTransport transport = new MockMetadataServerTransport(ACCESS_TOKEN); transport.setTokenRequestStatusCode(HttpStatusCodes.STATUS_CODE_NOT_FOUND); TestDefaultCredentialProvider testProvider = new TestDefaultCredentialProvider(); Credential defaultCredential = testProvider.getDefaultCredential(transport, JSON_FACTORY); assertNotNull(defaultCredential); try { defaultCredential.refreshToken(); fail("Expected error refreshing token."); } catch (IOException expected) { String message = expected.getMessage(); assertTrue(message.contains(Integer.toString(HttpStatusCodes.STATUS_CODE_NOT_FOUND))); assertTrue(message.contains("scope")); } }
8. DefaultCredentialProviderTest#testDefaultCredentialAppEngineDeployed()
Project: google-api-java-client
File: DefaultCredentialProviderTest.java
File: DefaultCredentialProviderTest.java
public void testDefaultCredentialAppEngineDeployed() throws IOException { HttpTransport transport = new MockHttpTransport(); TestDefaultCredentialProvider testProvider = new TestDefaultCredentialProvider(); testProvider.addType(DefaultCredentialProvider.APP_ENGINE_CREDENTIAL_CLASS, MockAppEngineCredential.class); testProvider.addType(GAE_SIGNAL_CLASS, MockAppEngineSystemProperty.class); Credential defaultCredential = testProvider.getDefaultCredential(transport, JSON_FACTORY); assertNotNull(defaultCredential); assertTrue(defaultCredential instanceof MockAppEngineCredential); assertSame(transport, defaultCredential.getTransport()); assertSame(JSON_FACTORY, defaultCredential.getJsonFactory()); }
9. BatchGoogleMailClientFactory#makeClient()
Project: camel
File: BatchGoogleMailClientFactory.java
File: BatchGoogleMailClientFactory.java
@Override public Gmail makeClient(String clientId, String clientSecret, Collection<String> scopes, String applicationName, String refreshToken, String accessToken) { Credential credential; try { credential = authorize(clientId, clientSecret, scopes); if (refreshToken != null && !"".equals(refreshToken)) { credential.setRefreshToken(refreshToken); } if (accessToken != null && !"".equals(accessToken)) { credential.setAccessToken(accessToken); } return new Gmail.Builder(transport, jsonFactory, credential).setApplicationName(applicationName).build(); } catch (Exception e) { LOG.error("Could not create Google Drive client.", e); } return null; }
10. BatchGoogleDriveClientFactory#makeClient()
Project: camel
File: BatchGoogleDriveClientFactory.java
File: BatchGoogleDriveClientFactory.java
@Override public Drive makeClient(String clientId, String clientSecret, Collection<String> scopes, String applicationName, String refreshToken, String accessToken) { Credential credential; try { credential = authorize(clientId, clientSecret, scopes); if (refreshToken != null && !"".equals(refreshToken)) { credential.setRefreshToken(refreshToken); } if (accessToken != null && !"".equals(accessToken)) { credential.setAccessToken(accessToken); } return new Drive.Builder(transport, jsonFactory, credential).setApplicationName(applicationName).build(); } catch (Exception e) { LOG.error("Could not create Google Drive client.", e); } return null; }
11. BatchGoogleCalendarClientFactory#makeClient()
Project: camel
File: BatchGoogleCalendarClientFactory.java
File: BatchGoogleCalendarClientFactory.java
@Override public Calendar makeClient(String clientId, String clientSecret, Collection<String> scopes, String applicationName, String refreshToken, String accessToken, String emailAddress, String p12FileName, String user) { Credential credential; try { // if emailAddress and p12FileName values are present, assume Google Service Account if (null != emailAddress && !"".equals(emailAddress) && null != p12FileName && !"".equals(p12FileName)) { credential = authorizeServiceAccount(emailAddress, p12FileName, scopes, user); } else { credential = authorize(clientId, clientSecret, scopes); if (refreshToken != null && !"".equals(refreshToken)) { credential.setRefreshToken(refreshToken); } if (accessToken != null && !"".equals(accessToken)) { credential.setAccessToken(accessToken); } } return new Calendar.Builder(transport, jsonFactory, credential).setApplicationName(applicationName).build(); } catch (Exception e) { LOG.error("Could not create Google Drive client.", e); } return null; }
12. AndroidPublisherHelper#init()
Project: android-play-publisher-api
File: AndroidPublisherHelper.java
File: AndroidPublisherHelper.java
/** * Performs all necessary setup steps for running requests against the API. * * @param applicationName the name of the application: com.example.app * @param serviceAccountEmail the Service Account Email (empty if using * installed application) * @return the {@Link AndroidPublisher} service * @throws GeneralSecurityException * @throws IOException */ protected static AndroidPublisher init(String applicationName, @Nullable String serviceAccountEmail) throws IOException, GeneralSecurityException { Preconditions.checkArgument(!Strings.isNullOrEmpty(applicationName), "applicationName cannot be null or empty!"); // Authorization. newTrustedTransport(); Credential credential; if (serviceAccountEmail == null || serviceAccountEmail.isEmpty()) { credential = authorizeWithInstalledApplication(); } else { credential = authorizeWithServiceAccount(serviceAccountEmail); } // Set up and return API client. return new AndroidPublisher.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential).setApplicationName(applicationName).build(); }
13. AuthorizationFlow#createAndStoreCredential()
Project: android-oauth-client
File: AuthorizationFlow.java
File: AuthorizationFlow.java
/** * Creates a new credential for the given user ID based on the given token * response and store in the credential store. * * @param response implicit authorization token response * @param userId user ID or {@code null} if not using a persisted credential * store * @return newly created credential * @throws IOException */ public Credential createAndStoreCredential(ImplicitResponseUrl implicitResponse, String userId) throws IOException { Credential credential = newCredential(userId).setAccessToken(implicitResponse.getAccessToken()).setExpiresInSeconds(implicitResponse.getExpiresInSeconds()); CredentialStore credentialStore = getCredentialStore(); if (credentialStore != null) { credentialStore.store(userId, credential); } if (credentialCreatedListener != null) { credentialCreatedListener.onCredentialCreated(credential, implicitResponse); } return credential; }
14. AndroidPublisherHelper#init()
Project: android-maven-plugin
File: AndroidPublisherHelper.java
File: AndroidPublisherHelper.java
/** * Performs all necessary setup steps for running requests against the API. * * @param serviceAccountEmail the Service Account Email (empty if using * installed application) * @return the {@Link AndroidPublisher} service * @throws GeneralSecurityException * @throws IOException */ public static AndroidPublisher init(String applicationName, String serviceAccountEmail, File pk12File) throws IOException, GeneralSecurityException { // Authorization. newTrustedTransport(); Credential credential = authorizeWithServiceAccount(serviceAccountEmail, pk12File); // Set up and return API client. return new AndroidPublisher.Builder(httpTransport, JSON_FACTORY, credential).setApplicationName(applicationName).build(); }
15. AndroidPublisherHelper#init()
Project: android-maven-plugin
File: AndroidPublisherHelper.java
File: AndroidPublisherHelper.java
/** * Performs all necessary setup steps for running requests against the API. * * @param applicationName the name of the application: com.example.app * @param serviceAccountEmail the Service Account Email (empty if using * installed application) * @return the {@Link AndroidPublisher} service * @throws GeneralSecurityException * @throws IOException */ public static AndroidPublisher init(String applicationName, @Nullable String serviceAccountEmail) throws IOException, GeneralSecurityException { Preconditions.checkArgument(!Strings.isNullOrEmpty(applicationName), "applicationName cannot be null or empty!"); // Authorization. newTrustedTransport(); Credential credential; credential = authorizeWithServiceAccount(serviceAccountEmail); // Set up and return API client. return new AndroidPublisher.Builder(httpTransport, JSON_FACTORY, credential).setApplicationName(applicationName).build(); }
16. Credentials#getCredentialFromClientSecrets()
Project: incubator-beam
File: Credentials.java
File: Credentials.java
/** * Loads OAuth2 credential from client secrets, which may require an * interactive authorization prompt. */ private static Credential getCredentialFromClientSecrets(GcpOptions options, Collection<String> scopes) throws IOException, GeneralSecurityException { String clientSecretsFile = options.getSecretsFile(); checkArgument(clientSecretsFile != null); HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport(); JsonFactory jsonFactory = JacksonFactory.getDefaultInstance(); GoogleClientSecrets clientSecrets; try { clientSecrets = GoogleClientSecrets.load(jsonFactory, new FileReader(clientSecretsFile)); } catch (IOException e) { throw new RuntimeException("Could not read the client secrets from file: " + clientSecretsFile, e); } FileDataStoreFactory dataStoreFactory = new FileDataStoreFactory(new java.io.File(options.getCredentialDir())); GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(httpTransport, jsonFactory, clientSecrets, scopes).setDataStoreFactory(dataStoreFactory).setTokenServerUrl(new GenericUrl(options.getTokenServerUrl())).setAuthorizationServerEncodedUrl(options.getAuthorizationServerEncodedUrl()).build(); // The credentialId identifies the credential if we're using a persistent // credential store. Credential credential = new AuthorizationCodeInstalledApp(flow, new PromptReceiver()).authorize(options.getCredentialId()); LOG.info("Got credential from client secret"); return credential; }
17. FileCredentialStoreTest#createEmptyCredential()
Project: google-oauth-java-client
File: FileCredentialStoreTest.java
File: FileCredentialStoreTest.java
private Credential createEmptyCredential() { Credential access = new Credential.Builder(BearerToken.queryParameterAccessMethod()).setTransport(new AccessTokenTransport()).setJsonFactory(JSON_FACTORY).setTokenServerUrl(TOKEN_SERVER_URL).setClientAuthentication(new BasicAuthentication(CLIENT_ID, CLIENT_SECRET)).build(); return access; }
18. FileCredentialStoreTest#testNotLoadCredentials()
Project: google-oauth-java-client
File: FileCredentialStoreTest.java
File: FileCredentialStoreTest.java
public void testNotLoadCredentials() throws Exception { Credential expected = createCredential(); FileCredentialStore store = new FileCredentialStore(createTempFile(), JSON_FACTORY); store.store(USER_ID, expected); try { store.load(USER_ID, null); fail("expected " + NullPointerException.class); } catch (NullPointerException ex) { } }
19. FileCredentialStoreTest#testLoadCredentials_empty()
Project: google-oauth-java-client
File: FileCredentialStoreTest.java
File: FileCredentialStoreTest.java
public void testLoadCredentials_empty() throws Exception { File file = createTempFile(); FileCredentialStore store = new FileCredentialStore(file, JSON_FACTORY); Credential actual = createEmptyCredential(); boolean loaded = store.load(USER_ID, actual); assertFalse(loaded); assertNull(actual.getAccessToken()); assertNull(actual.getRefreshToken()); assertNull(actual.getExpirationTimeMilliseconds()); }
20. DatastoreFactory#makeClient()
Project: google-cloud-datastore
File: DatastoreFactory.java
File: DatastoreFactory.java
/** * Constructs a Google APIs HTTP client with the associated credentials. */ public HttpRequestFactory makeClient(DatastoreOptions options) { Credential credential = options.getCredential(); HttpTransport transport = options.getTransport(); if (transport == null) { transport = credential == null ? new NetHttpTransport() : credential.getTransport(); } return transport.createRequestFactory(credential); }
21. DefaultCredentialProviderTest#testDefaultCredentialCompute()
Project: google-api-java-client
File: DefaultCredentialProviderTest.java
File: DefaultCredentialProviderTest.java
public void testDefaultCredentialCompute() throws IOException { HttpTransport transport = new MockMetadataServerTransport(ACCESS_TOKEN); TestDefaultCredentialProvider testProvider = new TestDefaultCredentialProvider(); Credential defaultCredential = testProvider.getDefaultCredential(transport, JSON_FACTORY); assertNotNull(defaultCredential); assertTrue(defaultCredential.refreshToken()); assertEquals(ACCESS_TOKEN, defaultCredential.getAccessToken()); }
22. Credentials#getCredentialFromClientSecrets()
Project: DataflowJavaSDK
File: Credentials.java
File: Credentials.java
/** * Loads OAuth2 credential from client secrets, which may require an * interactive authorization prompt. */ private static Credential getCredentialFromClientSecrets(GcpOptions options, Collection<String> scopes) throws IOException, GeneralSecurityException { String clientSecretsFile = options.getSecretsFile(); Preconditions.checkArgument(clientSecretsFile != null); HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport(); JsonFactory jsonFactory = JacksonFactory.getDefaultInstance(); GoogleClientSecrets clientSecrets; try { clientSecrets = GoogleClientSecrets.load(jsonFactory, new FileReader(clientSecretsFile)); } catch (IOException e) { throw new RuntimeException("Could not read the client secrets from file: " + clientSecretsFile, e); } FileDataStoreFactory dataStoreFactory = new FileDataStoreFactory(new java.io.File(options.getCredentialDir())); GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(httpTransport, jsonFactory, clientSecrets, scopes).setDataStoreFactory(dataStoreFactory).setTokenServerUrl(new GenericUrl(options.getTokenServerUrl())).setAuthorizationServerEncodedUrl(options.getAuthorizationServerEncodedUrl()).build(); // The credentialId identifies the credential if we're using a persistent // credential store. Credential credential = new AuthorizationCodeInstalledApp(flow, new PromptReceiver()).authorize(options.getCredentialId()); LOG.info("Got credential from client secret"); return credential; }
23. OAuthAuthenticator#invalidateToken()
Project: che
File: OAuthAuthenticator.java
File: OAuthAuthenticator.java
/** * Invalidate OAuth token for specified user. * * @param userId * user * @return <code>true</code> if OAuth token invalidated and <code>false</code> otherwise, e.g. if user does not have * token yet */ public boolean invalidateToken(String userId) throws IOException { Credential credential = flow.loadCredential(userId); if (credential != null) { flow.getCredentialDataStore().delete(userId); return true; } return false; }
24. OAuthAuthenticator#getToken()
Project: che
File: OAuthAuthenticator.java
File: OAuthAuthenticator.java
/** * Return authorization token by userId. * <p/> * WARN!!!. DO not use it directly. * * @param userId * user identifier * @return token value or {@code null}. When user have valid token then it will be returned, * when user have expired token and it can be refreshed then refreshed value will be returned, * when none token found for user then {@code null} will be returned, * when user have expired token and it can't be refreshed then {@code null} will be returned * @throws IOException * when error occurs during token loading * @see org.eclipse.che.api.auth.oauth.OAuthTokenProvider#getToken(String, String) */ public OAuthToken getToken(String userId) throws IOException { if (!isConfigured()) { throw new IOException("Authenticator is not configured"); } Credential credential = flow.loadCredential(userId); if (credential == null) { return null; } final Long expirationTime = credential.getExpiresInSeconds(); if (expirationTime != null && expirationTime < 0) { boolean tokenRefreshed; try { tokenRefreshed = credential.refreshToken(); } catch (IOException ioEx) { tokenRefreshed = false; } if (tokenRefreshed) { credential = flow.loadCredential(userId); } else { // and null result should be returned try { invalidateToken(userId); } catch (IOException ignored) { } return null; } } return newDto(OAuthToken.class).withToken(credential.getAccessToken()); }
25. InteractiveGoogleDriveClientFactory#makeClient()
Project: camel
File: InteractiveGoogleDriveClientFactory.java
File: InteractiveGoogleDriveClientFactory.java
@Override public Drive makeClient(String clientId, String clientSecret, Collection<String> scopes, String applicationName, String refreshToken, String accessToken) { Credential credential; try { credential = authorize(clientId, clientSecret, scopes); return new Drive.Builder(transport, jsonFactory, credential).setApplicationName(applicationName).build(); } catch (Exception e) { LOG.error("Could not create Google Drive client.", e); } return null; }