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

The following examples show how to use com.google.api.client.googleapis.auth.oauth2.GoogleCredential#getApplicationDefault() . 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: CredentialModule.java    From nomulus with Apache License 2.0 6 votes vote down vote up
/**
 * Provides the default {@link GoogleCredential} from the Google Cloud runtime for G Suite
 * Drive API.
 * TODO(b/138195359): Deprecate this credential once we figure out how to use
 * {@link GoogleCredentials} for G Suite Drive API.
 */
@GSuiteDriveCredential
@Provides
@Singleton
public static GoogleCredential provideGSuiteDriveCredential(
    @Config("defaultCredentialOauthScopes") ImmutableList<String> requiredScopes) {
  GoogleCredential credential;
  try {
    credential = GoogleCredential.getApplicationDefault();
  } catch (IOException e) {
    throw new RuntimeException(e);
  }
  if (credential.createScopedRequired()) {
    credential = credential.createScoped(requiredScopes);
  }
  return credential;
}
 
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: 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 6
Source File: PubsubUtils.java    From cloud-pubsub-samples-java with Apache License 2.0 6 votes vote down vote up
/**
 * Builds a new Pubsub client and returns it.
 *
 * @param httpTransport HttpTransport for Pubsub client.
 * @param jsonFactory JsonFactory for Pubsub client.
 * @return Pubsub client.
 * @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();
}
 
Example 7
Source File: GcpIamClientAuthenticationProvider.java    From spring-cloud-config with Apache License 2.0 6 votes vote down vote up
public static GcpCredentialSupplier getGoogleCredential(
		VaultEnvironmentProperties.GcpIamProperties gcp) {
	return () -> {

		VaultEnvironmentProperties.GcpCredentials credentialProperties = gcp
				.getCredentials();
		if (credentialProperties.getLocation() != null) {
			return GoogleCredential.fromStream(
					credentialProperties.getLocation().getInputStream());
		}

		if (StringUtils.hasText(credentialProperties.getEncodedKey())) {
			return GoogleCredential.fromStream(new ByteArrayInputStream(Base64
					.getDecoder().decode(credentialProperties.getEncodedKey())));
		}

		return GoogleCredential.getApplicationDefault();
	};
}
 
Example 8
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 9
Source File: ConfigParams.java    From kork with Apache License 2.0 6 votes vote down vote up
/** Helper function for the validator that reads our credentials for talking to Stackdriver. */
private static GoogleCredential loadCredential(
    HttpTransport transport, JsonFactory factory, String credentialsPath) throws IOException {
  final Logger log = LoggerFactory.getLogger("StackdriverWriter");

  GoogleCredential credential;
  if (credentialsPath != null && !credentialsPath.isEmpty()) {
    FileInputStream stream = new FileInputStream(credentialsPath);
    try {
      credential =
          GoogleCredential.fromStream(stream, transport, factory)
              .createScoped(Collections.singleton(MonitoringScopes.MONITORING));
      log.info("Loaded credentials from from {}", credentialsPath);
    } finally {
      stream.close();
    }
  } else {
    log.info(
        "spectator.stackdriver.monitoring.enabled without"
            + " spectator.stackdriver.credentialsPath. "
            + " Using default application credentials.");
    credential = GoogleCredential.getApplicationDefault();
  }
  return credential;
}
 
Example 10
Source File: Pubsub.java    From async-google-pubsub-client with Apache License 2.0 5 votes vote down vote up
private static Credential defaultCredential() {
  try {
    return GoogleCredential.getApplicationDefault(
        Utils.getDefaultTransport(), Utils.getDefaultJsonFactory());
  } catch (IOException e) {
    throw Throwables.propagate(e);
  }
}
 
Example 11
Source File: LocalController.java    From pubsub with Apache License 2.0 5 votes vote down vote up
/** Returns a LocalController using default application credentials. */
public static LocalController newLocalController(
    String projectName, Map<ClientParams, Integer> 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, numWorkers) -> {
          ComputeResourceController computeController =
              new LocalComputeResourceController(params, numWorkers, executor);
          controllers.add(computeController);
          computeControllers.add(computeController);
        });
    controllers.add(
        new PubsubResourceController(
            projectName, Client.TOPIC, ImmutableList.of(Client.SUBSCRIPTION), executor, pubsub));
    return new LocalController(executor, controllers, computeControllers);
  } catch (Throwable t) {
    log.error("Unable to initialize GCE: ", t);
    return null;
  }
}
 
Example 12
Source File: GoogleDirectoryUserRolesProvider.java    From fiat with Apache License 2.0 5 votes vote down vote up
private GoogleCredential getGoogleCredential() {
  try {
    if (StringUtils.isNotEmpty(config.getCredentialPath())) {
      return GoogleCredential.fromStream(new FileInputStream(config.getCredentialPath()));
    } else {
      return GoogleCredential.getApplicationDefault();
    }
  } catch (IOException ioe) {
    throw new RuntimeException(ioe);
  }
}
 
Example 13
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 14
Source File: GoogleAppSecretDecrypter.java    From data-transfer-project with Apache License 2.0 5 votes vote down vote up
@Inject
GoogleAppSecretDecrypter(
    HttpTransport transport, JsonFactory jsonFactory, @ProjectId String projectId)
    throws GoogleCredentialException {
  GoogleCredential credential;
  try {
    credential = GoogleCredential.getApplicationDefault(transport, jsonFactory);
  } catch (IOException e) {
    throw new GoogleCredentialException(
        "Problem obtaining credentials via GoogleCredential.getApplicationDefault()");
  }
  if (credential.createScopedRequired()) {
    credential = credential.createScoped(CloudKMSScopes.all());
  }
  this.cloudKMS =
      new CloudKMS.Builder(transport, jsonFactory, credential)
          .setApplicationName("GoogleAppSecretDecrypter")
          .build();
  this.secretsCryptoKey = String.format(SECRETS_CRYPTO_KEY_FMT_STRING, projectId);
}
 
Example 15
Source File: NewsInjector.java    From cloud-pubsub-samples-java with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a Cloud Pub/Sub client.
 */
public Pubsub createPubsubClient()
  throws IOException, GeneralSecurityException {
  HttpTransport transport = GoogleNetHttpTransport.newTrustedTransport();
  GoogleCredential credential = GoogleCredential.getApplicationDefault();
  HttpRequestInitializer initializer =
      new RetryHttpInitializerWrapper(credential);
  return new Pubsub.Builder(transport, JSON_FACTORY, initializer).build();
}
 
Example 16
Source File: Utils.java    From cloud-search-samples with Apache License 2.0 5 votes vote down vote up
static Directory buildDirectoryService() throws IOException, GeneralSecurityException {
  GoogleCredential credential = GoogleCredential.getApplicationDefault();
  if (credential.createScopedRequired()) {
    credential = credential.createScoped(Collections.singletonList(
        "https://www.googleapis.com/auth/admin.directory.user"
    ));
  }
  return new Directory.Builder(GoogleNetHttpTransport.newTrustedTransport(),
          JacksonFactory.getDefaultInstance(),
          credential)
      .setApplicationName("Cloud identity samples")
      .build();

}
 
Example 17
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 18
Source File: StorageFactory.java    From dlp-dataflow-deidentification with Apache License 2.0 5 votes vote down vote up
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);
  }

  return new Storage.Builder(transport, jsonFactory, credential)
      .setApplicationName("GCS")
      .build();
}
 
Example 19
Source File: GCEController.java    From pubsub with Apache License 2.0 4 votes vote down vote up
/** Returns a GCEController using default application credentials. */
public static GCEController newGCEController(
    String projectName, Map<ClientParams, Integer> 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"));
    }
    Storage storage =
        new Storage.Builder(transport, jsonFactory, credential)
            .setApplicationName("Cloud Pub/Sub Loadtest Framework")
            .build();
    Compute compute =
        new Compute.Builder(transport, jsonFactory, credential)
            .setApplicationName("Cloud Pub/Sub Loadtest Framework")
            .build();
    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<>();
    // Using atomic for effectively final not thread safety.
    AtomicBoolean hasJavaClient = new AtomicBoolean(false);
    AtomicReference<Boolean> hasKafkaClient = new AtomicReference<>(null);
    clients.forEach(
        (params, count) -> {
          hasJavaClient.set(
              hasJavaClient.get()
                  || (params.getClientType().language == ClientType.Language.JAVA));
          if (hasKafkaClient.get() != null) {
            if (hasKafkaClient.get() != params.getClientType().isKafka()) {
              if (!params.getClientType().isKafka()) {
                log.error("Cannot use mixed kafka and gcp client types.");
                System.exit(1);
              }
            }
          } else {
            hasKafkaClient.set(params.getClientType().isKafka());
          }

          GCEComputeResourceController computeController =
              new GCEComputeResourceController(projectName, params, count, executor, compute);
          controllers.add(computeController);
          computeControllers.add(computeController);
        });
    controllers.add(new FirewallResourceController(projectName, executor, compute));
    if (hasKafkaClient.get() != null && hasKafkaClient.get()) {
      controllers.add(new KafkaResourceController(Client.TOPIC, executor));
    }
    controllers.add(
        new PubsubResourceController(
            projectName, Client.TOPIC, ImmutableList.of(Client.SUBSCRIPTION), executor, pubsub));
    controllers.add(
        new StorageResourceController(
            projectName, Client.RESOURCE_DIR, false, hasJavaClient.get(), executor, storage));
    return new GCEController(clients, executor, controllers, computeControllers);
  } catch (Throwable t) {
    log.error("Unable to initialize GCE: ", t);
    return null;
  }
}
 
Example 20
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();
}