Java gmail api how to create DataStore object using MemoryDataStoreFactory?

Viewed 81

I want to use the Gmail Java API with an existing access token and refresh token with the following code:

    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
            HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, Collections.singletonList(GmailScopes.GMAIL_READONLY))
            .setAccessType("offline")
            .setCredentialDataStore()
            .build();
    LocalServerReceiver receiver = new LocalServerReceiver.Builder().setPort(8888).build();
    Credential credential = new AuthorizationCodeInstalledApp(flow, receiver).authorize("user");

I need to create a DataStore of StoredCredential object, set the tokens there and pass it to setCredentialDataStore method. I understand this can be done somehow by using MemoryDataStoreFactory.

Does anyone know how can I do it?

1 Answers

What if you try this:

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