com.google.api.gax.core.CredentialsProvider Java Examples

The following examples show how to use com.google.api.gax.core.CredentialsProvider. 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: StackdriverConfig.java    From micrometer with Apache License 2.0 6 votes vote down vote up
/**
 * Return {@link CredentialsProvider} to use.
 *
 * @return {@code CredentialsProvider} to use
 * @since 1.4.0
 */
default CredentialsProvider credentials() {
    return getString(this, "credentials")
            .flatMap((credentials, valid) -> {
                if (StringUtils.isBlank(credentials)) {
                    return Validated.valid(valid.getProperty(), MetricServiceSettings.defaultCredentialsProviderBuilder().build());
                }

                try {
                    FixedCredentialsProvider provider = FixedCredentialsProvider.create(
                            GoogleCredentials.fromStream(new FileInputStream(credentials))
                                    .createScoped(MetricServiceSettings.getDefaultServiceScopes())
                    );
                    return Validated.valid(valid.getProperty(), provider);
                } catch (IOException t) {
                    return Validated.invalid(valid.getProperty(), credentials, "cannot read credentials file", InvalidReason.MALFORMED, t);
                }
            })
            .get();
}
 
Example #2
Source File: StackdriverTraceAutoConfigurationTests.java    From spring-cloud-gcp with Apache License 2.0 6 votes vote down vote up
@Bean
public static CredentialsProvider googleCredentials() {
	return () -> {
		Credentials creds = mock(Credentials.class);
		doAnswer((Answer<Void>)
			(invocationOnMock) -> {
				RequestMetadataCallback callback =
						(RequestMetadataCallback) invocationOnMock.getArguments()[2];
				callback.onSuccess(Collections.emptyMap());
				return null;
			})
		.when(creds)
		.getRequestMetadata(any(), any(), any());
		return creds;
	};
}
 
Example #3
Source File: PubSubManager.java    From smallrye-reactive-messaging with Apache License 2.0 6 votes vote down vote up
private static Optional<CredentialsProvider> buildCredentialsProvider(final PubSubConfig config) {
    if (config.isMockPubSubTopics()) {
        return Optional.of(NoCredentialsProvider.create());
    }

    if (config.getCredentialPath() != null) {
        try {
            return Optional.of(FixedCredentialsProvider
                    .create(ServiceAccountCredentials.fromStream(Files.newInputStream(config.getCredentialPath()))));
        } catch (final IOException e) {
            throw new IllegalStateException(e);
        }
    }

    return Optional.empty();
}
 
Example #4
Source File: GcpSpannerAutoConfiguration.java    From spring-cloud-gcp with Apache License 2.0 6 votes vote down vote up
CoreSpannerAutoConfiguration(GcpSpannerProperties gcpSpannerProperties,
		GcpProjectIdProvider projectIdProvider,
		CredentialsProvider credentialsProvider) throws IOException {
	this.credentials = (gcpSpannerProperties.getCredentials().hasKey()
			? new DefaultCredentialsProvider(gcpSpannerProperties)
			: credentialsProvider).getCredentials();
	this.projectId = (gcpSpannerProperties.getProjectId() != null)
			? gcpSpannerProperties.getProjectId()
			: projectIdProvider.getProjectId();
	this.instanceId = gcpSpannerProperties.getInstanceId();
	this.databaseName = gcpSpannerProperties.getDatabase();
	this.numRpcChannels = gcpSpannerProperties.getNumRpcChannels();
	this.prefetchChunks = gcpSpannerProperties.getPrefetchChunks();
	this.minSessions = gcpSpannerProperties.getMinSessions();
	this.maxSessions = gcpSpannerProperties.getMaxSessions();
	this.maxIdleSessions = gcpSpannerProperties.getMaxIdleSessions();
	this.writeSessionsFraction = gcpSpannerProperties.getWriteSessionsFraction();
	this.keepAliveIntervalMinutes = gcpSpannerProperties
			.getKeepAliveIntervalMinutes();
	this.createInterleavedTableDdlOnDeleteCascade = gcpSpannerProperties
			.isCreateInterleavedTableDdlOnDeleteCascade();
	this.failIfPoolExhausted = gcpSpannerProperties.isFailIfPoolExhausted();
}
 
Example #5
Source File: GcpPubSubAutoConfiguration.java    From spring-cloud-gcp with Apache License 2.0 6 votes vote down vote up
public GcpPubSubAutoConfiguration(GcpPubSubProperties gcpPubSubProperties,
		GcpProjectIdProvider gcpProjectIdProvider,
		CredentialsProvider credentialsProvider) throws IOException {
	this.gcpPubSubProperties = gcpPubSubProperties;
	this.finalProjectIdProvider = (gcpPubSubProperties.getProjectId() != null)
			? gcpPubSubProperties::getProjectId
			: gcpProjectIdProvider;

	if (gcpPubSubProperties.getEmulatorHost() == null
			|| "false".equals(gcpPubSubProperties.getEmulatorHost())) {
		this.finalCredentialsProvider = gcpPubSubProperties.getCredentials().hasKey()
				? new DefaultCredentialsProvider(gcpPubSubProperties)
				: credentialsProvider;
	}
	else {
		// Since we cannot create a general NoCredentialsProvider if the emulator host is enabled
		// (because it would also be used for the other components), we have to create one here
		// for this particular case.
		this.finalCredentialsProvider = NoCredentialsProvider.create();
	}
}
 
Example #6
Source File: GoogleConfigPropertySourceLocator.java    From spring-cloud-gcp with Apache License 2.0 6 votes vote down vote up
public GoogleConfigPropertySourceLocator(GcpProjectIdProvider projectIdProvider,
		CredentialsProvider credentialsProvider,
		GcpConfigProperties gcpConfigProperties) throws IOException {
	Assert.notNull(gcpConfigProperties, "Google Config properties must not be null");

	if (gcpConfigProperties.isEnabled()) {
		Assert.notNull(credentialsProvider, "Credentials provider cannot be null");
		Assert.notNull(projectIdProvider, "Project ID provider cannot be null");
		this.credentials = gcpConfigProperties.getCredentials().hasKey()
				? new DefaultCredentialsProvider(gcpConfigProperties).getCredentials()
				: credentialsProvider.getCredentials();
		this.projectId = (gcpConfigProperties.getProjectId() != null)
				? gcpConfigProperties.getProjectId()
				: projectIdProvider.getProjectId();
		Assert.notNull(this.credentials, "Credentials must not be null");

		Assert.notNull(this.projectId, "Project ID must not be null");

		this.timeout = gcpConfigProperties.getTimeoutMillis();
		this.name = gcpConfigProperties.getName();
		this.profile = gcpConfigProperties.getProfile();
		this.enabled = gcpConfigProperties.isEnabled();
		Assert.notNull(this.name, "Config name must not be null");
		Assert.notNull(this.profile, "Config profile must not be null");
	}
}
 
Example #7
Source File: CloudPubSubSourceConnector.java    From pubsub with Apache License 2.0 6 votes vote down vote up
/**
 * Check whether the user provided Cloud Pub/Sub subscription name specified by {@link
 * #CPS_SUBSCRIPTION_CONFIG} exists or not.
 */
@VisibleForTesting
public void verifySubscription(String cpsProject, String cpsSubscription, CredentialsProvider credentialsProvider) {
  try {
    SubscriberStubSettings subscriberStubSettings =
    SubscriberStubSettings.newBuilder()
      .setTransportChannelProvider(
          SubscriberStubSettings.defaultGrpcTransportProviderBuilder()
              .setMaxInboundMessageSize(20 << 20) // 20MB
              .build())
      .setCredentialsProvider(credentialsProvider)
      .build();
    GrpcSubscriberStub stub = GrpcSubscriberStub.create(subscriberStubSettings);
    GetSubscriptionRequest request =
        GetSubscriptionRequest.newBuilder()
            .setSubscription(
                String.format(
                    ConnectorUtils.CPS_SUBSCRIPTION_FORMAT, cpsProject, cpsSubscription))
            .build();
    stub.getSubscriptionCallable().call(request);
  } catch (Exception e) {
    throw new ConnectException(
        "Error verifying the subscription " + cpsSubscription + " for project " + cpsProject, e);
  }
}
 
Example #8
Source File: UsePubSubEmulatorSnippet.java    From google-cloud-java with Apache License 2.0 5 votes vote down vote up
public static void main(String... args) throws IOException {
  // [START pubsub_use_emulator]
  String hostport = System.getenv("PUBSUB_EMULATOR_HOST");
  ManagedChannel channel = ManagedChannelBuilder.forTarget(hostport).usePlaintext().build();
  try {
    TransportChannelProvider channelProvider =
        FixedTransportChannelProvider.create(GrpcTransportChannel.create(channel));
    CredentialsProvider credentialsProvider = NoCredentialsProvider.create();

    // Set the channel and credentials provider when creating a `TopicAdminClient`.
    // Similarly for SubscriptionAdminClient
    TopicAdminClient topicClient =
        TopicAdminClient.create(
            TopicAdminSettings.newBuilder()
                .setTransportChannelProvider(channelProvider)
                .setCredentialsProvider(credentialsProvider)
                .build());

    TopicName topicName = TopicName.of("my-project-id", "my-topic-id");
    // Set the channel and credentials provider when creating a `Publisher`.
    // Similarly for Subscriber
    Publisher publisher =
        Publisher.newBuilder(topicName)
            .setChannelProvider(channelProvider)
            .setCredentialsProvider(credentialsProvider)
            .build();
  } finally {
    channel.shutdown();
  }
  // [END pubsub_use_emulator]
}
 
Example #9
Source File: GcpDatastoreAutoConfigurationTests.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
@Test
public void testDatastoreEmulatorCredentialsConfig() {
	this.contextRunner.run((context) -> {
		CredentialsProvider defaultCredentialsProvider = context.getBean(CredentialsProvider.class);
		assertThat(defaultCredentialsProvider).isNotInstanceOf(NoCredentialsProvider.class);

		DatastoreOptions datastoreOptions = getDatastoreBean(context).getOptions();
		assertThat(datastoreOptions.getCredentials()).isInstanceOf(NoCredentials.class);
	});
}
 
Example #10
Source File: GcpPubSubEmulatorAutoConfigurationTests.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
@Test
public void testEmulatorConfig() {
	this.contextRunner.run((context) -> {
		CredentialsProvider defaultCredentialsProvider = context.getBean(CredentialsProvider.class);
		assertThat(defaultCredentialsProvider).isNotInstanceOf(NoCredentialsProvider.class);

		TopicAdminSettings topicAdminSettings = context.getBean(TopicAdminSettings.class);
		CredentialsProvider credentialsProvider = topicAdminSettings.getCredentialsProvider();
		assertThat(credentialsProvider).isInstanceOf(NoCredentialsProvider.class);

		TransportChannelProvider transportChannelProvider = context.getBean(TransportChannelProvider.class);
		assertThat(transportChannelProvider).isInstanceOf(FixedTransportChannelProvider.class);
	});
}
 
Example #11
Source File: GcpStorageAutoConfiguration.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
public GcpStorageAutoConfiguration(
		GcpProjectIdProvider coreProjectIdProvider,
		CredentialsProvider credentialsProvider,
		GcpStorageProperties gcpStorageProperties) throws IOException {

	this.gcpProjectIdProvider =
			gcpStorageProperties.getProjectId() != null
					? gcpStorageProperties::getProjectId
					: coreProjectIdProvider;

	this.credentialsProvider =
			gcpStorageProperties.getCredentials().hasKey()
					? new DefaultCredentialsProvider(gcpStorageProperties)
					: credentialsProvider;
}
 
Example #12
Source File: CloudVisionAutoConfiguration.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
public CloudVisionAutoConfiguration(
		CloudVisionProperties properties, CredentialsProvider credentialsProvider)
		throws IOException {

	this.cloudVisionProperties = properties;

	if (properties.getCredentials().hasKey()) {
		this.credentialsProvider = new DefaultCredentialsProvider(properties);
	}
	else {
		this.credentialsProvider = credentialsProvider;
	}
}
 
Example #13
Source File: StackdriverTraceAutoConfiguration.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
public StackdriverTraceAutoConfiguration(GcpProjectIdProvider gcpProjectIdProvider,
		CredentialsProvider credentialsProvider,
		GcpTraceProperties gcpTraceProperties) throws IOException {
	this.finalProjectIdProvider = (gcpTraceProperties.getProjectId() != null)
			? gcpTraceProperties::getProjectId
			: gcpProjectIdProvider;
	this.finalCredentialsProvider =
			gcpTraceProperties.getCredentials().hasKey()
					? new DefaultCredentialsProvider(gcpTraceProperties)
					: credentialsProvider;
}
 
Example #14
Source File: GcpFirestoreAutoConfiguration.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
GcpFirestoreAutoConfiguration(GcpFirestoreProperties gcpFirestoreProperties,
		GcpProjectIdProvider projectIdProvider,
		CredentialsProvider credentialsProvider) throws IOException {

	this.projectId = (gcpFirestoreProperties.getProjectId() != null)
			? gcpFirestoreProperties.getProjectId()
			: projectIdProvider.getProjectId();

	this.credentialsProvider = (gcpFirestoreProperties.getCredentials().hasKey()
			? new DefaultCredentialsProvider(gcpFirestoreProperties)
			: credentialsProvider);

	this.hostPort = gcpFirestoreProperties.getHostPort();
	this.firestoreRootPath = String.format(ROOT_PATH_FORMAT, this.projectId);
}
 
Example #15
Source File: GcpStackdriverMetricsAutoConfiguration.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
public GcpStackdriverMetricsAutoConfiguration(GcpMetricsProperties gcpMetricsProperties,
		StackdriverProperties stackdriverProperties, GcpProjectIdProvider gcpProjectIdProvider,
		CredentialsProvider credentialsProvider) throws IOException {
	this.stackdriverProperties = stackdriverProperties;
	this.projectId = (gcpMetricsProperties.getProjectId() != null)
			? gcpMetricsProperties.getProjectId() : gcpProjectIdProvider.getProjectId();
	this.credentialsProvider = gcpMetricsProperties.getCredentials().hasKey()
			? new DefaultCredentialsProvider(gcpMetricsProperties) : credentialsProvider;
}
 
Example #16
Source File: GcpBigQueryAutoConfiguration.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
GcpBigQueryAutoConfiguration(
		GcpBigQueryProperties gcpBigQueryProperties,
		GcpProjectIdProvider projectIdProvider,
		CredentialsProvider credentialsProvider) throws IOException {

	this.projectId = (gcpBigQueryProperties.getProjectId() != null)
			? gcpBigQueryProperties.getProjectId()
			: projectIdProvider.getProjectId();

	this.credentialsProvider = (gcpBigQueryProperties.getCredentials().hasKey()
			? new DefaultCredentialsProvider(gcpBigQueryProperties)
			: credentialsProvider);

	this.datasetName = gcpBigQueryProperties.getDatasetName();
}
 
Example #17
Source File: PubSubAdmin.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
/**
 * This constructor instantiates TopicAdminClient and SubscriptionAdminClient with all their
 * defaults and the provided credentials provider.
 * @param projectIdProvider the project id provider to use
 * @param credentialsProvider the credentials provider to use
 * @throws IOException thrown when there are errors in contacting Google Cloud Pub/Sub
 */
public PubSubAdmin(GcpProjectIdProvider projectIdProvider,
		CredentialsProvider credentialsProvider) throws IOException {
	this(projectIdProvider,
			TopicAdminClient.create(
					TopicAdminSettings.newBuilder()
							.setCredentialsProvider(credentialsProvider)
							.build()),
			SubscriptionAdminClient.create(
					SubscriptionAdminSettings.newBuilder()
					.setCredentialsProvider(credentialsProvider)
					.build()));
}
 
Example #18
Source File: ConnectorUtils.java    From pubsub with Apache License 2.0 5 votes vote down vote up
/** Return {@link io.grpc.Channel} which is used by Cloud Pub/Sub gRPC API's. */
public static Channel getChannel(CredentialsProvider credentialsProvider) throws IOException {
  ManagedChannel channelImpl =
      NettyChannelBuilder.forAddress(ENDPOINT, 443)
          .negotiationType(NegotiationType.TLS)
          // Maximum Pub/Sub message size is 10MB.
          .maxInboundMessageSize(10 * 1024 * 1024)
          .build();
  final ClientAuthInterceptor interceptor =
      new ClientAuthInterceptor(
          credentialsProvider.getCredentials(),
          Executors.newCachedThreadPool());
  return ClientInterceptors.intercept(channelImpl, interceptor);
}
 
Example #19
Source File: GcpDatastoreAutoConfiguration.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
GcpDatastoreAutoConfiguration(GcpDatastoreProperties gcpDatastoreProperties,
		GcpProjectIdProvider projectIdProvider,
		CredentialsProvider credentialsProvider) throws IOException {

	this.projectId = (gcpDatastoreProperties.getProjectId() != null)
			? gcpDatastoreProperties.getProjectId()
			: projectIdProvider.getProjectId();
	this.namespace = gcpDatastoreProperties.getNamespace();

	String hostToConnect = gcpDatastoreProperties.getHost();
	if (gcpDatastoreProperties.getEmulator().isEnabled()) {
		hostToConnect = "localhost:" + gcpDatastoreProperties.getEmulator().getPort();
		LOGGER.info("Connecting to a local datastore emulator.");
	}

	if (hostToConnect == null) {
		this.credentials = (gcpDatastoreProperties.getCredentials().hasKey()
				? new DefaultCredentialsProvider(gcpDatastoreProperties)
				: credentialsProvider).getCredentials();
	}
	else {
		// Use empty credentials with Datastore Emulator.
		this.credentials = NoCredentials.getInstance();
	}

	this.host = hostToConnect;
}
 
Example #20
Source File: GoogleStorageIntegrationTests.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
@Bean
public CredentialsProvider credentialsProvider() {
	try {
		return new DefaultCredentialsProvider(Credentials::new);
	}
	catch (IOException ex) {
		throw new RuntimeException(ex);
	}
}
 
Example #21
Source File: GoogleStorageIntegrationTests.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
@Bean
public static Storage storage(CredentialsProvider credentialsProvider,
		GcpProjectIdProvider projectIdProvider) throws IOException {
	return StorageOptions.newBuilder()
			.setCredentials(credentialsProvider.getCredentials())
			.setProjectId(projectIdProvider.getProjectId()).build().getService();
}
 
Example #22
Source File: TestApp.java    From gcpsamples with Apache License 2.0 4 votes vote down vote up
public TestApp()  {

    String projectId = ServiceOptions.getDefaultProjectId();
	try {

		//export GRPC_PROXY_EXP=localhost:3128
		HttpHost proxy = new HttpHost("127.0.0.1",3128);
		DefaultHttpClient httpClient = new DefaultHttpClient();
		httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
					
		httpClient.addRequestInterceptor(new HttpRequestInterceptor(){            
			@Override
			public void process(org.apache.http.HttpRequest request, HttpContext context) throws HttpException, IOException {
					//if (request.getRequestLine().getMethod().equals("CONNECT"))                 
					//   request.addHeader(new BasicHeader("Proxy-Authorization","Basic dXNlcjE6dXNlcjE="));
				}
			});
		
		mHttpTransport =  new ApacheHttpTransport(httpClient);		

		HttpTransportFactory hf = new HttpTransportFactory(){
			@Override
			public HttpTransport create() {
				return mHttpTransport;
			}
		};            
		
		credential = GoogleCredentials.getApplicationDefault(hf);

		CredentialsProvider credentialsProvider =  new GoogleCredentialsProvider(){
			public List<String> getScopesToApply(){
				return Arrays.asList("https://www.googleapis.com/auth/pubsub");
			   }

			public Credentials getCredentials()  {
				return credential;
			}
		};

		TopicAdminSettings topicAdminSettings =
		     TopicAdminSettings.newBuilder().setCredentialsProvider(credentialsProvider)
				 .build();
				 
		 TopicAdminClient topicAdminClient =
		     TopicAdminClient.create(topicAdminSettings);
		
		//TopicAdminClient topicAdminClient = TopicAdminClient.create();
		ProjectName project = ProjectName.create(projectId);
		for (Topic element : topicAdminClient.listTopics(project).iterateAll()) 
	  		System.out.println(element.getName());
	
	} catch (Exception ex) 
	{
		System.out.println("ERROR " + ex);
	}
  }
 
Example #23
Source File: DatastoreHealthIndicatorAutoConfigurationTests.java    From spring-cloud-gcp with Apache License 2.0 4 votes vote down vote up
@Bean
public CredentialsProvider credentialsProvider() {
	return () -> mock(Credentials.class);
}
 
Example #24
Source File: GcpDatastoreEmulatorIntegrationTests.java    From spring-cloud-gcp with Apache License 2.0 4 votes vote down vote up
@Bean
public CredentialsProvider credentialsProvider() {
	return () -> mock(Credentials.class);
}
 
Example #25
Source File: GcpFirestoreAutoConfigurationTests.java    From spring-cloud-gcp with Apache License 2.0 4 votes vote down vote up
@Bean
public CredentialsProvider credentialsProvider() {
	return () -> mock(GoogleCredentials.class);
}
 
Example #26
Source File: GcpPubSubReactiveAutoConfigurationTest.java    From spring-cloud-gcp with Apache License 2.0 4 votes vote down vote up
@Bean
public CredentialsProvider googleCredentials() {
	return () -> mock(Credentials.class);
}
 
Example #27
Source File: SecretManagerBootstrapConfigurationTests.java    From spring-cloud-gcp with Apache License 2.0 4 votes vote down vote up
@Bean
public static CredentialsProvider googleCredentials() {
	return () -> mock(Credentials.class);
}
 
Example #28
Source File: GcpCloudSqlTestConfiguration.java    From spring-cloud-gcp with Apache License 2.0 4 votes vote down vote up
@Bean
public CredentialsProvider googleCredentials() {
	return () -> mock(Credentials.class);
}
 
Example #29
Source File: GcpStorageAutoConfigurationTests.java    From spring-cloud-gcp with Apache License 2.0 4 votes vote down vote up
@Bean
public static CredentialsProvider googleCredentials() {
	return () -> mock(Credentials.class);
}
 
Example #30
Source File: GcpSpannerAutoConfigurationTests.java    From spring-cloud-gcp with Apache License 2.0 4 votes vote down vote up
@Bean
public CredentialsProvider credentialsProvider() {
	return () -> mock(Credentials.class);
}