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

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

Introduction

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

Prototype

@Beta
public boolean createScopedRequired() 

Source Link

Document

Beta
Indicates whether the credential requires scopes to be specified by calling createScoped before use.

Usage

From source file:com.dataartisans.flink.dataflow.util.PortableConfiguration.java

License:Apache License

public static Pubsub createPubsubClient(HttpTransport httpTransport, JsonFactory jsonFactory)
        throws IOException {
    Preconditions.checkNotNull(httpTransport);
    Preconditions.checkNotNull(jsonFactory);
    GoogleCredential credential = GoogleCredential.getApplicationDefault(httpTransport, jsonFactory);
    // In some cases, you need to add the scope explicitly.
    if (credential.createScopedRequired()) {
        credential = credential.createScoped(PubsubScopes.all());
    }/*from ww  w. j  ava  2 s . com*/
    // Please use custom HttpRequestInitializer for automatic
    // retry upon failures.  We provide a simple reference
    // implementation in the "Retry Handling" section.
    HttpRequestInitializer initializer = new RetryHttpInitializerWrapper(credential);
    return new Pubsub.Builder(httpTransport, jsonFactory, initializer).build();
}

From source file:com.example.CryptFile.java

License:Apache License

/**
 * Creates an authorized CloudKMS client service using Application Default Credentials.
 *
 * @return an authorized CloudKMS client
 * @throws IOException if there's an error getting the default credentials.
 *//* w  w  w .  ja v  a 2  s  .co  m*/
public static CloudKMS createAuthorizedClient() throws IOException {
    // Create the credential
    HttpTransport transport = new NetHttpTransport();
    JsonFactory jsonFactory = new JacksonFactory();
    // Authorize the client using Application Default Credentials
    // @see https://g.co/dv/identity/protocols/application-default-credentials
    GoogleCredential credential = GoogleCredential.getApplicationDefault(transport, jsonFactory);

    // Depending on the environment that provides the default credentials (e.g. Compute Engine, App
    // Engine), the credentials may require us to specify the scopes we need explicitly.
    // Check for this case, and inject the scope if required.
    if (credential.createScopedRequired()) {
        credential = credential.createScoped(CloudKMSScopes.all());
    }

    return new CloudKMS.Builder(transport, jsonFactory, credential).setApplicationName("CloudKMS CryptFile")
            .build();
}

From source file:com.example.Quickstart.java

License:Apache License

/**
 * Creates an authorized CloudKMS client service using Application Default Credentials.
 *
 * @return an authorized CloudKMS client
 * @throws IOException if there's an error getting the default credentials.
 *//*from www. j  av  a 2 s.c  o  m*/
public static CloudKMS createAuthorizedClient() throws IOException {
    // Create the credential
    HttpTransport transport = new NetHttpTransport();
    JsonFactory jsonFactory = new JacksonFactory();
    // Authorize the client using Application Default Credentials
    // @see https://g.co/dv/identity/protocols/application-default-credentials
    GoogleCredential credential = GoogleCredential.getApplicationDefault(transport, jsonFactory);

    // Depending on the environment that provides the default credentials (e.g. Compute Engine, App
    // Engine), the credentials may require us to specify the scopes we need explicitly.
    // Check for this case, and inject the scope if required.
    if (credential.createScopedRequired()) {
        credential = credential.createScoped(CloudKMSScopes.all());
    }

    return new CloudKMS.Builder(transport, jsonFactory, credential).setApplicationName("CloudKMS snippets")
            .build();
}

From source file:com.gcloud.poc.DataFlow_File2File.java

License:Apache License

private static Storage getService() throws IOException, GeneralSecurityException {
    if (null == storageService) {
        GoogleCredential credential = GoogleCredential.getApplicationDefault();
        // Depending on the environment that provides the default credentials (e.g. Compute Engine,
        // App Engine), the credentials may require us to specify the scopes we need explicitly.
        // Check for this case, and inject the Cloud Storage scope if required.
        if (credential.createScopedRequired()) {
            credential = credential.createScoped(StorageScopes.all());
        }//from  w  w  w .j a  va  2s  . co m
        HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
        storageService = new Storage.Builder(httpTransport, JSON_FACTORY, credential)
                .setApplicationName(APPLICATION_NAME).build();
    }
    return storageService;
}

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

License:Apache License

/**
 * Creates an authorized Bigquery client service using Application Default Credentials.
 *
 * @return an authorized Bigquery client
 * @throws IOException if there's an error getting the default credentials.
 *//*  ww w . j a v  a2 s.c o  m*/
public static Bigquery createAuthorizedClient() throws IOException {
    // Create the credential
    HttpTransport transport = new NetHttpTransport();
    JsonFactory jsonFactory = new JacksonFactory();
    GoogleCredential credential = GoogleCredential.getApplicationDefault(transport, jsonFactory);

    // Depending on the environment that provides the default credentials (e.g. Compute Engine, App
    // Engine), the credentials may require us to specify the scopes we need explicitly.
    // Check for this case, and inject the Bigquery scope if required.
    if (credential.createScopedRequired()) {
        credential = credential.createScoped(BigqueryScopes.all());
    }

    return new Bigquery.Builder(transport, jsonFactory, credential).setApplicationName("Bigquery Samples")
            .build();
}

From source file:com.google.cloud.crypto.tink.tinkey.TinkeyUtil.java

License:Apache License

/**
 * @return a {@code GoogleCredential}, using the service account in {@code credentialFile}.
 * If {@code credentialFile} is null, returns an
 * <a href="https://g.co/dv/identity/protocols/application-default-credentials">application
 * default credential</a>.//w ww . ja va  2  s . com
 */
public static GoogleCredential readGoogleCredential(File credentialFile) throws IOException {
    GoogleCredential cred;
    if (credentialFile != null) {
        byte[] credBytes = Files.readAllBytes(credentialFile.toPath());
        cred = GoogleCredential.fromStream(new ByteArrayInputStream(credBytes));
    } else {
        cred = GoogleCredential.getApplicationDefault();
    }
    // Depending on the environment that provides the default credentials (e.g. Compute Engine, App
    // Engine), the credentials may require us to specify the scopes we need explicitly.
    // Check for this case, and inject the scope if required.
    if (cred.createScopedRequired()) {
        cred = cred.createScoped(CloudKMSScopes.all());
    }
    return cred;
}

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

License:Apache License

/**
 * Builds a new Pubsub client and returns it.
 *//*www .  j a  v  a 2s  .c  o  m*/
public static Pubsub getClient(final HttpTransport httpTransport, final JsonFactory jsonFactory)
        throws IOException {
    Preconditions.checkNotNull(httpTransport);
    Preconditions.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.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"
 *//* w  w w.j  a  v  a2  s  . c o m*/
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  ww w  .j a  v a  2  s  . c om
    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.java 2 s. co  m*/

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