Java Code Examples for com.google.api.client.auth.oauth2.Credential#setAccessToken()

The following examples show how to use com.google.api.client.auth.oauth2.Credential#setAccessToken() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: GCalGoogleOAuth.java    From openhab1-addons with Eclipse Public License 2.0 6 votes vote down vote up
private static Credential loadCredential(String userId, DataStore<StoredCredential> credentialDataStore)
        throws IOException {
    Credential credential = newCredential(userId, credentialDataStore);
    if (credentialDataStore != null) {
        StoredCredential stored = credentialDataStore.get(userId);
        if (stored == null) {
            return null;
        }
        credential.setAccessToken(stored.getAccessToken());
        credential.setRefreshToken(stored.getRefreshToken());
        credential.setExpirationTimeMilliseconds(stored.getExpirationTimeMilliseconds());
        if (logger.isDebugEnabled()) {
            logger.debug("Loaded credential");
            logger.debug("device access token: {}", stored.getAccessToken());
            logger.debug("device refresh_token: {}", stored.getRefreshToken());
            logger.debug("device expires_in: {}", stored.getExpirationTimeMilliseconds());
        }
    }
    return credential;
}
 
Example 2
Source File: AppEngineCredentialStore.java    From google-oauth-java-client with Apache License 2.0 5 votes vote down vote up
@Override
public boolean load(String userId, Credential credential) {
  DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
  Key key = KeyFactory.createKey(KIND, userId);
  try {
    Entity entity = datastore.get(key);
    credential.setAccessToken((String) entity.getProperty("accessToken"));
    credential.setRefreshToken((String) entity.getProperty("refreshToken"));
    credential.setExpirationTimeMilliseconds((Long) entity.getProperty("expirationTimeMillis"));
    return true;
  } catch (EntityNotFoundException exception) {
    return false;
  }
}
 
Example 3
Source File: FilePersistedCredential.java    From android-oauth-client with Apache License 2.0 5 votes vote down vote up
/**
 * @param credential credential whose {@link Credential#setAccessToken access token},
 *        {@link Credential#setRefreshToken refresh token}, and
 *        {@link Credential#setExpirationTimeMilliseconds expiration time} need to be set if the
 *        credential already exists in storage
 */
void load(Credential credential) {
  credential.setAccessToken(accessToken);
  credential.setRefreshToken(refreshToken);
  credential.setExpirationTimeMilliseconds(expirationTimeMillis);
  if (credential instanceof OAuthHmacCredential) {
      OAuthHmacCredential oauth10aCredential = (OAuthHmacCredential) credential;
      oauth10aCredential.setTokenSharedSecret(tokenSharedSecret);
      oauth10aCredential.setConsumerKey(consumerKey);
      oauth10aCredential.setSharedSecret(sharedSecret);
  }
}
 
Example 4
Source File: GoogleUtils.java    From mytracks with Apache License 2.0 4 votes vote down vote up
/**
 * Deletes Google Spreadsheets row.
 * 
 * @param context the context
 * @param accountName the account name
 * @param trackName the track name
 * @return true if deletion is success.
 */
public static boolean deleteSpreadsheetsRow(
    Context context, String accountName, String trackName) {
  try {
    // Get spreadsheet Id
    List<File> files = searchSpreadsheets(context, accountName);
    if (files == null || files.size() == 0) {
      return false;
    }
    String spreadsheetId = files.get(0).getId();

    // Get spreadsheet service
    SpreadsheetService spreadsheetService = new SpreadsheetService(
        "MyTracks-" + SystemUtils.getMyTracksVersion(context));
    Credential credential = new Credential(BearerToken.authorizationHeaderAccessMethod());
    credential.setAccessToken(
        SendToGoogleUtils.getToken(context, accountName, SendToGoogleUtils.SPREADSHEETS_SCOPE));
    spreadsheetService.setOAuth2Credentials(credential);

    // Get work sheet
    WorksheetFeed worksheetFeed = spreadsheetService.getFeed(new URL(
        String.format(Locale.US, SendSpreadsheetsAsyncTask.GET_WORKSHEETS_URI, spreadsheetId)),
        WorksheetFeed.class);
    Iterator<WorksheetEntry> worksheetEntryIterator = worksheetFeed.getEntries().iterator();
    while (worksheetEntryIterator.hasNext()) {
      WorksheetEntry worksheetEntry = (WorksheetEntry) worksheetEntryIterator.next();
      String worksheetTitle = worksheetEntry.getTitle().getPlainText();
      if (worksheetTitle.equals(SPREADSHEETS_WORKSHEET_NAME)) {
        URL url = worksheetEntry.getListFeedUrl();
        Iterator<ListEntry> listEntryIterator = spreadsheetService.getFeed(url, ListFeed.class)
            .getEntries().iterator();
        while (listEntryIterator.hasNext()) {
          ListEntry listEntry = (ListEntry) listEntryIterator.next();
          String name = listEntry.getCustomElements().getValue(SPREADSHEETS_TRANCK_NAME_COLUMN);
          if (name.equals(trackName)) {
            listEntry.delete();
            return true;
          }
        }
      }
    }
  } catch (Exception e) {
    Log.e(TAG, "Unable to delete spreadsheets row.", e);
  }
  return false;
}
 
Example 5
Source File: OAuth2CredentialsTest.java    From rides-java-sdk with MIT License 4 votes vote down vote up
@Test
public void useCustomDataStore() throws Exception {
    Credential credential = new Credential.Builder(BearerToken.authorizationHeaderAccessMethod())
            .setTransport(new MockHttpTransport())
            .setJsonFactory(new MockJsonFactory())
            .setClientAuthentication(Mockito.mock(HttpExecuteInterceptor.class))
            .setTokenServerUrl(new GenericUrl(TOKEN_REQUEST_URL))
            .build();

    credential.setAccessToken("accessToken2");
    credential.setRefreshToken("refreshToken2");
    credential.setExpiresInSeconds(1000L);

    DataStore mockDataStore = Mockito.mock(DataStore.class);
    MockDataStoreFactory mockDataStoreFactory = new MockDataStoreFactory(mockDataStore);
    Mockito.when(mockDataStore.get(eq("userId"))).thenReturn(new StoredCredential(credential));

    OAuth2Credentials oAuth2Credentials = new OAuth2Credentials.Builder()
            .setClientSecrets("CLIENT_ID", "CLIENT_SECRET")
            .setRedirectUri("http://redirect")
            .setHttpTransport(mockHttpTransport)
            .setCredentialDataStoreFactory(mockDataStoreFactory)
            .setScopes(Arrays.asList(Scope.PROFILE, Scope.REQUEST))
            .build();

    Credential storedCredential = oAuth2Credentials.authenticate("authorizationCode", "userId");
    Credential loadedCredential = oAuth2Credentials.loadCredential("userId");

    assertEquals("Refresh token does not match.", "refreshToken", storedCredential.getRefreshToken());
    assertTrue("Expected expires_in between 0 and 3600. Was actually: " + storedCredential.getExpiresInSeconds(),
            storedCredential.getExpiresInSeconds() > 0 && storedCredential.getExpiresInSeconds() <= 3600);
    assertEquals("Access token does not match.", "accessToken", storedCredential.getAccessToken());
    assertEquals("Access method (Bearer) does not match",
            BearerToken.authorizationHeaderAccessMethod().getClass(), storedCredential.getMethod().getClass());

    assertEquals("Refresh token does not match.", "refreshToken2", loadedCredential.getRefreshToken());
    assertTrue("Expected expires_in between 0 and 1000. Was actually: " + loadedCredential.getExpiresInSeconds(),
            loadedCredential.getExpiresInSeconds() > 0 && loadedCredential.getExpiresInSeconds() <= 1000L);
    assertEquals("Access token does not match.", "accessToken2", loadedCredential.getAccessToken());
    assertEquals("Access method (Bearer) does not match",
            BearerToken.authorizationHeaderAccessMethod().getClass(), loadedCredential.getMethod().getClass());
}
 
Example 6
Source File: FilePersistedCredential.java    From mirror with Apache License 2.0 2 votes vote down vote up
/**
 * @param credential credential whose {@link Credential#setAccessToken access token},
 *        {@link Credential#setRefreshToken refresh token}, and
 *        {@link Credential#setExpirationTimeMilliseconds expiration time} need to be set if the
 *        credential already exists in storage
 */
void load(Credential credential) {
  credential.setAccessToken(accessToken);
  credential.setRefreshToken(refreshToken);
  credential.setExpirationTimeMilliseconds(expirationTimeMillis);
}
 
Example 7
Source File: FilePersistedCredential.java    From google-oauth-java-client with Apache License 2.0 2 votes vote down vote up
/**
 * @param credential credential whose {@link Credential#setAccessToken access token},
 *        {@link Credential#setRefreshToken refresh token}, and
 *        {@link Credential#setExpirationTimeMilliseconds expiration time} need to be set if the
 *        credential already exists in storage
 */
void load(Credential credential) {
  credential.setAccessToken(accessToken);
  credential.setRefreshToken(refreshToken);
  credential.setExpirationTimeMilliseconds(expirationTimeMillis);
}