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

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

Introduction

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

Prototype

@Beta
public static GoogleCredential getApplicationDefault(HttpTransport transport, JsonFactory jsonFactory)
        throws IOException 

Source Link

Document

Beta
Returns the Application Default Credentials.

Usage

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.
 *///from  www . j  av  a 2 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.dataflow.examples.complete.game.injector.InjectorUtils.java

License:Apache License

/**
 * Builds a new Pubsub client and returns it.
 *///from w  w w .j  a va2  s .  c om
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.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   w  w  w . j ava  2s  .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);
    }// w  w w. ja v  a2s. c om

    return new Storage.Builder(transport, jsonFactory, credential).setApplicationName("AnnotationHive").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 ww . j av a  2  s.co  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.
 *///from w ww  . j a  v a2  s.c o m
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./*from w  w  w .  j a v a  2 s .c  o m*/
 */
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 ww.  ja v  a2s. c  om
    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.solutions.rtdp.Converter.java

License:Apache License

/** Starts the DataFlow convertor. */
public void startConverter(RtdpOptions options) throws IOException {
    final String projectId = options.getProject();
    final String topic = options.getTopic();
    final String datasetId = "iotds";
    final String tableName = "temp_sensor";

    String id = Long.toString(System.currentTimeMillis());
    options.setJobName("converter-" + id);

    GoogleCredential credential = GoogleCredential.getApplicationDefault(TRANSPORT, JSON_FACTORY);
    Bigquery bigquery = new Bigquery(new NetHttpTransport(), new JacksonFactory(), credential);
    Dataset dataset = new Dataset();
    DatasetReference datasetRef = new DatasetReference();
    datasetRef.setProjectId(projectId);/*w  w  w  .  j ava  2s .co  m*/
    datasetRef.setDatasetId(datasetId);
    dataset.setDatasetReference(datasetRef);
    try {
        bigquery.datasets().insert(projectId, dataset).execute();
        LOG.debug("Creating dataset : " + datasetId);
    } catch (IOException e) {
        LOG.debug(datasetId + " dataset already exists.");
    }

    TableReference ref = new TableReference();
    ref.setProjectId(projectId);
    ref.setDatasetId(datasetId);
    ref.setTableId(tableName);

    List<TableFieldSchema> fields = new ArrayList<TableFieldSchema>();
    fields.add(new TableFieldSchema().setName("deviceid").setType("STRING"));
    fields.add(new TableFieldSchema().setName("dt").setType("DATETIME"));
    fields.add(new TableFieldSchema().setName("temp").setType("FLOAT"));
    fields.add(new TableFieldSchema().setName("lat").setType("STRING"));
    fields.add(new TableFieldSchema().setName("lng").setType("STRING"));
    TableSchema schema = new TableSchema().setFields(fields);

    Pipeline p = Pipeline.create(options);
    p.apply(PubsubIO.readStrings().fromTopic("projects/" + options.getProject() + "/topics/" + topic))
            .apply(Window.<String>into(FixedWindows.of(Duration.standardSeconds(10))))
            .apply(ParDo.of(new RowGenerator()))
            .apply(BigQueryIO.writeTableRows().to(ref).withSchema(schema)
                    .withFailedInsertRetryPolicy(InsertRetryPolicy.alwaysRetry())
                    .withCreateDisposition(BigQueryIO.Write.CreateDisposition.CREATE_IF_NEEDED)
                    .withWriteDisposition(BigQueryIO.Write.WriteDisposition.WRITE_APPEND));
    p.run();
}

From source file:com.google.cloud.sparkdemo.BigqueryWriter.java

License:Apache License

private Bigquery createAuthorizedClient() {
    try {//from w ww  .j a  v a 2  s  .c om
        // Create the credential
        HttpTransport transport = new NetHttpTransport();
        JsonFactory jsonFactory = new JacksonFactory();
        GoogleCredential credential = GoogleCredential.getApplicationDefault(transport, jsonFactory);

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

        return new Bigquery.Builder(transport, jsonFactory, credential)
                .setApplicationName("Spark Gaming Samples").build();
    } catch (IOException e) {
        // can not create bigquery client
        e.printStackTrace();
        return null;
    }
}