Example usage for com.google.api.client.googleapis.auth.oauth2 GoogleCredential createScoped

List of usage examples for com.google.api.client.googleapis.auth.oauth2 GoogleCredential createScoped

Introduction

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

Prototype

@Beta
public GoogleCredential createScoped(Collection<String> scopes) 

Source Link

Document

Beta
For credentials that require scopes, creates a copy of the credential with the specified scopes.

Usage

From source file:com.google.cloud.dataflow.samples.daily_precipitation_sample.ReadDataWithFileName.java

License:Apache License

/**
 * Get all precipitation files in a specified bucket within the specified date range.
 * @return A set of fully qualified file names for all precipitation data files.
 * All names are in the format "gs://sub/dir/.../precip_YYYYMMDD.json"
 */// ww  w .  j  av a2  s  . c  om
private static HashSet<String> getPrecipitationFiles(String project, String bucket, String startDate,
        String endDate) {
    HashSet<String> files = new HashSet<>();

    // Prevents duplicate data files for the same date.
    HashSet<String> visitedFiles = new HashSet<>();

    try {
        HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
        GoogleCredential credential = GoogleCredential.getApplicationDefault();

        Collection<String> bigqueryScopes = BigqueryScopes.all();
        if (credential.createScopedRequired()) {
            credential = credential.createScoped(bigqueryScopes);
        }

        Storage client = new Storage.Builder(httpTransport, JSON_FACTORY, credential)
                .setApplicationName(project).build();

        // Get the contents of the bucket.
        Storage.Objects.List listObjects = client.objects().list(bucket);
        com.google.api.services.storage.model.Objects objects;
        do {
            objects = listObjects.execute();
            List<StorageObject> items = objects.getItems();
            if (items == null) {
                break;
            }
            for (StorageObject object : items) {
                String fileName = PathUtil.basename(object.getName());
                if (matchesFileTemplate(fileName) && isInRange(fileName, startDate, endDate)
                        && !visitedFiles.contains(fileName)) {
                    visitedFiles.add(fileName);
                    files.add("gs://" + PathUtil.join(bucket, object.getName()));
                }
            }
            listObjects.setPageToken(objects.getNextPageToken());
        } while (objects.getNextPageToken() != null);

    } catch (IOException | GeneralSecurityException e) {
        throw new RuntimeException("Exception while constructing ReadDataWithFileName reader.", e);
    }

    return files;
}

From source file:com.google.cloud.dataflow.tutorials.game.injector.InjectorUtils.java

License:Apache License

/** Builds a new Pubsub client and returns it. */
public static Pubsub getClient(final HttpTransport httpTransport, final JsonFactory jsonFactory)
        throws IOException {
    checkNotNull(httpTransport);//from   www .  java 2 s .  c  o m
    checkNotNull(jsonFactory);
    GoogleCredential credential = GoogleCredential.getApplicationDefault(httpTransport, jsonFactory);
    if (credential.createScopedRequired()) {
        credential = credential.createScoped(PubsubScopes.all());
    }
    if (credential.getClientAuthentication() != null) {
        System.out.println("\n***Warning! You are not using service account credentials to "
                + "authenticate.\nYou need to use service account credentials for this example,"
                + "\nsince user-level credentials do not have enough pubsub quota,\nand so you will run "
                + "out of PubSub quota very quickly.\nSee "
                + "https://developers.google.com/identity/protocols/application-default-credentials.");
        System.exit(1);
    }
    HttpRequestInitializer initializer = new RetryHttpInitializerWrapper(credential);
    return new Pubsub.Builder(httpTransport, jsonFactory, initializer).setApplicationName(APP_NAME).build();
}

From source file:com.google.cloud.genomics.cba.StorageFactory.java

License:Apache License

private static Storage buildService() throws IOException, GeneralSecurityException {
    HttpTransport transport = GoogleNetHttpTransport.newTrustedTransport();
    JsonFactory jsonFactory = new JacksonFactory();
    GoogleCredential credential = GoogleCredential.getApplicationDefault(transport, jsonFactory);

    if (credential.createScopedRequired()) {
        Collection<String> scopes = StorageScopes.all();
        credential = credential.createScoped(scopes);
    }/*from   w  w  w. j  a v a  2 s.c  o  m*/

    return new Storage.Builder(transport, jsonFactory, credential).setApplicationName("AnnotationHive").build();
}

From source file:com.google.cloud.pubsub.client.demos.appengine.util.PubsubUtils.java

License:Apache License

/**
 * Builds a new Pubsub client and returns it.
 *
 * @param httpTransport HttpTransport for Pubsub client.
 * @param jsonFactory JsonFactory for Pubsub client.
 * @return Pubsub client.//from  ww  w . j ava  2  s.com
 * @throws IOException when we can not get the default credentials.
 */
public static Pubsub getClient(final HttpTransport httpTransport, final JsonFactory jsonFactory)
        throws IOException {
    Preconditions.checkNotNull(httpTransport);
    Preconditions.checkNotNull(jsonFactory);
    GoogleCredential credential = GoogleCredential.getApplicationDefault();
    if (credential.createScopedRequired()) {
        credential = credential.createScoped(PubsubScopes.all());
    }
    // Please use custom HttpRequestInitializer for automatic
    // retry upon failures.
    HttpRequestInitializer initializer = new RetryHttpInitializerWrapper(credential);
    return new Pubsub.Builder(httpTransport, jsonFactory, initializer).setApplicationName(APPLICATION_NAME)
            .build();
}

From source file:com.google.cloud.pubsub.proxy.gcloud.GcloudPubsub.java

License:Open Source License

/**
 * Constructor that will automatically instantiate a Google Cloud Pub/Sub instance.
 *
 * @throws IOException when the initialization of the Google Cloud Pub/Sub client fails.
 *//*  w  w  w .jav  a 2 s .c  o  m*/
public GcloudPubsub() throws IOException {
    if (CLOUD_PUBSUB_PROJECT_ID == null) {
        throw new IllegalStateException(GCLOUD_PUBSUB_PROJECT_ID_NOT_SET_ERROR);
    }
    try {
        serverName = InetAddress.getLocalHost().getCanonicalHostName();
    } catch (UnknownHostException e) {
        throw new IllegalStateException("Unable to retrieve the hostname of the system");
    }
    HttpTransport httpTransport = checkNotNull(Utils.getDefaultTransport());
    JsonFactory jsonFactory = checkNotNull(Utils.getDefaultJsonFactory());
    GoogleCredential credential = GoogleCredential.getApplicationDefault(httpTransport, jsonFactory);
    if (credential.createScopedRequired()) {
        credential = credential.createScoped(PubsubScopes.all());
    }
    HttpRequestInitializer initializer = new RetryHttpInitializerWrapper(credential);
    pubsub = new Pubsub.Builder(httpTransport, jsonFactory, initializer).build();
    logger.info("Google Cloud Pub/Sub Initialization SUCCESS");
}

From source file:com.google.cloud.security.scanner.primitives.GCPProject.java

License:Apache License

/**
 * Return the Projects api object used for accessing the Cloud Resource Manager Projects API.
 * @return Projects api object used for accessing the Cloud Resource Manager Projects API
 * @throws GeneralSecurityException Thrown if there's a permissions error.
 * @throws IOException Thrown if there's an IO error initializing the API object.
 *//* www .  j ava  2 s.  com*/
public static synchronized Projects getProjectsApiStub() throws GeneralSecurityException, IOException {
    if (projectApiStub != null) {
        return projectApiStub;
    }
    HttpTransport transport;
    GoogleCredential credential;
    JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
    transport = GoogleNetHttpTransport.newTrustedTransport();
    credential = GoogleCredential.getApplicationDefault(transport, jsonFactory);
    if (credential.createScopedRequired()) {
        Collection<String> scopes = CloudResourceManagerScopes.all();
        credential = credential.createScoped(scopes);
    }
    projectApiStub = new CloudResourceManager.Builder(transport, jsonFactory, credential).build().projects();
    return projectApiStub;
}

From source file:com.google.cloud.security.scanner.primitives.GCPServiceAccount.java

License:Apache License

/**
 * Get the API stub for accessing the IAM Service Accounts API.
 * @return ServiceAccounts api stub for accessing the IAM Service Accounts API.
 * @throws IOException Thrown if there's an IO error initializing the api connection.
 * @throws GeneralSecurityException Thrown if there's a security error
 * initializing the connection./*www.ja v a  2  s .  c om*/
 */
public static ServiceAccounts getServiceAccountsApiStub() throws IOException, GeneralSecurityException {
    if (serviceAccountsApiStub == null) {
        HttpTransport transport;
        GoogleCredential credential;
        JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
        transport = GoogleNetHttpTransport.newTrustedTransport();
        credential = GoogleCredential.getApplicationDefault(transport, jsonFactory);
        if (credential.createScopedRequired()) {
            Collection<String> scopes = IamScopes.all();
            credential = credential.createScoped(scopes);
        }
        serviceAccountsApiStub = new Iam.Builder(transport, jsonFactory, credential).build().projects()
                .serviceAccounts();
    }
    return serviceAccountsApiStub;
}

From source file:com.google.cloud.security.scanner.sources.GCSFilesSource.java

License:Apache License

private static Storage constructStorageApiStub() throws GeneralSecurityException, IOException {
    JsonFactory jsonFactory = new JacksonFactory();
    HttpTransport transport;/*from   w  w w.j av a2  s  . co  m*/
    transport = GoogleNetHttpTransport.newTrustedTransport();
    GoogleCredential credential = GoogleCredential.getApplicationDefault(transport, jsonFactory);
    if (credential.createScopedRequired()) {
        Collection<String> scopes = StorageScopes.all();
        credential = credential.createScoped(scopes);
    }
    return new Storage.Builder(transport, jsonFactory, credential).setApplicationName("GCS Samples").build();
}

From source file:com.google.cloud.servicebroker.awwvision.VisionConfig.java

License:Open Source License

@Bean
Vision vision(HttpTransport transport, JsonFactory jsonFactory, GoogleCredential credential) {
    if (credential.createScopedRequired()) {
        credential = credential.createScoped(VisionScopes.all());
    }/*from w w w.ja v a2  s .co  m*/
    return new Vision.Builder(transport, jsonFactory, credential).setApplicationName(applicationName).build();
}

From source file:com.google.cloud.servicebroker.awwvision.VisionConfig.java

License:Open Source License

@Bean
Storage storage(HttpTransport transport, JsonFactory jsonFactory, GoogleCredential credential) {
    if (credential.createScopedRequired()) {
        credential = credential.createScoped(StorageScopes.all());
    }//from   w  w w  .j ava  2  s.  c o m
    return new Storage.Builder(transport, jsonFactory, credential).setApplicationName(applicationName).build();
}