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:com.github.drbookings.google.GoogleCalendarSync.java

License:Open Source License

/**
 * Authorizes the installed application to access user's protected data.
 *///from ww w  . ja  v a  2 s . c  o m
private static Credential authorize() throws Exception {
    // load client secrets
    final GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY,
            new InputStreamReader(GoogleCalendarSync.class.getResourceAsStream("/client_secrets.json")));
    if (clientSecrets.getDetails().getClientId().startsWith("Enter")
            || clientSecrets.getDetails().getClientSecret().startsWith("Enter ")) {
        if (logger.isErrorEnabled()) {
            logger.error("Enter Client ID and Secret from https://code.google.com/apis/console/?api=calendar "
                    + "into calendar-cmdline-sample/src/main/resources/client_secrets.json");
        }
        return null;
    }
    // set up authorization code flow
    final GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(httpTransport,
            JSON_FACTORY, clientSecrets, Collections.singleton(CalendarScopes.CALENDAR))
                    .setDataStoreFactory(dataStoreFactory).build();
    // authorize
    return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver())
            .authorize("557837674207-61uehop5b0u5enflhc7ata9a75sf731e.apps.googleusercontent.com");
}

From source file:com.github.robozonky.integrations.stonky.GoogleCredentialProvider.java

License:Apache License

private GoogleClientSecrets createClientSecrets() {
    final byte[] key = secrets.get();
    return Try.withResources(() -> new ByteArrayInputStream(key))
            .of(s -> GoogleClientSecrets.load(Util.JSON_FACTORY, new InputStreamReader(s)))
            .getOrElseThrow((Function<Throwable, IllegalStateException>) IllegalStateException::new);
}

From source file:com.github.valentin.fedoskin.fb2me.desktop.drive.DriveSample.java

License:Apache License

/** Authorizes the installed application to access user's protected data. */
private static Credential authorize() throws Exception {
    // load client secrets
    GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY,
            DriveSample.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=drive "
                + "into drive-cmdline-sample/src/main/resources/client_secrets.json");
        System.exit(1);/*from w  ww .jav a 2  s .  c  om*/
    }
    // set up file credential store
    FileCredentialStore credentialStore = new FileCredentialStore(
            new java.io.File(System.getProperty("user.home"), ".credentials/drive.json"), JSON_FACTORY);
    // set up authorization code flow
    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(HTTP_TRANSPORT, JSON_FACTORY,
            clientSecrets, Collections.singleton(DriveScopes.DRIVE_FILE)).setCredentialStore(credentialStore)
                    .build();
    // authorize
    return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
}

From source file:com.google.bidmanager.api.samples.SecurityUtilities.java

License:Apache License

public static Credential getUserCredential() throws Exception {
    GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY,
            new InputStreamReader(SecurityUtilities.class.getResourceAsStream("/client_secrets.json")));
    dataStoreFactory = new FileDataStoreFactory(DATA_STORE_DIR);

    // set up authorization code flow.
    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(HTTP_TRANSPORT, JSON_FACTORY,
            clientSecrets, SCOPES).setDataStoreFactory(dataStoreFactory).build();
    // authorize and get credentials.
    Credential credential = new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver())
            .authorize("user");

    return credential;
}

From source file:com.google.cloud.bigquery.samples.BigQueryJavaGettingStarted.java

License:Apache License

/**
 *  Helper to load client ID/Secret from file.
 *
 * @param clientSecretsLocation a path to a client_secrets.json file
 * @return a ClientSecrets object created from a client_secrets.json file
 *//*w ww  .j a v  a 2s . c o m*/
private static GoogleClientSecrets loadClientSecrets(String clientSecretsLocation) {
    try {
        clientSecrets = GoogleClientSecrets.load(new JacksonFactory(),
                BigQueryJavaGettingStarted.class.getResourceAsStream(clientSecretsLocation));
    } catch (Exception e) {
        System.out.println("Could not load client_secrets.json");
        e.printStackTrace();
    }
    return clientSecrets;
}

From source file:com.google.cloud.bigquery.snowball.BigQueryJavaGettingStarted.java

License:Apache License

/**
 * Helper to load client ID/Secret from file.
 *
 * @return a GoogleClientSecrets object based on a clientsecrets.json
 *///from   www.  j av  a2 s. c  o m
private static GoogleClientSecrets loadClientSecrets() {
    try {
        InputStream inputStream = new FileInputStream(CLIENTSECRETS_LOCATION);
        Reader reader = new InputStreamReader(inputStream);
        GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(new JacksonFactory(), reader);
        return clientSecrets;
    } catch (Exception e) {
        System.out.println("Could not load client secrets file " + CLIENTSECRETS_LOCATION);
        e.printStackTrace();
    }
    return null;
}

From source file:com.google.cloud.dataflow.sdk.util.Credentials.java

License:Apache License

/**
 * Loads OAuth2 credential from client secrets, which may require an
 * interactive authorization prompt.//  ww  w  . jav a  2 s  . c o  m
 */
private static Credential getCredentialFromClientSecrets(GcpOptions options, Collection<String> scopes)
        throws IOException, GeneralSecurityException {
    String clientSecretsFile = options.getSecretsFile();

    Preconditions.checkArgument(clientSecretsFile != null);
    HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();

    JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
    GoogleClientSecrets clientSecrets;

    try {
        clientSecrets = GoogleClientSecrets.load(jsonFactory, new FileReader(clientSecretsFile));
    } catch (IOException e) {
        throw new RuntimeException("Could not read the client secrets from file: " + clientSecretsFile, e);
    }

    FileDataStoreFactory dataStoreFactory = new FileDataStoreFactory(
            new java.io.File(options.getCredentialDir()));

    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(httpTransport, jsonFactory,
            clientSecrets, scopes).setDataStoreFactory(dataStoreFactory)
                    .setTokenServerUrl(new GenericUrl(options.getTokenServerUrl()))
                    .setAuthorizationServerEncodedUrl(options.getAuthorizationServerEncodedUrl()).build();

    // The credentialId identifies the credential if we're using a persistent
    // credential store.
    Credential credential = new AuthorizationCodeInstalledApp(flow, new PromptReceiver())
            .authorize(options.getCredentialId());

    LOG.info("Got credential from client secret");
    return credential;
}

From source file:com.google.cloud.genomics.gatk.common.grpc.GenomicsDataSource.java

License:Open Source License

private Channel initGenomicsChannel() throws FileNotFoundException, IOException, GeneralSecurityException {
    checkParamsForAuth(AUTH_REQUIREMENTS.CLIENT_SECRETS_ONLY);
    final GoogleClientSecrets secrets = GoogleClientSecrets.load(Utils.getDefaultJsonFactory(),
            new FileReader(clientSecretsFilename));
    final OfflineAuth auth = getFactory().getOfflineAuthFromClientSecretsFile(clientSecretsFilename);
    final UserCredentials userCredentials = new UserCredentials(secrets.getInstalled().getClientId(),
            secrets.getInstalled().getClientSecret(), auth.refreshToken);

    // Java 8's implementation of GCM ciphers is extremely slow. Therefore we disable
    // them here.
    List<String> defaultCiphers = GrpcSslContexts.forClient().ciphers(null).build().cipherSuites();
    List<String> performantCiphers = new ArrayList<>();
    for (String cipher : defaultCiphers) {
        if (!cipher.contains("GCM")) {
            performantCiphers.add(cipher);
        }/*from   www  .j  a v a  2 s  .  c om*/
    }

    channelImpl = NettyChannelBuilder.forAddress("genomics.googleapis.com", 443)
            .negotiationType(NegotiationType.TLS).streamWindowSize(1000000)
            .sslContext(GrpcSslContexts.forClient().ciphers(performantCiphers).build()).build();
    /*userCredentials = userCredentials.createScoped(
        Arrays.asList("https://www.googleapis.com/auth/genomics"));*/
    ClientAuthInterceptor interceptor = new ClientAuthInterceptor(userCredentials,
            Executors.newSingleThreadExecutor());
    return ClientInterceptors.intercept(channelImpl, interceptor);
}

From source file:com.google.cloud.genomics.utils.CredentialFactory.java

License:Apache License

/**
 * Creates an OAuth2 credential from client secrets, which may require an interactive authorization prompt.
 *
 * Use this method when the Application Default Credential is not sufficient.
 *
 * @param clientSecretsFile The {@code client_secrets.json} file path.
 * @param credentialId The credentialId for use in identifying the credential in the persistent credential store.
 * @return The user credential/*from   ww w  .jav a 2  s.  c  o  m*/
 */
public static Credential getCredentialFromClientSecrets(String clientSecretsFile, String credentialId) {
    Preconditions.checkArgument(clientSecretsFile != null);
    Preconditions.checkArgument(credentialId != null);

    HttpTransport httpTransport;
    try {
        httpTransport = GoogleNetHttpTransport.newTrustedTransport();
    } catch (IOException | GeneralSecurityException e) {
        throw new RuntimeException("Could not create HTTPS transport for use in credential creation", e);
    }

    JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
    GoogleClientSecrets clientSecrets;

    try {
        clientSecrets = GoogleClientSecrets.load(jsonFactory, new FileReader(clientSecretsFile));
    } catch (IOException e) {
        throw new RuntimeException("Could not read the client secrets from file: " + clientSecretsFile, e);
    }

    FileDataStoreFactory dataStoreFactory;
    try {
        dataStoreFactory = new FileDataStoreFactory(CREDENTIAL_STORE);
    } catch (IOException e) {
        throw new RuntimeException("Could not create persisten credential store " + CREDENTIAL_STORE, e);
    }

    GoogleAuthorizationCodeFlow flow;
    try {
        flow = new GoogleAuthorizationCodeFlow.Builder(httpTransport, jsonFactory, clientSecrets, SCOPES)
                .setDataStoreFactory(dataStoreFactory).build();
    } catch (IOException e) {
        throw new RuntimeException("Could not build credential authorization flow", e);
    }

    // The credentialId identifies the credential in the persistent credential store.
    Credential credential;
    try {
        credential = new AuthorizationCodeInstalledApp(flow, new PromptReceiver()).authorize(credentialId);
    } catch (IOException e) {
        throw new RuntimeException("Could not perform credential authorization flow", e);
    }
    return credential;
}

From source file:com.google.cloud.trace.sdk.InstalledAppCredentialProvider.java

License:Open Source License

@Override
public Credential getCredential(List<String> scopes) throws CloudTraceException {
    if (clientSecretsFile == null) {
        throw new IllegalStateException("Client-secrets file is required");
    }//from  w ww  .jav  a 2  s .  c  o  m

    JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
    GoogleClientSecrets clientSecrets;
    try {
        clientSecrets = GoogleClientSecrets.load(jsonFactory, new FileReader(clientSecretsFile));
        GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(httpTransport, jsonFactory,
                clientSecrets, scopes).setDataStoreFactory(dataStoreFactory).build();
        return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
    } catch (IOException e) {
        throw new CloudTraceException("Exception getting oauth2 credential", e);
    }
}