Example usage for com.google.api.client.googleapis.auth.oauth2 GoogleClientSecrets load

List of usage examples for com.google.api.client.googleapis.auth.oauth2 GoogleClientSecrets load

Introduction

In this page you can find the example usage for com.google.api.client.googleapis.auth.oauth2 GoogleClientSecrets load.

Prototype

public static GoogleClientSecrets load(JsonFactory jsonFactory, Reader reader) throws IOException 

Source Link

Document

Loads the client_secrets.json file from the given reader.

Usage

From source file:pkg398gmail.GmailMethods.java

public static void firstRun() throws IOException {
    clientSecrets = GoogleClientSecrets.load(jsonFactory, new FileReader(CLIENT_SECRET_PATH));

    /*/*  ww  w.  j a  v  a 2s .  co m*/
     This approach requires passing a one-time authorization code from your client to your server; 
     this code is used to acquire an access token and refresh tokens for your server.
            
     */
    /*
            
     When a user loads your application for the first time, 
     they are presented with a dialog to grant permission for your application to access their Gmail 
     account with the requested permission scopes. After this initial authorization, 
     the user is ********only presented with the permission dialog************* if your app's
     client ID changes or the requested scopes have changed.
            
     */
    // Allow user to authorize via url.

    flow = new GoogleAuthorizationCodeFlow.Builder(httpTransport, jsonFactory, clientSecrets,
            Arrays.asList(SCOPE)).setAccessType("offline").setApprovalPrompt("force").build();

    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.
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    code = br.readLine();
    //code="1/UGFqD3rQdkT2lSOHbCpSS7-2eCWoWP8zPOyMgHHYyh4";

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

    /*
     online use 
     credential = new GoogleCredential()
     .setFromTokenResponse(response);
     */
    // offline use.
    //http://stackoverflow.com/questions/15064636/googlecredential-wont-build-without-googlecredential-builder

    //http://stackoverflow.com/questions/10533203/fetching-access-token-from-refresh-token-using-java

    createCredential();

    // now we get the refresh token. We use this refresh the user session.      
    String refToken = credential.getRefreshToken();
    System.out.println("Refresh Token:  " + refToken);

    // Create a new authorized Gmail API client
    createService();
    // send message
    send();

}

From source file:pkg398gmail.GmailMethods.java

public static void normalRun() throws IOException {
    clientSecrets = GoogleClientSecrets.load(jsonFactory, new FileReader(CLIENT_SECRET_PATH));
    createCredentialWithRefresh();// w ww .j a v  a 2s  .c  om

    // now we get the refresh token. We use this refresh the user session.      
    String refToken = credential.getRefreshToken();
    System.out.println("Refresh Token:  " + refToken);

    // Create a new authorized Gmail API client
    createService();
    // send message
    send();
}

From source file:pkg398gmail.GmailRun.java

public static void normalRun() throws IOException {
    clientSecrets = GoogleClientSecrets.load(jsonFactory, new FileReader(CLIENT_SECRET_PATH));

    createCredentialWithRefresh();// w  w w.j  av a 2 s .co  m

    // now we get the refresh token. We use this refresh the user session.      
    String refToken = credential.getRefreshToken();
    System.out.println("Refresh Token:  " + refToken);

    // Create a new authorized Gmail API client
    createService();
    // send message
    send();
}

From source file:raspi_ui.backend.calendar.CalendarData.java

License:Apache License

private static Credential authorize() throws Exception {
    // load client secrets
    GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY,
            new InputStreamReader(CalendarData.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=calendar "
                + "into calendar-cmdline-sample/src/main/resources/client_secrets.json");
        System.exit(1);//from w ww .ja  v a2s  .c  om
    }
    // set up authorization code flow
    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(httpTransport, JSON_FACTORY,
            clientSecrets, Collections.singleton(CalendarScopes.CALENDAR)).setDataStoreFactory(dataStoreFactory)
                    .build();
    // authorize
    return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
}

From source file:remotedrive.client.googledrive.GoogleDriveClient.java

License:Open Source License

/**
 * Authenticates to Google Drive account.
 * @param username The google account email address.
 * @param password Always empty for google drive authentication
 *//*  www . j a  v  a2 s . c  o  m*/
public void authenticate(String username, char[] password) {
    // Arguments validation
    if (null == username || username.length() == 0) {
        throw new IllegalArgumentException("Username has to be provided");
    }

    try {
        // Initialize internal state
        HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
        JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();

        // Initialize the client secrets
        GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(jsonFactory,
                new InputStreamReader(GoogleDriveClient.class.getResourceAsStream("/client_secrets.json")));

        // Initialize authorization flow
        GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(httpTransport, jsonFactory,
                clientSecrets, Arrays.asList(DriveScopes.DRIVE))
                        .setDataStoreFactory(new FileDataStoreFactory(
                                new java.io.File(System.getProperty("user.home"), ".store/cloud_storage")))
                        .setApprovalPrompt("auto").setAccessType("offline").build();

        // Initialize the credentials for installed application
        credential = new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize(username);

        // Initialize the drive service
        driveService = new com.google.api.services.drive.Drive.Builder(httpTransport, jsonFactory, credential)
                .setApplicationName("CloudStorage").build();

        // Retrieve about resource in order to initialize disk information
        com.google.api.services.drive.Drive.About.Get get = driveService.about().get();
        About about = get.execute();

        // Add root in the FS index
        pathsToIdsIndex.put("", about.getRootFolderId());

        // Initialize disk information
        drive = new Drive(about.getQuotaBytesTotal(), about.getQuotaBytesUsed());
    } catch (Exception e) {
        throw new ClientAuthenticationException(String.format("Unable to authentication as %s", username), e);
    }
}

From source file:rescustomerservices.GmailQuickstart.java

/**
 * Creates an authorized Credential object.
 * @return an authorized Credential object.
 * @throws IOException/*www .  j  a  va2s . c  om*/
 */
public static Credential authorize() throws IOException {
    // Load client secrets.
    InputStream in = GmailQuickstart.class.getResourceAsStream("client_secret.json");
    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;
}

From source file:ru.tiis.library.service.impl.GDriveService.java

License:Apache License

private static GoogleAuthorizationCodeFlow buildAuthorizationFlow() throws IOException {

    // load client secrets
    java.io.File credentials = new java.io.File(
            GDriveService.class.getResource("upload-service-credentials.json").getFile());
    log.info("Data store dir : " + DATA_STORE_DIR);
    FileInputStream fis = new FileInputStream(credentials);
    GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(fis));
    if (clientSecrets.getDetails().getClientId().startsWith("Enter")
            || clientSecrets.getDetails().getClientSecret().startsWith("Enter ")) {

        log.warn("Enter Client ID and Secret from https://code.google.com/apis/console/?api=drive "
                + "into drive-cmdline-sample/src/main/resources/client_secrets.json");
        return null;
    }//from w  w w .j  a  v a 2s.c om
    log.info("Google client secrets loaded");

    // set up authorization flow configuration
    log.info("Building authorization code flow...");
    GoogleAuthorizationCodeFlow.Builder flowBuilder = new GoogleAuthorizationCodeFlow.Builder(httpTransport,
            JSON_FACTORY, clientSecrets, Collections.singleton(DriveScopes.DRIVE_FILE))
                    .setDataStoreFactory(dataStoreFactory).setAccessType("offline").setApprovalPrompt("force");
    GoogleAuthorizationCodeFlow flow = flowBuilder.build();
    log.info("Building authorization code flow - done");

    return flow;
}

From source file:SchedulingHeuristic.GCalAccessForLocalApplication.java

License:Open Source License

/**
 * Creates an authorized Credential object.
 * @return an authorized Credential object.
 * @throws IOException/*w ww .j  a va2s. co  m*/
 */
public static Credential authorize() throws IOException {
    // Load client secrets.
    InputStream in = GCalAccessForLocalApplication.class.getResourceAsStream("/client_secret.json");
    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;
}

From source file:sciuto.corey.alerter.drive.google.GoogleDriveWrapper.java

License:Apache License

/**
 * Creates the Google Drive client. Pass in the pointer to
 * clients_secret.json./*from   w  ww.j  a va  2s  .c  o m*/
 * 
 * @see https://developers.google.com/identity/protocols/OAuth2
 * 
 * @param secretsLocation
 * @return
 * @throws IOException
 * @throws GeneralSecurityException 
 */
public GoogleDriveWrapper(String secretsLocation) throws IOException, GeneralSecurityException {
    HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
    File dataStoreDirectory = new File("dataStore/");
    dataStoreDirectory.mkdir();
    FileDataStoreFactory dataStoreFactory = new FileDataStoreFactory(dataStoreDirectory);
    JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();

    GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(jsonFactory, new FileReader(secretsLocation));
    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(httpTransport, jsonFactory,
            clientSecrets, Collections.singleton(DriveScopes.DRIVE_FILE)).setDataStoreFactory(dataStoreFactory)
                    .build();

    Credential credential = new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver())
            .authorize("user");

    Drive drive = new Drive.Builder(httpTransport, jsonFactory, credential)
            .setApplicationName("CoreySciuto-Alerter/0.1").build();
    this.drive = drive;
}

From source file:Scrappers.Auth.java

/**
 * Authorizes the installed application to access user's protected data.
 *
 * @param scopes              list of scopes needed to run youtube upload.
 * @param credentialDatastore name of the credential datastore to cache OAuth tokens
 *///from   w w w .j  a  va  2  s  .c  o  m
public static Credential authorize(List<String> scopes, String credentialDatastore) throws IOException {

    // Load client secrets.
    Reader clientSecretReader = new InputStreamReader(Auth.class.getResourceAsStream("/client_secrets.json"));
    GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, clientSecretReader);

    // Checks that the defaults have been replaced (Default = "Enter X here").
    if (clientSecrets.getDetails().getClientId().startsWith("Enter")
            || clientSecrets.getDetails().getClientSecret().startsWith("Enter ")) {
        System.out.println(
                "Enter Client ID and Secret from https://console.developers.google.com/project/_/apiui/credential "
                        + "into src/main/resources/client_secrets.json");
        System.exit(1);
    }

    // This creates the credentials datastore at ~/.oauth-credentials/${credentialDatastore}
    FileDataStoreFactory fileDataStoreFactory = new FileDataStoreFactory(
            new File(System.getProperty("user.home") + "/" + CREDENTIALS_DIRECTORY));
    DataStore<StoredCredential> datastore = fileDataStoreFactory.getDataStore(credentialDatastore);

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

    // Build the local server and bind it to port 8080
    LocalServerReceiver localReceiver = new LocalServerReceiver.Builder().setPort(8080).build();

    // Authorize.
    return new AuthorizationCodeInstalledApp(flow, localReceiver).authorize("user");
}