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:ComputeEngineSample.java

License:Open Source License

public static void main(String[] args) {
    try {//  w  ww . j av  a 2  s  .co m
        httpTransport = GoogleNetHttpTransport.newTrustedTransport();

        // Authenticate using Google Application Default Credentials.
        GoogleCredential credential = GoogleCredential.getApplicationDefault();
        if (credential.createScopedRequired()) {
            List<String> scopes = new ArrayList<>();
            // Set Google Cloud Storage scope to Full Control.
            scopes.add(ComputeScopes.DEVSTORAGE_FULL_CONTROL);
            // Set Google Compute Engine scope to Read-write.
            scopes.add(ComputeScopes.COMPUTE);
            credential = credential.createScoped(scopes);
        }

        // Create Compute Engine object for listing instances.
        Compute compute = new Compute.Builder(httpTransport, JSON_FACTORY, credential)
                .setApplicationName(APPLICATION_NAME).build();

        // List out instances, looking for the one created by this sample app.
        boolean foundOurInstance = printInstances(compute);

        Operation op;
        if (foundOurInstance) {
            op = deleteInstance(compute, SAMPLE_INSTANCE_NAME);
        } else {
            op = startInstance(compute, SAMPLE_INSTANCE_NAME);
        }

        // Call Compute Engine API operation and poll for operation completion status
        System.out.println("Waiting for operation completion...");
        Operation.Error error = blockUntilComplete(compute, op, OPERATION_TIMEOUT_MILLIS);
        if (error == null) {
            System.out.println("Success!");
        } else {
            System.out.println(error.toPrettyString());
        }
    } catch (IOException e) {
        System.err.println(e.getMessage());
    } catch (Throwable t) {
        t.printStackTrace();
    }
    System.exit(1);
}

From source file:ListLogs.java

License:Apache License

/**
 * Returns an authorized Cloud Logging API service client that is usable
 * on Google App Engine, Google Compute Engine, workstations with the Google Cloud SDK,
 * and other computers if you install service account private credentials.
 * See https://cloud.google.com/logging/docs/api/tasks.
 *//*from  w w w  .ja v a2 s  . c o m*/
// [START auth]
public static Logging getLoggingService() throws IOException {
    HttpTransport transport = new NetHttpTransport();
    JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
    GoogleCredential credential = GoogleCredential.getApplicationDefault(transport, jsonFactory);
    if (credential.createScopedRequired()) {
        credential = credential.createScoped(LOGGING_SCOPES);
    }
    Logging service = new Logging.Builder(transport, jsonFactory, credential)
            .setApplicationName(APPLICATION_NAME).build();
    return service;
}

From source file:StorageFactory.java

License:Open Source License

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

    // Depending on the environment that provides the default credentials (for
    // example: 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()) {
        Collection<String> scopes = StorageScopes.all();
        credential = credential.createScoped(scopes);
    }//from   ww  w .  j  a  va  2  s  . c  o m

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

From source file:TaskQueueSample.java

License:Open Source License

private static void run() throws Exception {
    httpTransport = GoogleNetHttpTransport.newTrustedTransport();
    // [START auth_and_intitalize_client]
    // Authenticate using Google Application Default Credentials.
    GoogleCredential credential = GoogleCredential.getApplicationDefault();
    if (credential.createScopedRequired()) {
        List<String> scopes = new ArrayList<>();
        // Set TaskQueue Scopes
        scopes.add(TaskqueueScopes.TASKQUEUE);
        scopes.add(TaskqueueScopes.TASKQUEUE_CONSUMER);
        credential = credential.createScoped(scopes);
    }//from  w  w  w. j  a  v  a  2s.c om
    // Intialize Taskqueue object.
    Taskqueue taskQueue = new Taskqueue.Builder(httpTransport, JSON_FACTORY, credential)
            .setApplicationName(APPLICATION_NAME).build();
    // [END auth_and_intitalize_client]

    /* Get the task queue using the name of an existing task queue
    *  listed in the App Engine Task Queue section of the Developers console.
    *  See the following sample for an example App Engine app that creates a
    *  pull task queue:
    *  https://github.com/GoogleCloudPlatform/java-docs-samples/tree/master/appengine/taskqueue
    */
    com.google.api.services.taskqueue.model.TaskQueue queue = getQueue(taskQueue);
    System.out.println("================== Listing Task Queue details ==================");
    System.out.println(queue);
    // Lease, process and delete tasks
    // [START lease_tasks]
    Tasks tasks = getLeasedTasks(taskQueue);
    if (tasks.getItems() == null || tasks.getItems().size() == 0) {
        System.out.println("No tasks to lease, so now exiting");
    } else {
        for (Task leasedTask : tasks.getItems()) {
            processTask(leasedTask);
            deleteTask(taskQueue, leasedTask);
        }
    }
    // [END lease_tasks]
}

From source file:bqutils.BigQueryServiceFactory.java

License:Apache License

/**
 * Creates an authorized client to Google BigQuery.
 *
 * @return The BigQuery Service//w  w  w  .j a  v a2  s .  co m
 * @throws IOException Thrown if there is an error connecting
 */
// [START get_service]
private 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()) {
        Collection<String> bigqueryScopes = BigqueryScopes.all();
        credential = credential.createScoped(bigqueryScopes);
    }

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

From source file:br.unb.cic.bionimbuz.controller.elasticitycontroller.GoogleAPI.java

@Override
public void createinstance(String type, String instanceName) throws IOException {
    System.out.println("================== Setup ==================");
    try {/*from  w  w  w  .ja v  a  2 s .com*/
        httpTransport = GoogleNetHttpTransport.newTrustedTransport();

        // Authenticate using Google Application Default Credentials.
        //GoogleCredential credential = GoogleCredential.getApplicationDefault();
        GoogleCredential credential;

        //InputStream auth = new ByteArrayInputStream(authpath.getBytes(StandardCharsets.UTF_8));
        InputStream is = null;
        is = new FileInputStream(SystemConstants.FILE_CREDENTIALS_GOOGLE);

        credential = GoogleCredential.fromStream(is, httpTransport, JSON_FACTORY);

        if (credential.createScopedRequired()) {
            List<String> scopes = new ArrayList();
            // Set Google Clo  ud Storage scope to Full Control.
            scopes.add(ComputeScopes.DEVSTORAGE_FULL_CONTROL);
            // Set Google Compute Engine scope to Read-write.
            scopes.add(ComputeScopes.COMPUTE);
            credential = credential.createScoped(scopes);
        }

        // Create Compute Engine object for listing instances.
        Compute compute = new Compute.Builder(httpTransport, JSON_FACTORY, credential)
                .setApplicationName(APPLICATION_NAME).build();

        System.out.println("================== Starting New Instance ==================");

        // Create VM Instance object with the required properties.
        com.google.api.services.compute.model.Instance instance = new com.google.api.services.compute.model.Instance();
        instance.setName(instanceName);
        instance.setMachineType("https://www.googleapis.com/compute/v1/projects/" + PROJECT_ID + "/zones/"
                + ZONE_NAME + "/machineTypes/" + type);

        // Add Network Interface to be used by VM Instance.
        NetworkInterface ifc = new NetworkInterface();
        ifc.setNetwork(
                "https://www.googleapis.com/compute/v1/projects/" + PROJECT_ID + "/global/networks/default");
        List<AccessConfig> configs = new ArrayList();
        AccessConfig config = new AccessConfig();
        config.setType(NETWORK_INTERFACE_CONFIG);
        config.setName(NETWORK_ACCESS_CONFIG);
        configs.add(config);
        ifc.setAccessConfigs(configs);
        instance.setNetworkInterfaces(Collections.singletonList(ifc));
        //get Internal ip, do a method that set it

        // Add attached Persistent Disk to be used by VM Instance.
        AttachedDisk disk = new AttachedDisk();
        disk.setBoot(true);
        disk.setAutoDelete(true);
        disk.setType("PERSISTENT");
        AttachedDiskInitializeParams params = new AttachedDiskInitializeParams();
        // Assign the Persistent Disk the same name as the VM Instance.
        params.setDiskName(instanceName);
        // Specify the source operating system machine image to be used by the VM Instance.
        params.setSourceImage(SOURCE_IMAGE_PREFIX + SOURCE_IMAGE_PATH);
        // Specify the disk type as Standard Persistent Disk
        params.setDiskType("https://www.googleapis.com/compute/v1/projects/" + PROJECT_ID + "/zones/"
                + ZONE_NAME + "/diskTypes/pd-standard");
        disk.setInitializeParams(params);
        instance.setDisks(Collections.singletonList(disk));

        // Initialize the service account to be used by the VM Instance and set the API access scopes.
        ServiceAccount account = new ServiceAccount();
        account.setEmail("default");
        List<String> scopes = new ArrayList();
        scopes.add("https://www.googleapis.com/auth/devstorage.full_control");
        scopes.add("https://www.googleapis.com/auth/compute");
        account.setScopes(scopes);
        instance.setServiceAccounts(Collections.singletonList(account));

        // Optional - Add a startup script to be used by the VM Instance.
        Metadata meta = new Metadata();
        Metadata.Items item = new Metadata.Items();
        item.setKey("startup-script-url");
        // If you put a script called "vm-startup.sh" in this Google Cloud Storage bucket, it will execute on VM startup.
        // This assumes you've created a bucket named the same as your PROJECT_ID
        // For info on creating buckets see: https://cloud.google.com/storage/docs/cloud-console#_creatingbuckets
        item.setValue("gs://" + PROJECT_ID + "/vm-startup.sh");
        meta.setItems(Collections.singletonList(item));
        instance.setMetadata(meta);

        System.out.println(instance.toPrettyString());
        Compute.Instances.Insert insert = compute.instances().insert(PROJECT_ID, ZONE_NAME, instance);
        insert.execute();

        try {
            Thread.sleep(15000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println("OK");

        String instanceCreatedName = instance.getName();
        System.out.println(instanceCreatedName);
        Compute.Instances.Get get = compute.instances().get(PROJECT_ID, ZONE_NAME, instanceCreatedName);
        Instance instanceCreated = get.execute();
        setIpInstance(instanceCreated.getNetworkInterfaces().get(0).getAccessConfigs().get(0).getNatIP());

    } catch (GeneralSecurityException ex) {
        Logger.getLogger(GoogleAPI.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:br.unb.cic.bionimbuz.elasticity.legacy.FULLGoogleAPI.java

License:Apache License

public static void main(String[] args) {
    try {/*from  w  w w .  j  a  v  a 2  s .co  m*/
        httpTransport = GoogleNetHttpTransport.newTrustedTransport();

        // Authenticate using Google Application Default Credentials.
        //GoogleCredential credential = GoogleCredential.getApplicationDefault();
        GoogleCredential credential;

        //InputStream auth = new ByteArrayInputStream(authpath.getBytes(StandardCharsets.UTF_8));

        InputStream is = null;
        is = new FileInputStream(authpath);

        credential = GoogleCredential.fromStream(is, httpTransport, JSON_FACTORY);

        if (credential.createScopedRequired()) {
            List<String> scopes = new ArrayList();
            // Set Google Clo  ud Storage scope to Full Control.
            scopes.add(ComputeScopes.DEVSTORAGE_FULL_CONTROL);
            // Set Google Compute Engine scope to Read-write.
            scopes.add(ComputeScopes.COMPUTE);
            credential = credential.createScoped(scopes);
        }

        // Create Compute Engine object for listing instances.
        Compute compute = new Compute.Builder(httpTransport, JSON_FACTORY, credential)
                .setApplicationName(APPLICATION_NAME).build();

        // List out instances, looking for the one created by this sample app.
        boolean foundOurInstance = printInstances(compute);

        Operation op;
        if (foundOurInstance) {
            op = deleteInstance(compute, SAMPLE_INSTANCE_NAME);
        } else {
            op = startInstance(compute, SAMPLE_INSTANCE_NAME);
        }

        // Call Compute Engine API operation and poll for operation completion status
        System.out.println("Waiting for operation completion...");
        Operation.Error error = blockUntilComplete(compute, op, OPERATION_TIMEOUT_MILLIS);
        if (error == null) {
            System.out.println("Success!");
        } else {
            System.out.println(error.toPrettyString());
        }
    } catch (IOException e) {
        System.err.println(e.getMessage());
    } catch (Throwable t) {
        t.printStackTrace();
    }
    System.exit(1);
}

From source file:com.appengine.pubsub.HelloAppEngine.java

License:Open Source License

public void initialize() throws Exception {
    System.out.println("Initialize the Google APIs Client Library client");
    log.info("Initialize the Google APIs Client Library client with logger");

    // build the transport
    NetHttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
    JacksonFactory jsonFactory = JacksonFactory.getDefaultInstance();

    // get the credentials
    List<String> scopeList = Arrays.asList(ALL_SCOPES);
    GoogleCredential credential = GoogleCredential.getApplicationDefault();
    if (credential.createScopedRequired()) {
        credential = credential.createScoped(scopeList);
    }/*from w w  w  .jav a2 s.  c  om*/

    // create the client stub
    this.client = new Pubsub.Builder(httpTransport, jsonFactory, credential)
            .setApplicationName(APPLICATION_NAME).build();
}

From source file:com.appsflyer.spark.bigquery.BigQueryServiceFactory.java

License:Apache License

/**
 * Creates an authorized client to Google BigQuery.
 *
 * @return The BigQuery Service/*from w w  w  . j av a  2  s.  c  om*/
 * @throws IOException Thrown if there is an error connecting
 */
private 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()) {
        Collection<String> bigqueryScopes = BigqueryScopes.all();
        credential = credential.createScoped(bigqueryScopes);
    }

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

From source file:com.bucketoperations.controller.StorageFactory.java

License:Open Source License

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

    // Depending on the environment that provides the default credentials (for
    // example: 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()) {
        Collection<String> scopes = StorageScopes.all();
        credential = credential.createScoped(scopes);
    }//  w  w  w .  j a  va2  s . co  m

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