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

The following examples show how to use com.google.api.client.util.store.FileDataStoreFactory. 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: Main.java    From java-11-examples with Apache License 2.0 7 votes vote down vote up
/**
 * Creates an authorized Credential object.
 * @param HTTP_TRANSPORT The network HTTP Transport.
 * @return An authorized Credential object.
 * @throws IOException If the credentials.json file cannot be found.
 */
private static Credential getCredentials(final NetHttpTransport HTTP_TRANSPORT) throws IOException {
    // Load client secrets.
    InputStream in = Main.class.getResourceAsStream(CREDENTIALS_FILE_PATH);
    if (in == null) {
        throw new FileNotFoundException("Resource not found: " + CREDENTIALS_FILE_PATH);
    }
    GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));

    // Build flow and trigger user authorization request.
    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
            HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
            .setDataStoreFactory(new FileDataStoreFactory(new java.io.File(TOKENS_DIRECTORY_PATH)))
            .setAccessType("offline")
            .build();
    LocalServerReceiver receiver = new LocalServerReceiver.Builder().setPort(8888).build();
    return new AuthorizationCodeInstalledApp(flow, receiver).authorize("user");
}
 
Example #2
Source File: ClassroomQuickstart.java    From java-samples with Apache License 2.0 6 votes vote down vote up
/**
 * Creates an authorized Credential object.
 * @param HTTP_TRANSPORT The network HTTP Transport.
 * @return An authorized Credential object.
 * @throws IOException If the credentials.json file cannot be found.
 */
private static Credential getCredentials(final NetHttpTransport HTTP_TRANSPORT) throws IOException {
    // Load client secrets.
    InputStream in = ClassroomQuickstart.class.getResourceAsStream(CREDENTIALS_FILE_PATH);
    if (in == null) {
        throw new FileNotFoundException("Resource not found: " + CREDENTIALS_FILE_PATH);
    }
    GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));

    // Build flow and trigger user authorization request.
    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
            HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
            .setDataStoreFactory(new FileDataStoreFactory(new java.io.File(TOKENS_DIRECTORY_PATH)))
            .setAccessType("offline")
            .build();
    LocalServerReceiver receiver = new LocalServerReceiver.Builder().setPort(8888).build();
    return new AuthorizationCodeInstalledApp(flow, receiver).authorize("user");
}
 
Example #3
Source File: PeopleQuickstart.java    From java-samples with Apache License 2.0 6 votes vote down vote up
/**
 * Creates an authorized Credential object.
 * @param HTTP_TRANSPORT The network HTTP Transport.
 * @return An authorized Credential object.
 * @throws IOException If the credentials.json file cannot be found.
 */
private static Credential getCredentials(final NetHttpTransport HTTP_TRANSPORT) throws IOException {
    // Load client secrets.
    InputStream in = PeopleQuickstart.class.getResourceAsStream(CREDENTIALS_FILE_PATH);
    if (in == null) {
        throw new FileNotFoundException("Resource not found: " + CREDENTIALS_FILE_PATH);
    }
    GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));

    // Build flow and trigger user authorization request.
    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
            HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
            .setDataStoreFactory(new FileDataStoreFactory(new java.io.File(TOKENS_DIRECTORY_PATH)))
            .setAccessType("offline")
            .build();
    LocalServerReceiver receiver = new LocalServerReceiver.Builder().setPort(8888).build();
    return new AuthorizationCodeInstalledApp(flow, receiver).authorize("user");
}
 
Example #4
Source File: AppsScriptQuickstart.java    From java-samples with Apache License 2.0 6 votes vote down vote up
/**
 * Creates an authorized Credential object.
 * @param HTTP_TRANSPORT The network HTTP Transport.
 * @return An authorized Credential object.
 * @throws IOException If the credentials.json file cannot be found.
 */
private static Credential getCredentials(final NetHttpTransport HTTP_TRANSPORT) throws IOException {
    // Load client secrets.
    InputStream in = AppsScriptQuickstart.class.getResourceAsStream(CREDENTIALS_FILE_PATH);
    if (in == null) {
        throw new FileNotFoundException("Resource not found: " + CREDENTIALS_FILE_PATH);
    }
    GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));

    // Build flow and trigger user authorization request.
    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
            HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
            .setDataStoreFactory(new FileDataStoreFactory(new java.io.File(TOKENS_DIRECTORY_PATH)))
            .setAccessType("offline")
            .build();
    LocalServerReceiver receiver = new LocalServerReceiver.Builder().setPort(8888).build();
    return new AuthorizationCodeInstalledApp(flow, receiver).authorize("user");
}
 
Example #5
Source File: SlidesQuickstart.java    From java-samples with Apache License 2.0 6 votes vote down vote up
/**
 * Creates an authorized Credential object.
 * @param HTTP_TRANSPORT The network HTTP Transport.
 * @return An authorized Credential object.
 * @throws IOException If the credentials.json file cannot be found.
 */
private static Credential getCredentials(final NetHttpTransport HTTP_TRANSPORT) throws IOException {
    // Load client secrets.
    InputStream in = SlidesQuickstart.class.getResourceAsStream(CREDENTIALS_FILE_PATH);
    if (in == null) {
        throw new FileNotFoundException("Resource not found: " + CREDENTIALS_FILE_PATH);
    }
    GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));

    // Build flow and trigger user authorization request.
    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
            HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
            .setDataStoreFactory(new FileDataStoreFactory(new java.io.File(TOKENS_DIRECTORY_PATH)))
            .setAccessType("offline")
            .build();
    LocalServerReceiver receiver = new LocalServerReceiver.Builder().setPort(8888).build();
    return new AuthorizationCodeInstalledApp(flow, receiver).authorize("user");
}
 
Example #6
Source File: CalendarQuickstart.java    From java-samples with Apache License 2.0 6 votes vote down vote up
/**
 * Creates an authorized Credential object.
 * @param HTTP_TRANSPORT The network HTTP Transport.
 * @return An authorized Credential object.
 * @throws IOException If the credentials.json file cannot be found.
 */
private static Credential getCredentials(final NetHttpTransport HTTP_TRANSPORT) throws IOException {
    // Load client secrets.
    InputStream in = CalendarQuickstart.class.getResourceAsStream(CREDENTIALS_FILE_PATH);
    if (in == null) {
        throw new FileNotFoundException("Resource not found: " + CREDENTIALS_FILE_PATH);
    }
    GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));

    // Build flow and trigger user authorization request.
    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
            HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
            .setDataStoreFactory(new FileDataStoreFactory(new java.io.File(TOKENS_DIRECTORY_PATH)))
            .setAccessType("offline")
            .build();
    LocalServerReceiver receiver = new LocalServerReceiver.Builder().setPort(8888).build();
    return new AuthorizationCodeInstalledApp(flow, receiver).authorize("user");
}
 
Example #7
Source File: GmailQuickstart.java    From java-samples with Apache License 2.0 6 votes vote down vote up
/**
 * Creates an authorized Credential object.
 * @param HTTP_TRANSPORT The network HTTP Transport.
 * @return An authorized Credential object.
 * @throws IOException If the credentials.json file cannot be found.
 */
private static Credential getCredentials(final NetHttpTransport HTTP_TRANSPORT) throws IOException {
    // Load client secrets.
    InputStream in = GmailQuickstart.class.getResourceAsStream(CREDENTIALS_FILE_PATH);
    if (in == null) {
        throw new FileNotFoundException("Resource not found: " + CREDENTIALS_FILE_PATH);
    }
    GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));

    // Build flow and trigger user authorization request.
    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
            HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
            .setDataStoreFactory(new FileDataStoreFactory(new java.io.File(TOKENS_DIRECTORY_PATH)))
            .setAccessType("offline")
            .build();
    LocalServerReceiver receiver = new LocalServerReceiver.Builder().setPort(8888).build();
    return new AuthorizationCodeInstalledApp(flow, receiver).authorize("user");
}
 
Example #8
Source File: AdminSDKReportsQuickstart.java    From java-samples with Apache License 2.0 6 votes vote down vote up
/**
 * Creates an authorized Credential object.
 * @param HTTP_TRANSPORT The network HTTP Transport.
 * @return An authorized Credential object.
 * @throws IOException If the credentials.json file cannot be found.
 */
private static Credential getCredentials(final NetHttpTransport HTTP_TRANSPORT) throws IOException {
    // Load client secrets.
    InputStream in = AdminSDKReportsQuickstart.class.getResourceAsStream(CREDENTIALS_FILE_PATH);
    if (in == null) {
        throw new FileNotFoundException("Resource not found: " + CREDENTIALS_FILE_PATH);
    }
    GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));

    // Build flow and trigger user authorization request.
    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
            HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
            .setDataStoreFactory(new FileDataStoreFactory(new java.io.File(TOKENS_DIRECTORY_PATH)))
            .setAccessType("offline")
            .build();
    LocalServerReceiver receiver = new LocalServerReceiver.Builder().setPort(8888).build();
    return new AuthorizationCodeInstalledApp(flow, receiver).authorize("user");
}
 
Example #9
Source File: AdminSDKDirectoryQuickstart.java    From java-samples with Apache License 2.0 6 votes vote down vote up
/**
 * Creates an authorized Credential object.
 * @param HTTP_TRANSPORT The network HTTP Transport.
 * @return An authorized Credential object.
 * @throws IOException If the credentials.json file cannot be found.
 */
private static Credential getCredentials(final NetHttpTransport HTTP_TRANSPORT) throws IOException {
    // Load client secrets.
    InputStream in = AdminSDKDirectoryQuickstart.class.getResourceAsStream(CREDENTIALS_FILE_PATH);
    if (in == null) {
        throw new FileNotFoundException("Resource not found: " + CREDENTIALS_FILE_PATH);
    }
    GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));

    // Build flow and trigger user authorization request.
    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
            HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
            .setDataStoreFactory(new FileDataStoreFactory(new java.io.File(TOKENS_DIRECTORY_PATH)))
            .setAccessType("offline")
            .build();
    LocalServerReceiver receiver = new LocalServerReceiver.Builder().setPort(8888).build();
    return new AuthorizationCodeInstalledApp(flow, receiver).authorize("user");
}
 
Example #10
Source File: AdminSDKResellerQuickstart.java    From java-samples with Apache License 2.0 6 votes vote down vote up
/**
 * Creates an authorized Credential object.
 * @param HTTP_TRANSPORT The network HTTP Transport.
 * @return An authorized Credential object.
 * @throws IOException If the credentials.json file cannot be found.
 */
private static Credential getCredentials(final NetHttpTransport HTTP_TRANSPORT) throws IOException {
    // Load client secrets.
    InputStream in = AdminSDKResellerQuickstart.class.getResourceAsStream(CREDENTIALS_FILE_PATH);
    if (in == null) {
        throw new FileNotFoundException("Resource not found: " + CREDENTIALS_FILE_PATH);
    }
    GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));

    // Build flow and trigger user authorization request.
    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
            HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
            .setDataStoreFactory(new FileDataStoreFactory(new java.io.File(TOKENS_DIRECTORY_PATH)))
            .setAccessType("offline")
            .build();
    LocalServerReceiver receiver = new LocalServerReceiver.Builder().setPort(8888).build();
    return new AuthorizationCodeInstalledApp(flow, receiver).authorize("user");
}
 
Example #11
Source File: TasksQuickstart.java    From java-samples with Apache License 2.0 6 votes vote down vote up
/**
 * Creates an authorized Credential object.
 * @param HTTP_TRANSPORT The network HTTP Transport.
 * @return An authorized Credential object.
 * @throws IOException If the credentials.json file cannot be found.
 */
private static Credential getCredentials(final NetHttpTransport HTTP_TRANSPORT) throws IOException {
    // Load client secrets.
    InputStream in = TasksQuickstart.class.getResourceAsStream(CREDENTIALS_FILE_PATH);
    if (in == null) {
        throw new FileNotFoundException("Resource not found: " + CREDENTIALS_FILE_PATH);
    }
    GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));

    // Build flow and trigger user authorization request.
    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
            HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
            .setDataStoreFactory(new FileDataStoreFactory(new java.io.File(TOKENS_DIRECTORY_PATH)))
            .setAccessType("offline")
            .build();
    LocalServerReceiver receiver = new LocalServerReceiver.Builder().setPort(8888).build();
    return new AuthorizationCodeInstalledApp(flow, receiver).authorize("user");
}
 
Example #12
Source File: OutputJSON.java    From java-samples with Apache License 2.0 6 votes vote down vote up
/**
 * Creates an authorized Credential object.
 *
 * @param HTTP_TRANSPORT The network HTTP Transport.
 * @return An authorized Credential object.
 * @throws IOException If the credentials.json file cannot be found.
 */
private static Credential getCredentials(final NetHttpTransport HTTP_TRANSPORT)
        throws IOException {
    // Load client secrets.
    InputStream in = OutputJSON.class.getResourceAsStream(CREDENTIALS_FILE_PATH);
    GoogleClientSecrets credentials =
            GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));

    // Build flow and trigger user authorization request.
    GoogleAuthorizationCodeFlow flow =
            new GoogleAuthorizationCodeFlow.Builder(HTTP_TRANSPORT, JSON_FACTORY, credentials, SCOPES)
                    .setDataStoreFactory(new FileDataStoreFactory(new java.io.File(TOKENS_DIRECTORY_PATH)))
                    .setAccessType("offline")
                    .build();
    LocalServerReceiver receiver = new LocalServerReceiver.Builder().setPort(8888).build();
    return new AuthorizationCodeInstalledApp(flow, receiver).authorize("user");
}
 
Example #13
Source File: DocsQuickstart.java    From java-samples with Apache License 2.0 6 votes vote down vote up
/**
 * Creates an authorized Credential object.
 * @param HTTP_TRANSPORT The network HTTP Transport.
 * @return An authorized Credential object.
 * @throws IOException If the credentials.json file cannot be found.
 */
private static Credential getCredentials(final NetHttpTransport HTTP_TRANSPORT) throws IOException {
    // Load client secrets.
    InputStream in = DocsQuickstart.class.getResourceAsStream(CREDENTIALS_FILE_PATH);
    if (in == null) {
        throw new FileNotFoundException("Resource not found: " + CREDENTIALS_FILE_PATH);
    }
    GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));

    // Build flow and trigger user authorization request.
    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
            HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
            .setDataStoreFactory(new FileDataStoreFactory(new java.io.File(TOKENS_DIRECTORY_PATH)))
            .setAccessType("offline")
            .build();
    LocalServerReceiver receiver = new LocalServerReceiver.Builder().setPort(8888).build();
    return new AuthorizationCodeInstalledApp(flow, receiver).authorize("user");
}
 
Example #14
Source File: SheetsQuickstart.java    From java-samples with Apache License 2.0 6 votes vote down vote up
/**
 * Creates an authorized Credential object.
 * @param HTTP_TRANSPORT The network HTTP Transport.
 * @return An authorized Credential object.
 * @throws IOException If the credentials.json file cannot be found.
 */
private static Credential getCredentials(final NetHttpTransport HTTP_TRANSPORT) throws IOException {
    // Load client secrets.
    InputStream in = SheetsQuickstart.class.getResourceAsStream(CREDENTIALS_FILE_PATH);
    if (in == null) {
        throw new FileNotFoundException("Resource not found: " + CREDENTIALS_FILE_PATH);
    }
    GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));

    // Build flow and trigger user authorization request.
    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
            HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
            .setDataStoreFactory(new FileDataStoreFactory(new java.io.File(TOKENS_DIRECTORY_PATH)))
            .setAccessType("offline")
            .build();
    LocalServerReceiver receiver = new LocalServerReceiver.Builder().setPort(8888).build();
    return new AuthorizationCodeInstalledApp(flow, receiver).authorize("user");
}
 
Example #15
Source File: GoogleDriveRuntime.java    From components with Apache License 2.0 6 votes vote down vote up
private Credential getCredential(NetHttpTransport httpTransport) throws IOException, GeneralSecurityException {
    GoogleDriveConnectionProperties conn = getConnectionProperties();
    /* get rid of warning on windows until fixed... https://github.com/google/google-http-java-client/issues/315 */
    final java.util.logging.Logger dsLogger = java.util.logging.Logger.getLogger(FileDataStoreFactory.class.getName());
    dsLogger.setLevel(java.util.logging.Level.SEVERE);
    switch (conn.oAuthMethod.getValue()) {
    case AccessToken:
        return GoogleDriveCredentialWithAccessToken.builder().accessToken(conn.accessToken.getValue()).build();
    case InstalledApplicationWithIdAndSecret:
        return GoogleDriveCredentialWithInstalledApplication.builderWithIdAndSecret(httpTransport, getDatastoreFile(conn))
                .clientId(conn.clientId.getValue()).clientSecret(conn.clientSecret.getValue()).build();
    case InstalledApplicationWithJSON:
        return GoogleDriveCredentialWithInstalledApplication.builderWithJSON(httpTransport, getDatastoreFile(conn))
                .clientSecretFile(new File(conn.clientSecretFile.getValue())).build();
    case ServiceAccount:
        return GoogleDriveCredentialWithServiceAccount.builder()
                .serviceAccountJSONFile(new File(conn.serviceAccountFile.getValue())).build();
    }
    throw new IllegalArgumentException(messages.getMessage("error.credential.oaut.method"));
}
 
Example #16
Source File: DriveQuickstart.java    From java-samples with Apache License 2.0 6 votes vote down vote up
/**
 * Creates an authorized Credential object.
 * @param HTTP_TRANSPORT The network HTTP Transport.
 * @return An authorized Credential object.
 * @throws IOException If the credentials.json file cannot be found.
 */
private static Credential getCredentials(final NetHttpTransport HTTP_TRANSPORT) throws IOException {
    // Load client secrets.
    InputStream in = DriveQuickstart.class.getResourceAsStream(CREDENTIALS_FILE_PATH);
    if (in == null) {
        throw new FileNotFoundException("Resource not found: " + CREDENTIALS_FILE_PATH);
    }
    GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));

    // Build flow and trigger user authorization request.
    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
            HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
            .setDataStoreFactory(new FileDataStoreFactory(new java.io.File(TOKENS_DIRECTORY_PATH)))
            .setAccessType("offline")
            .build();
    LocalServerReceiver receiver = new LocalServerReceiver.Builder().setPort(8888).build();
    return new AuthorizationCodeInstalledApp(flow, receiver).authorize("user");
}
 
Example #17
Source File: GetUserProfile.java    From rides-java-sdk with MIT License 6 votes vote down vote up
/**
 * Creates an {@link OAuth2Credentials} object that can be used by any of the servlets.
 */
public static OAuth2Credentials createOAuth2Credentials(SessionConfiguration sessionConfiguration) throws Exception {




    // Store the users OAuth2 credentials in their home directory.
    File credentialDirectory =
            new File(System.getProperty("user.home") + File.separator + ".uber_credentials");
    credentialDirectory.setReadable(true, true);
    credentialDirectory.setWritable(true, true);
    // If you'd like to store them in memory or in a DB, any DataStoreFactory can be used.
    AbstractDataStoreFactory dataStoreFactory = new FileDataStoreFactory(credentialDirectory);

    // Build an OAuth2Credentials object with your secrets.
    return new OAuth2Credentials.Builder()
            .setCredentialDataStoreFactory(dataStoreFactory)
            .setRedirectUri(sessionConfiguration.getRedirectUri())
            .setClientSecrets(sessionConfiguration.getClientId(), sessionConfiguration.getClientSecret())
            .build();
}
 
Example #18
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 #19
Source File: DailyMotionSample.java    From google-oauth-java-client with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
  try {
    DATA_STORE_FACTORY = new FileDataStoreFactory(DATA_STORE_DIR);
    final Credential credential = authorize();
    HttpRequestFactory requestFactory =
        HTTP_TRANSPORT.createRequestFactory(new HttpRequestInitializer() {
          @Override
          public void initialize(HttpRequest request) throws IOException {
            credential.initialize(request);
            request.setParser(new JsonObjectParser(JSON_FACTORY));
          }
        });
    run(requestFactory);
    // Success!
    return;
  } catch (IOException e) {
    System.err.println(e.getMessage());
  } catch (Throwable t) {
    t.printStackTrace();
  }
  System.exit(1);
}
 
Example #20
Source File: GoogleDriveFactory.java    From google-drive-ftp-adapter with GNU Lesser General Public License v3.0 6 votes vote down vote up
public GoogleDriveFactory(Properties configuration) {
    /* Directory to store user credentials. */
    java.io.File DATA_STORE_DIR = new java.io.File("data/google/" + configuration.getProperty("account", "default"));
    
    authPort = Integer.parseInt(configuration.getProperty("auth.port", String.valueOf("-1")));

    try {
        // initialize the data store factory
        dataStoreFactory = new FileDataStoreFactory(DATA_STORE_DIR);
        // initialize the transport
        httpTransport = GoogleNetHttpTransport.newTrustedTransport();

    } catch (Exception e) {
        throw new RuntimeException("Error intializing google drive API", e);
    }
}
 
Example #21
Source File: gdoc2adoc.java    From gdoc2adoc with Apache License 2.0 6 votes vote down vote up
/**
 * Creates an authorized Credential object.
 *
 * @param HTTP_TRANSPORT The network HTTP Transport.
 * @return An authorized Credential object.
 * @throws IOException If the credentials.json file cannot be found.
 */
private Credential getCredentials(final NetHttpTransport HTTP_TRANSPORT)
        throws IOException {
    // Load client secrets.
    GoogleClientSecrets secrets =
            GoogleClientSecrets.load(JSON_FACTORY, new FileReader(credentials));

    // Build flow and trigger user authorization request.
    GoogleAuthorizationCodeFlow flow =
            new GoogleAuthorizationCodeFlow.Builder(HTTP_TRANSPORT, JSON_FACTORY, secrets, SCOPES)
                    .setDataStoreFactory(new FileDataStoreFactory(new java.io.File(TOKENS_DIRECTORY_PATH)))
                    .setAccessType("offline")
                    .build();
    LocalServerReceiver receiver = new LocalServerReceiver.Builder().setPort(8888).build();
    return new AuthorizationCodeInstalledApp(flow, receiver).authorize("user");
}
 
Example #22
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 #23
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 #24
Source File: PhotosLibraryClientFactory.java    From java-photoslibrary with Apache License 2.0 6 votes vote down vote up
private static Credentials getUserCredentials(String credentialsPath, List<String> selectedScopes)
    throws IOException, GeneralSecurityException {
  GoogleClientSecrets clientSecrets =
      GoogleClientSecrets.load(
          JSON_FACTORY, new InputStreamReader(new FileInputStream(credentialsPath)));
  String clientId = clientSecrets.getDetails().getClientId();
  String clientSecret = clientSecrets.getDetails().getClientSecret();

  GoogleAuthorizationCodeFlow flow =
      new GoogleAuthorizationCodeFlow.Builder(
              GoogleNetHttpTransport.newTrustedTransport(),
              JSON_FACTORY,
              clientSecrets,
              selectedScopes)
          .setDataStoreFactory(new FileDataStoreFactory(DATA_STORE_DIR))
          .setAccessType("offline")
          .build();
  LocalServerReceiver receiver =
      new LocalServerReceiver.Builder().setPort(LOCAL_RECEIVER_PORT).build();
  Credential credential = new AuthorizationCodeInstalledApp(flow, receiver).authorize("user");
  return UserCredentials.newBuilder()
      .setClientId(clientId)
      .setClientSecret(clientSecret)
      .setRefreshToken(credential.getRefreshToken())
      .build();
}
 
Example #25
Source File: SearchHelper.java    From connector-sdk with Apache License 2.0 5 votes vote down vote up
private static Credential createCredentials(
    HttpTransport httpTransport, SearchAuthInfo searchAuthInfo)
    throws IOException {
  GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(
      JSON_FACTORY, new InputStreamReader(searchAuthInfo.getClientSecretsStream(), UTF_8));
  GoogleAuthorizationCodeFlow flow =
      new GoogleAuthorizationCodeFlow.Builder(
          httpTransport, JSON_FACTORY, clientSecrets, API_SCOPES)
          .setDataStoreFactory(new FileDataStoreFactory(searchAuthInfo.getCredentialsDirectory()))
          .build();
  return flow.loadCredential(searchAuthInfo.getUserEmail());
}
 
Example #26
Source File: GmailServiceMaker.java    From teammates with GNU General Public License v2.0 5 votes vote down vote up
private GoogleAuthorizationCodeFlow buildFlow(GoogleClientSecrets clientSecrets) throws IOException {
    // if the scopes need to change, the user will need to manually delete
    // <TestProperties.TEST_GMAIL_API_FOLDER>/StoredCredential
    List<String> scopes = Arrays.asList(GmailScopes.GMAIL_READONLY, GmailScopes.GMAIL_MODIFY);
    FileDataStoreFactory dataStoreFactory = new FileDataStoreFactory(new File(TestProperties.TEST_GMAIL_API_FOLDER));
    return new GoogleAuthorizationCodeFlow.Builder(
            HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, scopes)
            .setDataStoreFactory(dataStoreFactory)
            .setAccessType("offline")
            .build();
}
 
Example #27
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 #28
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 #29
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 #30
Source File: AuthModule.java    From nomulus with Apache License 2.0 5 votes vote down vote up
@Provides
@Singleton
public static AbstractDataStoreFactory provideDataStoreFactory() {
  try {
    return new FileDataStoreFactory(DATA_STORE_DIR);
  } catch (IOException ex) {
    throw new RuntimeException(ex);
  }
}