Java Code Examples for com.google.api.client.googleapis.auth.oauth2.GoogleCredential#createScoped()

The following examples show how to use com.google.api.client.googleapis.auth.oauth2.GoogleCredential#createScoped() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AuthModule.java    From nomulus with Apache License 2.0 6 votes vote down vote up
@Provides
@CloudSqlClientCredential
public static Credential providesLocalCredentialForCloudSqlClient(
    @LocalCredentialJson String credentialJson,
    @Config("localCredentialOauthScopes") ImmutableList<String> credentialScopes) {
  try {
    GoogleCredential credential =
        GoogleCredential.fromStream(new ByteArrayInputStream(credentialJson.getBytes(UTF_8)));
    if (credential.createScopedRequired()) {
      credential = credential.createScoped(credentialScopes);
    }
    return credential;
  } catch (IOException e) {
    throw new UncheckedIOException(
        "Error occurred while creating a GoogleCredential for Cloud SQL client", e);
  }
}
 
Example 2
Source File: DictionarySample.java    From cloud-search-samples with Apache License 2.0 6 votes vote down vote up
/**
 * Builds and initializes the client with service account credentials.
 *
 * @return CloudSearch instance
 * @throws IOException if unable to read credentials
 */
private CloudSearch buildAuthorizedClient() throws IOException {
  // Get the service account credentials based on the GOOGLE_APPLICATION_CREDENTIALS
  // environment variable
  GoogleCredential credential = GoogleCredential.getApplicationDefault(
      Utils.getDefaultTransport(),
      Utils.getDefaultJsonFactory());
  // Ensure credentials have the correct scope
  if (credential.createScopedRequired()) {
    credential = credential.createScoped(Collections.singletonList(
        "https://www.googleapis.com/auth/cloud_search"
    ));
  }
  // Build the cloud search client
  return new CloudSearch.Builder(
      Utils.getDefaultTransport(),
      Utils.getDefaultJsonFactory(),
      credential)
      .setApplicationName("Cloud Search Samples")
      .build();
}
 
Example 3
Source File: SchemaSample.java    From cloud-search-samples with Apache License 2.0 6 votes vote down vote up
/**
 * Builds and initializes the client with service account credentials.
 * @return CloudSearch instance
 * @throws IOException if unable to load credentials
 */
private CloudSearch buildAuthorizedClient() throws IOException {
  // Get the service account credentials based on the GOOGLE_APPLICATION_CREDENTIALS
  // environment variable
  GoogleCredential credential = GoogleCredential.getApplicationDefault(
      Utils.getDefaultTransport(),
      Utils.getDefaultJsonFactory());
  // Ensure credentials have the correct scope
  if (credential.createScopedRequired()) {
    credential = credential.createScoped(Collections.singletonList(
        "https://www.googleapis.com/auth/cloud_search"
    ));
  }
  // Build the cloud search client
  return new CloudSearch.Builder(
      Utils.getDefaultTransport(),
      Utils.getDefaultJsonFactory(),
      credential)
      .setApplicationName("Cloud Search Samples")
      .build();
}
 
Example 4
Source File: InjectorUtils.java    From beam with Apache License 2.0 6 votes vote down vote up
/** Builds a new Pubsub client and returns it. */
public static Pubsub getClient(final HttpTransport httpTransport, final JsonFactory jsonFactory)
    throws IOException {
  checkNotNull(httpTransport);
  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();
}
 
Example 5
Source File: InjectorUtils.java    From deployment-examples with MIT License 6 votes vote down vote up
/** Builds a new Pubsub client and returns it. */
public static Pubsub getClient(final HttpTransport httpTransport, final JsonFactory jsonFactory)
    throws IOException {
  checkNotNull(httpTransport);
  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();
}
 
Example 6
Source File: StorageHandler.java    From tech-gallery with Apache License 2.0 6 votes vote down vote up
/**
 * Method to create the service or get the service if is already created.
 *
 * @author <a href="mailto:[email protected]"> João Felipe de Medeiros Moreira </a>
 * @since 13/10/2015
 *
 * @return the Storage service already created.
 *
 * @throws IOException in case a IO problem.
 * @throws GeneralSecurityException in case a security problem.
 */
private static Storage getService() throws IOException, GeneralSecurityException {
  logger.finest("###### Getting the storage service");
  if (null == storageService) {
    HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
    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());
    }
    storageService = new Storage.Builder(httpTransport, JSON_FACTORY, credential)
        .setApplicationName(APPLICATION_NAME).build();
  }
  return storageService;
}
 
Example 7
Source File: GCPProject.java    From policyscanner with Apache License 2.0 6 votes vote down vote up
/**
 * 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.
 */
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;
}
 
Example 8
Source File: GCPServiceAccount.java    From policyscanner with Apache License 2.0 6 votes vote down vote up
/**
 * 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.
 */
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;
}
 
Example 9
Source File: GcsWaitIT.java    From digdag with Apache License 2.0 5 votes vote down vote up
private Storage gcsClient(GoogleCredential credential)
{
    if (credential.createScopedRequired()) {
        credential = credential.createScoped(StorageScopes.all());
    }
    return new Storage.Builder(transport, jsonFactory, credential)
            .setApplicationName("digdag-test")
            .build();
}
 
Example 10
Source File: BigQueryIT.java    From digdag with Apache License 2.0 5 votes vote down vote up
private Storage gcsClient(GoogleCredential credential)
{
    if (credential.createScopedRequired()) {
        credential = credential.createScoped(StorageScopes.all());
    }
    return new Storage.Builder(transport, jsonFactory, credential)
            .setApplicationName("digdag-test")
            .build();
}
 
Example 11
Source File: BigQueryInterpreter.java    From zeppelin with Apache License 2.0 5 votes vote down vote up
private static Bigquery createAuthorizedClient() throws IOException {
  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("Zeppelin/1.0 (GPN:Apache Zeppelin;)").build();
}
 
Example 12
Source File: InprocessController.java    From pubsub with Apache License 2.0 5 votes vote down vote up
/** Returns a LocalController using default application credentials. */
public static InprocessController newController(
    String projectName, List<ClientParams> clients, ScheduledExecutorService executor) {
  try {
    HttpTransport transport = GoogleNetHttpTransport.newTrustedTransport();
    JsonFactory jsonFactory = new JacksonFactory();
    GoogleCredential credential = GoogleCredential.getApplicationDefault(transport, jsonFactory);
    if (credential.createScopedRequired()) {
      credential =
          credential.createScoped(
              Collections.singletonList("https://www.googleapis.com/auth/cloud-platform"));
    }
    Pubsub pubsub =
        new Pubsub.Builder(transport, jsonFactory, credential)
            .setApplicationName("Cloud Pub/Sub Loadtest Framework")
            .build();
    ArrayList<ResourceController> controllers = new ArrayList<>();
    ArrayList<ComputeResourceController> computeControllers = new ArrayList<>();
    clients.forEach(
        params -> {
          if (params.getClientType().language != ClientType.Language.JAVA
              || params.getClientType().messaging != ClientType.MessagingType.CPS_GCLOUD) {
            throw new RuntimeException("Invalid params for Inprocess Java Controller: " + params);
          }
          ComputeResourceController computeController =
              new InprocessJavaComputeResourceController(params, executor);
          controllers.add(computeController);
          computeControllers.add(computeController);
        });
    controllers.add(
        new PubsubResourceController(
            projectName, Client.TOPIC, ImmutableList.of(Client.SUBSCRIPTION), executor, pubsub));
    return new InprocessController(clients, executor, controllers, computeControllers);
  } catch (Throwable t) {
    log.error("Unable to initialize GCE: ", t);
    return null;
  }
}
 
Example 13
Source File: BqClient.java    From digdag with Apache License 2.0 5 votes vote down vote up
@Override
protected Bigquery client(GoogleCredential credential, HttpTransport transport, JsonFactory jsonFactory)
{
    if (credential.createScopedRequired()) {
        credential = credential.createScoped(BigqueryScopes.all());
    }

    return new Bigquery.Builder(transport, jsonFactory, credential)
            .setApplicationName("Digdag")
            .build();
}
 
Example 14
Source File: GCSFilesSource.java    From policyscanner with Apache License 2.0 5 votes vote down vote up
private static Storage constructStorageApiStub() throws GeneralSecurityException, IOException {
  JsonFactory jsonFactory = new JacksonFactory();
  HttpTransport transport;
  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();
}
 
Example 15
Source File: LifecycleIT.java    From spydra with Apache License 2.0 5 votes vote down vote up
private boolean isClusterCollected(SpydraArgument arguments)
    throws IOException, GeneralSecurityException {
  GoogleCredential credential = new GcpUtils().getCredential();
  if (credential.createScopedRequired()) {
    credential =
        credential.createScoped(
            Collections.singletonList("https://www.googleapis.com/auth/cloud-platform"));
  }

  HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
  JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
  Dataproc dataprocService =
      new Dataproc.Builder(httpTransport, jsonFactory, credential)
          .setApplicationName("Google Cloud Platform Sample")
          .build();

  Dataproc.Projects.Regions.Clusters.List request =
      dataprocService.projects().regions().clusters().list(
          arguments.getCluster().getOptions().get(SpydraArgument.OPTION_PROJECT),
          arguments.getRegion());
  ListClustersResponse response;
  do {
    response = request.execute();
    if (response.getClusters() == null) continue;

    String clusterName = arguments.getCluster().getName();
    for (Cluster cluster : response.getClusters()) {
      if (cluster.getClusterName().equals(clusterName)) {
        String status = cluster.getStatus().getState();
        LOGGER.info("Cluster state is" + status);
        return status.equals("DELETING");
      }
    }

    request.setPageToken(response.getNextPageToken());
  } while (response.getNextPageToken() != null);
  return true;
}
 
Example 16
Source File: BigQueryIT.java    From digdag with Apache License 2.0 5 votes vote down vote up
private Bigquery bqClient(GoogleCredential credential)
{
    if (credential.createScopedRequired()) {
        credential = credential.createScoped(BigqueryScopes.all());
    }
    return new Bigquery.Builder(transport, jsonFactory, credential)
            .setApplicationName("digdag-test")
            .build();
}
 
Example 17
Source File: BaragonServiceModule.java    From Baragon with Apache License 2.0 5 votes vote down vote up
@Provides
@Singleton
@Named(GOOGLE_CLOUD_COMPUTE_SERVICE)
public Optional<Compute> provideComputeService(BaragonConfiguration config) throws Exception {
  if (!config.getGoogleCloudConfiguration().isEnabled()) {
    return Optional.absent();
  }
  HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
  JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();

  GoogleCredential credential = null;

  if (config.getGoogleCloudConfiguration().getGoogleCredentialsFile() != null) {
    File credentialsFile = new File(config.getGoogleCloudConfiguration().getGoogleCredentialsFile());
    credential = GoogleCredential.fromStream(
        new FileInputStream(credentialsFile)
    );
  } else if (config.getGoogleCloudConfiguration().getGoogleCredentials() != null) {
    credential = GoogleCredential.fromStream(
        new ByteArrayInputStream(config.getGoogleCloudConfiguration().getGoogleCredentials().getBytes("UTF-8"))
    );
  } else {
    throw new RuntimeException("Must specify googleCloudCredentials or googleCloudCredentialsFile when using google cloud api");
  }

  if (credential.createScopedRequired()) {
    credential =
        credential.createScoped(Collections.singletonList("https://www.googleapis.com/auth/cloud-platform"));
  }

  return Optional.of(new Compute.Builder(httpTransport, jsonFactory, credential)
      .setApplicationName("BaragonService")
      .build());
}
 
Example 18
Source File: Utils.java    From cloud-search-samples with Apache License 2.0 5 votes vote down vote up
static CloudIdentity buildCloudIdentityService()
    throws IOException, GeneralSecurityException {
  GoogleCredential credential = GoogleCredential.getApplicationDefault();
  if (credential.createScopedRequired()) {
    credential = credential.createScoped(Collections.singletonList(
        "https://www.googleapis.com/auth/cloud-identity.groups"
    ));
  }
  return new CloudIdentity.Builder(GoogleNetHttpTransport.newTrustedTransport(),
          JacksonFactory.getDefaultInstance(),
          credential)
      .setApplicationName("Cloud identity samples")
      .build();
}
 
Example 19
Source File: KMSFactory.java    From dlp-dataflow-deidentification with Apache License 2.0 4 votes vote down vote up
private static CloudKMS buildService() throws IOException, GeneralSecurityException {
  HttpTransport transport = GoogleNetHttpTransport.newTrustedTransport();
  JsonFactory jsonFactory = new JacksonFactory();
  GoogleCredential credential = GoogleCredential.getApplicationDefault(transport, jsonFactory);

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

  return new CloudKMS.Builder(transport, jsonFactory, credential)
      .setApplicationName("Cloud KMS ")
      .build();
}
 
Example 20
Source File: Pubsub.java    From async-google-pubsub-client with Apache License 2.0 4 votes vote down vote up
private Credential scoped(final GoogleCredential credential) {
  if (credential.createScopedRequired()) {
    return credential.createScoped(SCOPES);
  }
  return credential;
}