com.google.api.client.util.store.DataStore Java Examples

The following examples show how to use com.google.api.client.util.store.DataStore. 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: CustomDataStoreFactory.java    From pentaho-kettle with Apache License 2.0 6 votes vote down vote up
public DataStore<V> delete( String key ) throws IOException {
  if ( key == null ) {
    return this;
  } else {
    this.lock.lock();

    try {
      this.keyValueMap.remove( key );
      this.save();
    } finally {
      this.lock.unlock();
    }

    return this;
  }
}
 
Example #2
Source File: JPADataStore.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
@Override
public DataStore<StoredCredential> set(String userId, StoredCredential cred) throws IOException {
	GoogleDriveUser gdu = repository.findBySakaiId(userId);
	if(gdu == null) {
		gdu = new GoogleDriveUser();
		gdu.setSakaiUserId(userId);
		gdu.setToken(cred.getAccessToken());
		gdu.setRefreshToken(cred.getRefreshToken());
		repository.save(gdu);
	} else {
		gdu.setToken(cred.getAccessToken());
		gdu.setRefreshToken(cred.getRefreshToken());
		repository.update(gdu);
	}
	return this;
}
 
Example #3
Source File: AppEngineDataStoreFactory.java    From google-http-java-client with Apache License 2.0 6 votes vote down vote up
@Override
public DataStore<V> delete(String key) throws IOException {
  if (key == null) {
    return this;
  }
  lock.lock();
  try {
    dataStoreService.delete(KeyFactory.createKey(getId(), key));
    if (memcache != null) {
      memcache.delete(key);
    }
  } finally {
    lock.unlock();
  }
  return this;
}
 
Example #4
Source File: AppEngineCredentialStoreTest.java    From google-oauth-java-client with Apache License 2.0 6 votes vote down vote up
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());
}
 
Example #5
Source File: FileCredentialStoreTest.java    From google-oauth-java-client with Apache License 2.0 6 votes vote down vote up
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());
}
 
Example #6
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 #7
Source File: JPADataStore.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
@Override
public DataStore<StoredCredential> set(String userId, StoredCredential cred) throws IOException {
	GoogleDriveUser gdu = repository.findBySakaiId(userId);
	if(gdu == null) {
		gdu = new GoogleDriveUser();
		gdu.setSakaiUserId(userId);
		gdu.setToken(cred.getAccessToken());
		gdu.setRefreshToken(cred.getRefreshToken());
		repository.save(gdu);
	} else {
		gdu.setToken(cred.getAccessToken());
		gdu.setRefreshToken(cred.getRefreshToken());
		repository.update(gdu);
	}
	return this;
}
 
Example #8
Source File: ApigeeDataClient.java    From apigee-android-sdk with Apache License 2.0 6 votes vote down vote up
/**
 * Stores the given OAuth 2 token response within a file data store.
 * The stored token response can then retrieved using the getOAuth2TokenDataFromStore method.
 *
 * @param storageId a string object that is used to store the token response
 * @param tokenResponse the token response containing the OAuth 2 token information.
 * @return If the token response was stored or not.
 */
public Boolean storeOAuth2TokenData(String storageId, TokenResponse tokenResponse) {
    Boolean wasStored = false;
    try {
        File oauth2StorageFolder = new File(this.context.getFilesDir(),"oauth2StorageFolder");
        oauth2StorageFolder.mkdirs();
        FileDataStoreFactory fileDataStoreFactory = new FileDataStoreFactory(oauth2StorageFolder);
        DataStore<StoredCredential> storedCredentialDataStore = fileDataStoreFactory.getDataStore(storageId);
        Credential oauth2Credential = new Credential(BearerToken.authorizationHeaderAccessMethod()).setFromTokenResponse(
                tokenResponse);
        StoredCredential storedOAuth2Credential = new StoredCredential(oauth2Credential);
        storedCredentialDataStore.set(storageId,storedOAuth2Credential);
        wasStored = true;
    } catch ( Exception exception ) {
        logInfo("Exception storing OAuth2TokenData :" + exception.getLocalizedMessage());
    }
    return wasStored;
}
 
Example #9
Source File: Auth.java    From youtube-chat-for-minecraft with Apache License 2.0 6 votes vote down vote up
/**
 * Authorizes the installed application to access user's protected data.
 *
 * @param scopes list of scopes needed to run youtube upload.
 * @param clientSecret the client secret from Google API console
 * @param credentialDatastore name of the credential datastore to cache OAuth tokens
 */
public static Credential authorize(
    Collection<String> scopes, String clientSecret, String credentialDatastore)
    throws IOException {
  // Load client secrets
  GoogleClientSecrets clientSecrets =
      GoogleClientSecrets.load(JSON_FACTORY, new StringReader(clientSecret));

  // This creates the credentials datastore at ~/.oauth-credentials/${credentialDatastore}
  FileDataStoreFactory fileDataStoreFactory =
      new FileDataStoreFactory(new File(getCredentialsDirectory()));
  DataStore<StoredCredential> datastore = fileDataStoreFactory.getDataStore(credentialDatastore);

  GoogleAuthorizationCodeFlow flow =
      new GoogleAuthorizationCodeFlow.Builder(HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, scopes)
          .setCredentialDataStore(datastore)
          .build();

  // authorize
  return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
}
 
Example #10
Source File: CustomDataStoreFactory.java    From hop with Apache License 2.0 6 votes vote down vote up
public DataStore<V> delete( String key ) throws IOException {
  if ( key == null ) {
    return this;
  } else {
    this.lock.lock();

    try {
      this.keyValueMap.remove( key );
      this.save();
    } finally {
      this.lock.unlock();
    }

    return this;
  }
}
 
Example #11
Source File: ApigeeDataClient.java    From apigee-android-sdk with Apache License 2.0 5 votes vote down vote up
/**
 * Deletes the TokenResponse that is associated with the given storageId from the file data store.
 *
 * @param storageId The storageId associated with the stored TokenResponse.
 */
public void deleteStoredOAuth2TokenData(String storageId) {
    try {
        File oauth2StorageFolder = new File(this.context.getFilesDir(),"oauth2StorageFolder");
        oauth2StorageFolder.mkdirs();
        FileDataStoreFactory fileDataStoreFactory = new FileDataStoreFactory(oauth2StorageFolder);
        DataStore<StoredCredential> storedCredentialDataStore = fileDataStoreFactory.getDataStore(storageId);
        storedCredentialDataStore.delete(storageId);
    } catch ( Exception exception ) {
        logInfo("Exception deleting OAuth2TokenData :" + exception.getLocalizedMessage());
    }
}
 
Example #12
Source File: GCalGoogleOAuth.java    From openhab1-addons with Eclipse Public License 2.0 5 votes vote down vote up
private static Credential newCredential(String userId, DataStore<StoredCredential> credentialDataStore) {

        Credential.Builder builder = new Credential.Builder(BearerToken.authorizationHeaderAccessMethod())
                .setTransport(HTTP_TRANSPORT).setJsonFactory(JSON_FACTORY)
                .setTokenServerEncodedUrl("https://accounts.google.com/o/oauth2/token")
                .setClientAuthentication(new ClientParametersAuthentication(client_id, client_secret))
                .setRequestInitializer(null).setClock(Clock.SYSTEM);

        builder.addRefreshListener(new DataStoreCredentialRefreshListener(userId, credentialDataStore));

        return builder.build();
    }
 
Example #13
Source File: CustomDataStoreFactory.java    From pentaho-kettle with Apache License 2.0 5 votes vote down vote up
public final DataStore<V> clear() throws IOException {
  this.lock.lock();

  try {
    this.keyValueMap.clear();
    this.save();
  } finally {
    this.lock.unlock();
  }

  return this;
}
 
Example #14
Source File: AppEngineCredentialStore.java    From google-oauth-java-client with Apache License 2.0 5 votes vote down vote up
/**
 * Migrates to the new format using {@link DataStore} of {@link StoredCredential}.
 *
 * @param credentialDataStore credential data store
 * @since 1.16
 */
public final void migrateTo(DataStore<StoredCredential> credentialDataStore) throws IOException {
  DatastoreService service = DatastoreServiceFactory.getDatastoreService();
  PreparedQuery queryResult = service.prepare(new Query(KIND));
  for (Entity entity : queryResult.asIterable()) {
    StoredCredential storedCredential = new StoredCredential().setAccessToken(
        (String) entity.getProperty("accessToken"))
        .setRefreshToken((String) entity.getProperty("refreshToken"))
        .setExpirationTimeMilliseconds((Long) entity.getProperty("expirationTimeMillis"));
    credentialDataStore.set(entity.getKey().getName(), storedCredential);
  }
}
 
Example #15
Source File: ConfigDataStoreFactory.java    From googleads-shopping-samples with Apache License 2.0 5 votes vote down vote up
public DataStore<StoredCredential> set(String key, StoredCredential value) throws IOException {
  if (key != UNUSED_ID) {
    throw new IOException("Unexpected real user ID");
  }
  token = Token.fromStoredCredential(value);
  writeToken();
  return this;
}
 
Example #16
Source File: GoogleDriveServiceImpl.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
public boolean revokeGoogleDriveConfiguration(String userId){
	log.info("revokeGoogleDriveConfiguration for user {}", userId);
	try {
		cleanGoogleDriveCacheForUser(userId);
		DataStore<StoredCredential> credentialStore = flow.getCredentialDataStore();
		return (credentialStore.delete(userId) != null);
	} catch (Exception e) {
		log.warn("Error while trying to remove GoogleDrive configuration : {}", e.getMessage());
	}
	return false;
}
 
Example #17
Source File: CustomDataStoreFactory.java    From pentaho-kettle with Apache License 2.0 5 votes vote down vote up
public final DataStore<V> set( String key, V value ) throws IOException {
  Preconditions.checkNotNull( key );
  Preconditions.checkNotNull( value );
  this.lock.lock();

  try {
    this.keyValueMap.put( key, IOUtils.serialize( value ) );
    this.save();
  } finally {
    this.lock.unlock();
  }

  return this;
}
 
Example #18
Source File: CustomDataStoreFactory.java    From hop with Apache License 2.0 5 votes vote down vote up
public final DataStore<V> clear() throws IOException {
  this.lock.lock();

  try {
    this.keyValueMap.clear();
    this.save();
  } finally {
    this.lock.unlock();
  }

  return this;
}
 
Example #19
Source File: CustomDataStoreFactory.java    From hop with Apache License 2.0 5 votes vote down vote up
public final DataStore<V> set( String key, V value ) throws IOException {
  Preconditions.checkNotNull( key );
  Preconditions.checkNotNull( value );
  this.lock.lock();

  try {
    this.keyValueMap.put( key, IOUtils.serialize( value ) );
    this.save();
  } finally {
    this.lock.unlock();
  }

  return this;
}
 
Example #20
Source File: Authorizer.java    From mail-importer with Apache License 2.0 5 votes vote down vote up
private DataStore<StoredCredential> getStoredCredentialDataStore()
    throws IOException {
  File userHomeDir = getUserHomeDir();
  File mailimporter = new File(userHomeDir, ".mailimporter");
  FileDataStoreFactory dataStoreFactory =
      new FileDataStoreFactory(mailimporter);
  return dataStoreFactory.getDataStore("credentials");
}
 
Example #21
Source File: GoogleDriveServiceImpl.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
public boolean revokeGoogleDriveConfiguration(String userId){
	log.info("revokeGoogleDriveConfiguration for user {}", userId);
	try {
		cleanGoogleDriveCacheForUser(userId);
		DataStore<StoredCredential> credentialStore = flow.getCredentialDataStore();
		return (credentialStore.delete(userId) != null);
	} catch (Exception e) {
		log.warn("Error while trying to remove GoogleDrive configuration : {}", e.getMessage());
	}
	return false;
}
 
Example #22
Source File: FileDataStoreFactoryTest.java    From google-http-java-client with Apache License 2.0 5 votes vote down vote up
public void testSave() throws IOException {
  FileDataStoreFactory factory = newDataStoreFactory();
  DataStore<String> store = factory.getDataStore("foo");
  store.set("k", "v");
  assertEquals(
      ImmutableSet.of("k"),
      new FileDataStoreFactory(factory.getDataDirectory()).getDataStore("foo").keySet());
  store.clear();
  assertTrue(new FileDataStoreFactory(factory.getDataDirectory()).getDataStore("foo").isEmpty());
}
 
Example #23
Source File: FilePersistedCredentials.java    From google-oauth-java-client with Apache License 2.0 4 votes vote down vote up
void migrateTo(DataStore<StoredCredential> typedDataStore) throws IOException {
  for (Map.Entry<String, FilePersistedCredential> entry : credentials.entrySet()) {
    typedDataStore.set(entry.getKey(), entry.getValue().toStoredCredential());
  }
}
 
Example #24
Source File: CustomDataStoreFactory.java    From hop with Apache License 2.0 4 votes vote down vote up
protected <V extends Serializable> DataStore<V> createDataStore( String id ) throws IOException {
  return new CustomDataStore( this, this.dataDirectory, id );
}
 
Example #25
Source File: AuthModuleTest.java    From nomulus with Apache License 2.0 4 votes vote down vote up
@Override
protected <V extends Serializable> DataStore<V> createDataStore(String id) {
  @SuppressWarnings("unchecked")
  DataStore<V> result = (DataStore<V>) dataStore;
  return result;
}
 
Example #26
Source File: CustomDataStoreFactory.java    From pentaho-kettle with Apache License 2.0 4 votes vote down vote up
protected <V extends Serializable> DataStore<V> createDataStore( String id ) throws IOException {
  return new CustomDataStore( this, this.dataDirectory, id );
}
 
Example #27
Source File: Authorizer.java    From mail-importer with Apache License 2.0 4 votes vote down vote up
public Credential get() {
  try {
    GoogleClientSecrets clientSecrets = loadGoogleClientSecrets(jsonFactory);

    DataStore<StoredCredential> dataStore = getStoredCredentialDataStore();

    // Allow user to authorize via url.
    GoogleAuthorizationCodeFlow flow =
        new GoogleAuthorizationCodeFlow.Builder(
            httpTransport,
            jsonFactory,
            clientSecrets,
            ImmutableList.of(
                GmailScopes.GMAIL_MODIFY,
                GmailScopes.GMAIL_READONLY))
            .setCredentialDataStore(dataStore)
            .setAccessType("offline")
            .setApprovalPrompt("auto")
            .build();

    // First, see if we have a stored credential for the user.
    Credential credential = flow.loadCredential(user.getEmailAddress());

    // If we don't, prompt them to get one.
    if (credential == null) {
      String url = flow.newAuthorizationUrl()
          .setRedirectUri(GoogleOAuthConstants.OOB_REDIRECT_URI)
          .build();
      System.out.println("Please open the following URL in your browser then "
          + "type the authorization code:\n" + url);

      // Read code entered by user.
      System.out.print("Code: ");
      System.out.flush();
      BufferedReader br = new BufferedReader(
          new InputStreamReader(System.in));
      String code = br.readLine();

      // Generate Credential using retrieved code.
      GoogleTokenResponse response = flow.newTokenRequest(code)
          .setRedirectUri(GoogleOAuthConstants.OOB_REDIRECT_URI)
          .execute();

      credential =
          flow.createAndStoreCredential(response, user.getEmailAddress());
    }

    Gmail gmail = new Gmail.Builder(httpTransport, jsonFactory, credential)
        .setApplicationName(GmailServiceModule.APP_NAME)
        .build();

    Profile profile = gmail.users()
        .getProfile(user.getEmailAddress())
        .execute();

    System.out.println(profile.toPrettyString());
    return credential;
  } catch (IOException exception) {
    throw new RuntimeException(exception);
  }
}
 
Example #28
Source File: JPADataStore.java    From sakai with Educational Community License v2.0 4 votes vote down vote up
@Override
public DataStore<StoredCredential> clear() throws IOException {
	repository.deleteAll();
	return this;
}
 
Example #29
Source File: JPADataStore.java    From sakai with Educational Community License v2.0 4 votes vote down vote up
@Override
public DataStore<StoredCredential> delete(String userId) throws IOException {
	repository.delete(userId);
	return this;
}
 
Example #30
Source File: DataStoreCredentialRefreshListener.java    From google-oauth-java-client with Apache License 2.0 4 votes vote down vote up
/** Returns the stored credential data store. */
public DataStore<StoredCredential> getCredentialDataStore() {
  return credentialDataStore;
}