com.google.cloud.pubsub.v1.TopicAdminSettings Java Examples

The following examples show how to use com.google.cloud.pubsub.v1.TopicAdminSettings. 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: TopicAdmin.java    From ffwd with Apache License 2.0 6 votes vote down vote up
@Provides
@Singleton
public TopicAdminClient getClient() throws IOException {
  final TopicAdminSettings.Builder adminSetting = TopicAdminSettings.newBuilder();

  final String emulatorHost = System.getenv("PUBSUB_EMULATOR_HOST");
  if (emulatorHost != null) {
    ManagedChannel channel =
      ManagedChannelBuilder.forTarget(emulatorHost).usePlaintext().build();
    TransportChannelProvider channelProvider =
      FixedTransportChannelProvider.create(GrpcTransportChannel.create(channel));

    adminSetting.setTransportChannelProvider(channelProvider);
    adminSetting.setCredentialsProvider(NoCredentialsProvider.create());
  }

  return TopicAdminClient.create(adminSetting.build());
}
 
Example #2
Source File: PubsubHelper.java    From flink with Apache License 2.0 5 votes vote down vote up
public TopicAdminClient getTopicAdminClient() throws IOException {
	if (topicClient == null) {
		TopicAdminSettings topicAdminSettings = TopicAdminSettings.newBuilder()
			.setTransportChannelProvider(channelProvider)
			.setCredentialsProvider(NoCredentialsProvider.create())
			.build();
		topicClient = TopicAdminClient.create(topicAdminSettings);
	}
	return topicClient;
}
 
Example #3
Source File: PubSubManager.java    From smallrye-reactive-messaging with Apache License 2.0 5 votes vote down vote up
private static TopicAdminClient buildTopicAdminClient(final PubSubConfig config) {
    final TopicAdminSettings.Builder topicAdminSettingsBuilder = TopicAdminSettings.newBuilder();

    buildCredentialsProvider(config).ifPresent(topicAdminSettingsBuilder::setCredentialsProvider);
    buildTransportChannelProvider(config).ifPresent(topicAdminSettingsBuilder::setTransportChannelProvider);

    try {
        return TopicAdminClient.create(topicAdminSettingsBuilder.build());
    } catch (final IOException e) {
        throw ex.illegalStateUnableToBuildTopicAdminClient(e);
    }
}
 
Example #4
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 #5
Source File: GcpPubSubAutoConfiguration.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
@Bean
@ConditionalOnMissingBean
public TopicAdminClient topicAdminClient(
		TopicAdminSettings topicAdminSettings) {
	try {
		return TopicAdminClient.create(topicAdminSettings);
	}
	catch (IOException ioe) {
		throw new PubSubException("An error occurred while creating TopicAdminClient.", ioe);
	}
}
 
Example #6
Source File: GcpPubSubAutoConfiguration.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
@Bean
@ConditionalOnMissingBean
public TopicAdminSettings topicAdminSettings(
		TransportChannelProvider transportChannelProvider) {
	try {
		return TopicAdminSettings.newBuilder()
				.setCredentialsProvider(this.finalCredentialsProvider)
				.setHeaderProvider(this.headerProvider)
				.setTransportChannelProvider(transportChannelProvider)
				.build();
	}
	catch (IOException ioe) {
		throw new PubSubException("An error occurred while creating TopicAdminSettings.", ioe);
	}
}
 
Example #7
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 #8
Source File: Connection.java    From heroic with Apache License 2.0 5 votes vote down vote up
void createTopic() throws IOException {
    log.info("Creating topic {}", topicName);
    TopicAdminClient topicAdminClient = TopicAdminClient.create(
        TopicAdminSettings.newBuilder()
            .setTransportChannelProvider(channelProvider)
            .setCredentialsProvider(credentialsProvider)
            .build()
    );
    try {
        topicAdminClient.createTopic(topicName);
    } catch (AlreadyExistsException e) {
        log.info("Topic already exists");
    }
}
 
Example #9
Source File: PubsubHelper.java    From flink with Apache License 2.0 5 votes vote down vote up
public TopicAdminClient getTopicAdminClient() throws IOException {
	if (topicClient == null) {
		TopicAdminSettings topicAdminSettings = TopicAdminSettings.newBuilder()
			.setTransportChannelProvider(channelProvider)
			.setCredentialsProvider(NoCredentialsProvider.create())
			.build();
		topicClient = TopicAdminClient.create(topicAdminSettings);
	}
	return topicClient;
}
 
Example #10
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 #11
Source File: PubSubTestBinder.java    From spring-cloud-gcp with Apache License 2.0 4 votes vote down vote up
public PubSubTestBinder(String host) {
	GcpProjectIdProvider projectIdProvider = () -> "porto sentido";

	// Transport channel provider so that test binder talks to emulator.
	ManagedChannel channel = ManagedChannelBuilder
			.forTarget(host)
			.usePlaintext()
			.build();
	TransportChannelProvider transportChannelProvider =
			FixedTransportChannelProvider.create(GrpcTransportChannel.create(channel));

	PubSubChannelProvisioner pubSubChannelProvisioner;

	try {
		SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create(
				SubscriptionAdminSettings.newBuilder()
						.setTransportChannelProvider(transportChannelProvider)
						.setCredentialsProvider(NoCredentialsProvider.create())
						.build()
		);

		TopicAdminClient topicAdminClient = TopicAdminClient.create(
				TopicAdminSettings.newBuilder()
						.setTransportChannelProvider(transportChannelProvider)
						.setCredentialsProvider(NoCredentialsProvider.create())
						.build()
		);

		pubSubChannelProvisioner = new PubSubChannelProvisioner(
				new PubSubAdmin(projectIdProvider, topicAdminClient, subscriptionAdminClient)
		);
	}
	catch (IOException ioe) {
		throw new RuntimeException("Couldn't build test binder.", ioe);
	}

	DefaultSubscriberFactory subscriberFactory = new DefaultSubscriberFactory(projectIdProvider);
	subscriberFactory.setChannelProvider(transportChannelProvider);
	subscriberFactory.setCredentialsProvider(NoCredentialsProvider.create());

	DefaultPublisherFactory publisherFactory = new DefaultPublisherFactory(projectIdProvider);
	publisherFactory.setChannelProvider(transportChannelProvider);
	publisherFactory.setCredentialsProvider(NoCredentialsProvider.create());

	PubSubTemplate pubSubTemplate = new PubSubTemplate(publisherFactory, subscriberFactory);

	PubSubMessageChannelBinder binder =
			new PubSubMessageChannelBinder(null, pubSubChannelProvisioner, pubSubTemplate,
					new PubSubExtendedBindingProperties());
	GenericApplicationContext context = new GenericApplicationContext();
	binder.setApplicationContext(context);
	this.setBinder(binder);
}
 
Example #12
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 #13
Source File: TestApp.java    From gcpsamples with Apache License 2.0 4 votes vote down vote up
public TestApp() {
	try
	{
		/*
		// For GoogleAPIs
		HttpTransport httpTransport = new NetHttpTransport();             
		JacksonFactory jsonFactory = new JacksonFactory();
		//ComputeCredential credential = new ComputeCredential.Builder(httpTransport, jsonFactory).build();	
		GoogleCredential credential = GoogleCredential.getApplicationDefault(httpTransport,jsonFactory);				            
		if (credential.createScopedRequired())
		    credential = credential.createScoped(Arrays.asList(Oauth2Scopes.USERINFO_EMAIL));           				            
		Oauth2 service = new Oauth2.Builder(httpTransport, jsonFactory, credential)
		            .setApplicationName("oauth client")   
		            .build();				            
		Userinfoplus ui = service.userinfo().get().execute();
		System.out.println(ui.getEmail());
		*/

         // Using Google Cloud APIs
	  Storage storage_service = StorageOptions.newBuilder()
		.build()
		.getService();	
	  for (Bucket b : storage_service.list().iterateAll()){
		  System.out.println(b);
	  }

         // String cred_file = "/path/to/cred.json";
	  //GoogleCredentials creds = GoogleCredentials.fromStream(new FileInputStream(cred_file));	
	  GoogleCredentials creds = GoogleCredentials.getApplicationDefault();	  	  
	  FixedCredentialsProvider credentialsProvider = FixedCredentialsProvider.create(creds);
	  
	  ///ManagedChannel channel = ManagedChannelBuilder.forTarget("pubsub.googleapis.com:443").build();
         //TransportChannelProvider channelProvider = FixedTransportChannelProvider.create(GrpcTransportChannel.create(channel));	
	  
	  TransportChannelProvider channelProvider = TopicAdminSettings.defaultTransportChannelProvider();

	  TopicAdminClient topicClient =
		  TopicAdminClient.create(
			  TopicAdminSettings.newBuilder()
				  .setTransportChannelProvider(channelProvider)
				  .setCredentialsProvider(credentialsProvider)
				  .build());

	  ListTopicsRequest listTopicsRequest =
						ListTopicsRequest.newBuilder()
							.setProject(ProjectName.format("your_project"))
							.build();
	  ListTopicsPagedResponse response = topicClient.listTopics(listTopicsRequest);
	  Iterable<Topic> topics = response.iterateAll();
	  for (Topic topic : topics) 
		 System.out.println(topic);
	 		  

	} 
	catch (Exception ex) {
		System.out.println("Error:  " + ex);
	}
}
 
Example #14
Source File: TestApp.java    From gcpsamples with Apache License 2.0 4 votes vote down vote up
public TestApp() {
		try
		{

			// use env or set the path directly
			String cred_env = System.getenv("GOOGLE_APPLICATION_CREDENTIALS");
			cred_env = "/path/to/your/cert.json";
			
/*
			<!--use:
				<dependency>
				<groupId>com.google.api-client</groupId>
				<artifactId>google-api-client</artifactId>
				<version>1.23.0</version>
				</dependency>
				<dependency>
				<groupId>com.google.apis</groupId>
				<artifactId>google-api-services-oauth2</artifactId>
				<version>v2-rev114-1.22.0</version>
				</dependency>
			--> 
			HttpTransport httpTransport = new NetHttpTransport();             
			JacksonFactory jsonFactory = new JacksonFactory();

            // unset GOOGLE_APPLICATION_CREDENTIALS
            //String SERVICE_ACCOUNT_JSON_FILE = "YOUR_SERVICE_ACCOUNT_JSON_FILE.json";
            //FileInputStream inputStream = new FileInputStream(new File(SERVICE_ACCOUNT_JSON_FILE));
            //GoogleCredential credential = GoogleCredential.fromStream(inputStream, httpTransport, jsonFactory);

			// to use application default credentials and a JSON file, set the environment variable first:
            // export GOOGLE_APPLICATION_CREDENTIALS=YOUR_SERVICE_ACCOUNT_JSON_FILE.json        
            GoogleCredential credential = GoogleCredential.getApplicationDefault(httpTransport,jsonFactory);

            if (credential.createScopedRequired())
                credential = credential.createScoped(Arrays.asList(Oauth2Scopes.USERINFO_EMAIL));

			Oauth2 service = new Oauth2.Builder(httpTransport, jsonFactory, credential)
			            .setApplicationName("oauth client")   
			            .build();				            
			Userinfoplus ui = service.userinfo().get().execute();
			System.out.println(ui.getEmail());
*/
/* 
          Using Google Cloud APIs with service account file
		  // You can also just export an export GOOGLE_APPLICATION_CREDENTIALS and use StorageOptions.defaultInstance().service()
		  // see: https://github.com/google/google-auth-library-java#google-auth-library-oauth2-http
		  uncomment the dependencies for google-api-client
		  
			<dependency>
				<groupId>com.google.cloud</groupId>
				<artifactId>google-cloud-storage</artifactId>
				<version>1.35.0</version>
			</dependency>

			<dependency>
				<groupId>com.google.cloud</groupId>
				<artifactId>google-cloud-pubsub</artifactId>
				<version>1.35.0</version>
			</dependency>
*/
		  
		  
		  Storage storage_service = StorageOptions.newBuilder()
			.build()
			.getService();	
		  for (Bucket b : storage_service.list().iterateAll()){
			  System.out.println(b);
		  }

		  //GoogleCredentials creds = GoogleCredentials.fromStream(new FileInputStream(cred_env));	
		  GoogleCredentials creds = GoogleCredentials.getApplicationDefault();	  	  
		  FixedCredentialsProvider credentialsProvider = FixedCredentialsProvider.create(creds);
		  
		  ///ManagedChannel channel = ManagedChannelBuilder.forTarget("pubsub.googleapis.com:443").build();
          //TransportChannelProvider channelProvider = FixedTransportChannelProvider.create(GrpcTransportChannel.create(channel));	
		  
		  TransportChannelProvider channelProvider = TopicAdminSettings.defaultTransportChannelProvider();

		  TopicAdminClient topicClient =
			  TopicAdminClient.create(
				  TopicAdminSettings.newBuilder()
					  .setTransportChannelProvider(channelProvider)
					  .setCredentialsProvider(credentialsProvider)
					  .build());

		  ListTopicsRequest listTopicsRequest =
							ListTopicsRequest.newBuilder()
								.setProject(ProjectName.format("your_project"))
								.build();
		  ListTopicsPagedResponse response = topicClient.listTopics(listTopicsRequest);
		  Iterable<Topic> topics = response.iterateAll();
		  for (Topic topic : topics) 
			 System.out.println(topic);
		 

		} 
		catch (Exception ex) {
			System.out.println("Error:  " + ex);
		}
	}