Java Code Examples for com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets#load()

The following examples show how to use com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets#load() . 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: DriveActivityQuickstart.java    From java-samples with Apache License 2.0 7 votes vote down vote up
/**
 * Creates an authorized Credential object.
 *
 * @return an authorized Credential object.
 * @throws IOException
 */
public static Credential authorize() throws IOException {
    // Load client secrets.
    InputStream in = DriveActivityQuickstart.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(DATA_STORE_FACTORY)
                    .setAccessType("offline")
                    .build();
    Credential credential =
            new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver())
                    .authorize("user");
    System.out.println("Credentials saved to " + DATA_STORE_DIR.getAbsolutePath());
    return credential;
}
 
Example 3
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 4
Source File: GoogleSheetsAuth.java    From jbpm-work-items with Apache License 2.0 6 votes vote down vote up
public Credential authorize(String clientSecretJSON) throws Exception {
    GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY,
                                                                 new StringReader(clientSecretJSON));

    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
            HTTP_TRANSPORT,
            JSON_FACTORY,
            clientSecrets,
            Collections.singleton(SheetsScopes.SPREADSHEETS_READONLY))
            .build();

    return new AuthorizationCodeInstalledApp(flow,
                                             new LocalServerReceiver()).authorize("user");
}
 
Example 5
Source File: GoogleMailAuth.java    From jbpm-work-items with Apache License 2.0 6 votes vote down vote up
public Credential authorize(String clientSecretJSON) throws Exception {
    GoogleClientSecrets clientSecrets =
            GoogleClientSecrets.load(JSON_FACTORY,
                                     new StringReader(clientSecretJSON));

    GoogleAuthorizationCodeFlow flow =
            new GoogleAuthorizationCodeFlow.Builder(
                    HTTP_TRANSPORT,
                    JSON_FACTORY,
                    clientSecrets,
                    SCOPES)
                    .setAccessType("offline")
                    .build();
    Credential credential = new AuthorizationCodeInstalledApp(
            flow,
            new LocalServerReceiver()).authorize("user");
    return credential;
}
 
Example 6
Source File: Main.java    From google-sites-liberation with Apache License 2.0 6 votes vote down vote up
/** Authorizes the installed application to access user's protected data. 
* @throws Exception */
 private static Credential authorize() throws Exception {
   // load client secrets
   clientSecrets = GoogleClientSecrets.load(JSON_FACTORY,
       new InputStreamReader(Main.class.getResourceAsStream("/client_secrets.json")));
   if (clientSecrets.getDetails().getClientId().startsWith("Enter")
       || clientSecrets.getDetails().getClientSecret().startsWith("Enter")) {
     System.out.println("Enter Client ID and Secret from https://code.google.com/apis/console/ "
         + "into google-sites-liberation/src/main/resources/client_secrets.json");
     System.exit(1);
   }
   // set up authorization code flow
   GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
       httpTransport, JSON_FACTORY, clientSecrets, SCOPES).setDataStoreFactory(
       dataStoreFactory).setAccessType("offline").build();
   
   //Loading receiver on 8080 port (you can change this if already in use) 
   LocalServerReceiver localServerReceiver = new LocalServerReceiver.Builder().setPort( 8080 ).build(); 
   
   // authorize
   return new AuthorizationCodeInstalledApp(flow, localServerReceiver).authorize("user");
 }
 
Example 7
Source File: Utils.java    From java-samples with Apache License 2.0 6 votes vote down vote up
/** Authorizes the installed application to access user's protected data. */
public static Credential authorize(List<String> scopes) throws Exception {
  // Load client secrets.
  GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY,
      new InputStreamReader(SyncTokenSample.class.getResourceAsStream("/client_secrets.json")));
  if (clientSecrets.getDetails().getClientId().startsWith("Enter")
      || clientSecrets.getDetails().getClientSecret().startsWith("Enter")) {
    System.out.println(
        "Overwrite the src/main/resources/client_secrets.json file with the client secrets file "
        + "you downloaded from your Google Developers Console project.");
    System.exit(1);
  }

  GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(httpTransport,
      JSON_FACTORY, clientSecrets, scopes).setDataStoreFactory(dataStoreFactory).build();
  // Authorize.
  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: 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: 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 11
Source File: GoogleDriveFileObject.java    From pentaho-kettle with Apache License 2.0 6 votes vote down vote up
private Credential authorize() throws IOException {
  InputStream
      in =
      new FileInputStream( resolveCredentialsPath() + "/" + resourceBundle.getString( "client.secrets" ) );
  GoogleClientSecrets clientSecrets = GoogleClientSecrets.load( JSON_FACTORY, new InputStreamReader( in ) );

  GoogleAuthorizationCodeFlow
      flow =
      new GoogleAuthorizationCodeFlow.Builder( HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES )
          .setDataStoreFactory( DATA_STORE_FACTORY ).setAccessType( "offline" ).build();

  Credential
      credential =
      new CustomAuthorizationCodeInstalledApp( flow, new CustomLocalServerReceiver() ).authorize( "user" );
  return credential;
}
 
Example 12
Source File: GmailServiceMaker.java    From teammates with GNU General Public License v2.0 5 votes vote down vote up
private GoogleClientSecrets loadClientSecretFromJson() throws IOException {
    try (InputStream in = Files.newInputStream(Paths.get(TestProperties.TEST_GMAIL_API_FOLDER, "client_secret.json"))) {
        return GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));
    } catch (FileNotFoundException e) {
        throw new RuntimeException("You need to set up your Gmail API credentials." + System.lineSeparator()
                + "See docs/development.md section \"Deploying to a staging server\".", e);
    }
}
 
Example 13
Source File: Authorizer.java    From mail-importer with Apache License 2.0 5 votes vote down vote up
private GoogleClientSecrets loadGoogleClientSecrets(JsonFactory jsonFactory)
    throws IOException {
  URL url = Resources.getResource("client_secret.json");
  CharSource inputSupplier =
      Resources.asCharSource(url, Charsets.UTF_8);
  return GoogleClientSecrets.load(jsonFactory, inputSupplier.openStream());
}
 
Example 14
Source File: GoogleDriveCredentialWithInstalledApplication.java    From components with Apache License 2.0 5 votes vote down vote up
@Override
public Credential build() throws IOException {
    GoogleClientSecrets secrets = GoogleClientSecrets.load(JSON_FACTORY, new FileReader(clientSecretFile));
    // make a sanity check (check this.installed) before authorizing
    secrets.getDetails().getClientId();
    // Build flow and trigger user authorization request.
    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(httpTransport, JSON_FACTORY, secrets,
            scopes).setDataStoreFactory(dataStoreFactory).setAccessType("offline").build();
    return new AuthorizationCodeInstalledAppTalend(flow, new LocalServerReceiver()).authorize("user");
}
 
Example 15
Source File: GoogleDriveFileObject.java    From hop with Apache License 2.0 5 votes vote down vote up
private Credential authorize() throws IOException {
  InputStream in = new FileInputStream( resolveCredentialsPath() + "/" + resourceBundle.getString( "client.secrets" ) );
  GoogleClientSecrets clientSecrets = GoogleClientSecrets.load( JSON_FACTORY, new InputStreamReader( in ) );

  GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder( HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES )
          .setDataStoreFactory( DATA_STORE_FACTORY ).setAccessType( "offline" ).build();

  Credential credential = new CustomAuthorizationCodeInstalledApp( flow, new CustomLocalServerReceiver() ).authorize( "user" );
  return credential;
}
 
Example 16
Source File: GoogleCalendarAuth.java    From jbpm-work-items with Apache License 2.0 5 votes vote down vote up
public Credential authorize(String clientSecretJSON) throws Exception {
    GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY,
                                                                 new StringReader(clientSecretJSON));

    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
            HTTP_TRANSPORT,
            JSON_FACTORY,
            clientSecrets,
            Collections.singleton(CalendarScopes.CALENDAR))
            .build();

    return new AuthorizationCodeInstalledApp(flow,
                                             new LocalServerReceiver()).authorize("user");
}
 
Example 17
Source File: GoogleTasksAuth.java    From jbpm-work-items with Apache License 2.0 5 votes vote down vote up
public Credential authorize(String clientSecretJSON) throws Exception {
    GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY,
                                                                 new StringReader(clientSecretJSON));

    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
            HTTP_TRANSPORT,
            JSON_FACTORY,
            clientSecrets,
            SCOPES)
            .build();

    return new AuthorizationCodeInstalledApp(flow,
                                             new LocalServerReceiver()).authorize("user");
}
 
Example 18
Source File: GApiGateway.java    From gdx-gamesvcs with Apache License 2.0 5 votes vote down vote up
/**
 * Be sure to specify the name of your application. If the application name
 * is {@code null} or blank, the application will log a warning. Suggested
 * format is "MyCompany-ProductName/1.0".
 */
public static void init(String applicationName, InputStream clientSecret, File dataStoreDirectory) throws
        GeneralSecurityException, IOException {
    GApiGateway.applicationName = applicationName;
    GApiGateway.clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(clientSecret));

    httpTransport = GoogleNetHttpTransport.newTrustedTransport();

    dataStoreFactory = new FileDataStoreFactory(dataStoreDirectory);
}
 
Example 19
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 20
Source File: FirstApiRequest.java    From googleads-adxseller-examples with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {
  httpTransport = GoogleNetHttpTransport.newTrustedTransport();
  dataStoreFactory = new FileDataStoreFactory(DATA_STORE_DIR);

  GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(
      jsonFactory, new InputStreamReader(
          FirstApiRequest.class.getResourceAsStream("/client_secrets.json")));
  if (clientSecrets.getDetails().getClientId().startsWith("Enter")
      || clientSecrets.getDetails().getClientSecret().startsWith("Enter ")) {
    System.out.println("Enter Client ID and Secret from "
        + "https://code.google.com/apis/console/?api=adexchangeseller into "
        + "adexchangeseller-cmdline-sample/src/main/resources/client_secrets.json");
    System.exit(1);
  }
  // set up authorization code flow
  GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
      httpTransport, jsonFactory, clientSecrets,
      Collections.singleton(AdExchangeSellerScopes.ADEXCHANGE_SELLER_READONLY))
      .setDataStoreFactory(dataStoreFactory).build();
  // authorize and get credentials
  Credential credential =
      new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver())
        .authorize("user");

  // Create an authorized AdExchangeSeller instance
  AdExchangeSeller adExchangeSeller = new AdExchangeSeller.Builder(httpTransport,
      jsonFactory, credential).setApplicationName(APPLICATION_NAME).build();

  // Set up a report object for the last 7 days’ performance
  Generate request = adExchangeSeller.accounts().reports().generate("myaccount",
      "today-6d", "today");

  // Add report dimensions
  request.setDimension(Arrays.asList("DATE", "WINNING_BID_RULE_NAME"));
  // Add report metrics
  request.setMetric(Arrays.asList("AD_REQUESTS", "CLICKS"));

  // Run the report.
  // If this was a bigger report we would use paging, see GenerateReportWithPaging.java
  Report response = request.execute();

  if (response.getRows() == null || response.getRows().isEmpty()) {
    System.out.println("No rows returned.");
    return;
  }

  // Display the returned data
  displayHeaders(response.getHeaders());
  displayRows(response.getRows());
  displayTotals(response.getTotals());
}