com.google.api.client.auth.oauth2.Credential

Here are the examples of the java api class com.google.api.client.auth.oauth2.Credential taken from open source projects.

1. FileCredentialStoreTest#testStoreCredentials()

View license
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()

View license
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. AndroidPublisherHelper#init()

View license
/**
     * 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();
}

4. FileCredentialStoreTest#testMigrateTo()

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

5. FileCredentialStoreTest#createCredential()

View license
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;
}

6. AppEngineCredentialStoreTest#testMigrateTo()

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

7. DefaultCredentialProviderTest#testDefaultCredentialComputeErrorUnexpected()

View license
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"));
    }
}

8. DefaultCredentialProviderTest#testDefaultCredentialComputeErrorNotFound()

View license
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"));
    }
}

9. DefaultCredentialProviderTest#testDefaultCredentialAppEngineDeployed()

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

10. BatchGoogleMailClientFactory#makeClient()

View license
@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;
}

11. BatchGoogleDriveClientFactory#makeClient()

View license
@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;
}

12. BatchGoogleCalendarClientFactory#makeClient()

View license
@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;
}

13. AndroidPublisherHelper#init()

View license
/**
     * 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();
}

14. AuthorizationFlow#createAndStoreCredential()

View license
/**
     * 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;
}

15. AndroidPublisherHelper#init()

View license
/**
     * 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. OAuthAuthenticator#invalidateToken()

Project: che
Source File: OAuthAuthenticator.java
View license
/**
     * 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;
}

17. Credentials#getCredentialFromClientSecrets()

Project: DataflowJavaSDK
Source File: Credentials.java
View license
/**
   * 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;
}

18. OAuthAuthenticator#getToken()

Project: che
Source File: OAuthAuthenticator.java
View license
/**
     * 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());
}

19. DefaultCredentialProviderTest#testDefaultCredentialCompute()

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

20. InteractiveGoogleDriveClientFactory#makeClient()

View license
@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;
}

21. DatastoreFactory#makeClient()

View license
/**
   * 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);
}

22. FileCredentialStoreTest#testLoadCredentials_empty()

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

23. FileCredentialStoreTest#testNotLoadCredentials()

View license
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) {
    }
}

24. FileCredentialStoreTest#createEmptyCredential()

View license
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;
}

25. Credentials#getCredentialFromClientSecrets()

Project: incubator-beam
Source File: Credentials.java
View license
/**
   * 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;
}