### Create Push Subscription Example Source: https://github.com/googleapis/java-pubsub/blob/main/README.md Example demonstrating how to create a push subscription in Pub/Sub. Ensure you have the necessary dependencies and authentication configured. ```java /* * Copyright 2023 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package pubsub; import com.google.api.gax.core.FixedCredentialsProvider; import com.google.auth.oauth2.GoogleCredentials; import com.google.cloud.pubsub.v1.SubscriptionAdminClient; import com.google.cloud.pubsub.v1.SubscriptionAdminSettings; import com.google.pubsub.v1.ProjectName; import com.google.pubsub.v1.PushConfig; import com.google.pubsub.v1.SchemaSettings; import com.google.pubsub.v1.Subscription; import com.google.pubsub.v1.SubscriptionName; import com.google.pubsub.v1.TopicName; import java.io.IOException; public class CreatePushSubscriptionExample { public static void createPushSubscription( String projectId, String topicId, String subscriptionId, String pushEndpoint) throws IOException { // TODO(developer): Replace these variables before running the sample. // projectId = "your-project-id"; // topicId = "your-topic-id"; // subscriptionId = "your-subscription-id"; // pushEndpoint = "your-push-endpoint"; // e.g., https://your-app.com/push // Use Application Default Credentials (ADC) to authenticate. // See https://cloud.google.com/docs/authentication-overview#adc GoogleCredentials credentials = GoogleCredentials.getApplicationDefault(); SubscriptionAdminSettings subscriptionAdminSettings = SubscriptionAdminSettings.newBuilder() .setCredentialsProvider(FixedCredentialsProvider.create(credentials)) .build(); try ( SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create(subscriptionAdminSettings)) { TopicName topicName = TopicName.of(projectId, topicId); SubscriptionName subscriptionName = SubscriptionName.of(projectId, subscriptionId); // Configure the push subscription. PushConfig pushConfig = PushConfig.newBuilder().setPushEndpoint(pushEndpoint).build(); Subscription subscription = Subscription.newBuilder() .setName(subscriptionName) .setTopic(topicName) .setPushConfig(pushConfig) .setEnableMessageOrdering(true) .build(); // Create the subscription. Subscription createdSubscription = subscriptionAdminClient.createSubscription(subscription); System.out.println("Subscription created: " + createdSubscription.getName()); } } } ``` -------------------------------- ### Create Pull Subscription Example Source: https://github.com/googleapis/java-pubsub/blob/main/README.md Example demonstrating how to create a pull subscription in Pub/Sub. Ensure you have the necessary dependencies and authentication configured. ```java /* * Copyright 2023 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package pubsub; import com.google.api.gax.core.FixedCredentialsProvider; import com.google.auth.oauth2.GoogleCredentials; import com.google.cloud.pubsub.v1.SubscriptionAdminClient; import com.google.cloud.pubsub.v1.SubscriptionAdminSettings; import com.google.pubsub.v1.ProjectName; import com.google.pubsub.v1.SchemaSettings; import com.google.pubsub.v1.Subscription; import com.google.pubsub.v1.SubscriptionName; import com.google.pubsub.v1.TopicName; import java.io.IOException; public class CreatePullSubscriptionExample { public static void createPullSubscription( String projectId, String topicId, String subscriptionId) throws IOException { // TODO(developer): Replace these variables before running the sample. // projectId = "your-project-id"; // topicId = "your-topic-id"; // subscriptionId = "your-subscription-id"; // Use Application Default Credentials (ADC) to authenticate. // See https://cloud.google.com/docs/authentication-overview#adc GoogleCredentials credentials = GoogleCredentials.getApplicationDefault(); SubscriptionAdminSettings subscriptionAdminSettings = SubscriptionAdminSettings.newBuilder() .setCredentialsProvider(FixedCredentialsProvider.create(credentials)) .build(); try ( SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create(subscriptionAdminSettings)) { TopicName topicName = TopicName.of(projectId, topicId); SubscriptionName subscriptionName = SubscriptionName.of(projectId, subscriptionId); // Create a pull subscription. Subscription subscription = Subscription.newBuilder() .setName(subscriptionName) .setTopic(topicName) .setEnableMessageOrdering(true) .build(); // Create the subscription. Subscription createdSubscription = subscriptionAdminClient.createSubscription(subscription); System.out.println("Subscription created: " + createdSubscription.getName()); } } } ``` -------------------------------- ### Create Cloud Storage Subscription Example Source: https://github.com/googleapis/java-pubsub/blob/main/README.md Example demonstrating how to create a Pub/Sub subscription that forwards messages to a Cloud Storage bucket. Ensure you have the necessary dependencies and authentication configured. ```java /* * Copyright 2023 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package pubsub; import com.google.api.gax.core.FixedCredentialsProvider; import com.google.auth.oauth2.GoogleCredentials; import com.google.cloud.pubsub.v1.SubscriptionAdminClient; import com.google.cloud.pubsub.v1.SubscriptionAdminSettings; import com.google.pubsub.v1.ProjectName; import com.google.pubsub.v1.SchemaSettings; import com.google.pubsub.v1.Subscription; import com.google.pubsub.v1.SubscriptionName; import com.google.pubsub.v1.TopicName; import java.io.IOException; public class CreateCloudStorageSubscriptionExample { public static void createCloudStorageSubscription( String projectId, String topicId, String subscriptionId, String bucketName) throws IOException { // TODO(developer): Replace these variables before running the sample. // projectId = "your-project-id"; // topicId = "your-topic-id"; // subscriptionId = "your-subscription-id"; // bucketName = "your-bucket-name"; // Use Application Default Credentials (ADC) to authenticate. // See https://cloud.google.com/docs/authentication-overview#adc GoogleCredentials credentials = GoogleCredentials.getApplicationDefault(); SubscriptionAdminSettings subscriptionAdminSettings = SubscriptionAdminSettings.newBuilder() .setCredentialsProvider(FixedCredentialsProvider.create(credentials)) .build(); try ( SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create(subscriptionAdminSettings)) { TopicName topicName = TopicName.of(projectId, topicId); SubscriptionName subscriptionName = SubscriptionName.of(projectId, subscriptionId); // Configure the Cloud Storage subscription. Subscription subscription = Subscription.newBuilder() .setName(subscriptionName) .setTopic(topicName) .setEnableMessageOrdering(true) .setCloudStorageConfig( Subscription.CloudStorageConfig.newBuilder().setBucket(bucketName).build()) .build(); // Create the subscription. Subscription createdSubscription = subscriptionAdminClient.createSubscription(subscription); System.out.println("Subscription created: " + createdSubscription.getName()); } } } ``` -------------------------------- ### Basic Publisher Example in Java Source: https://github.com/googleapis/java-pubsub/blob/main/README.md A fundamental example of how to use the Publisher client to send messages to a Pub/Sub topic. This serves as a starting point for message publishing. ```java PublisherExample.java ``` -------------------------------- ### Create Proto Schema Example Source: https://github.com/googleapis/java-pubsub/blob/main/README.md Example demonstrating how to create a Protocol Buffer schema in Pub/Sub. Ensure you have the necessary dependencies and authentication configured. ```java /* * Copyright 2023 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package pubsub; import com.google.api.gax.core.FixedCredentialsProvider; import com.google.auth.oauth2.GoogleCredentials; import com.google.cloud.pubsub.v1.SchemaServiceClient; import com.google.cloud.pubsub.v1.SchemaServiceSettings; import com.google.pubsub.v1.ProjectName; import com.google.pubsub.v1.Schema; import com.google.pubsub.v1.SchemaName; import java.io.IOException; public class CreateProtoSchemaExample { public static void createProtoSchema(String projectId, String schemaId) throws IOException { // TODO(developer): Replace these variables before running the sample. // projectId = "your-project-id"; // schemaId = "your-schema-id"; // Use Application Default Credentials (ADC) to authenticate. // See https://cloud.google.com/docs/authentication-overview#adc GoogleCredentials credentials = GoogleCredentials.getApplicationDefault(); SchemaServiceSettings schemaServiceSettings = SchemaServiceSettings.newBuilder() .setCredentialsProvider(FixedCredentialsProvider.create(credentials)) .build(); try (SchemaServiceClient schemaServiceClient = SchemaServiceClient.create(schemaServiceSettings)) { ProjectName projectName = ProjectName.of(projectId); SchemaName schemaName = SchemaName.of(projectId, schemaId); // Define the schema content. Schema schema = Schema.newBuilder() .setType(Schema.Type.PROTOCOL_BUFFER) .setDefinition("syntax = \"proto3\";\n\nmessage Hello {\n string message = 1;\n}") .build(); // Create the schema. Schema createdSchema = schemaServiceClient.createSchema(projectName, schemaId, schema); System.out.println("Schema created: " + createdSchema.getName()); } } } ``` -------------------------------- ### Create Big Query Subscription Example Source: https://github.com/googleapis/java-pubsub/blob/main/README.md Example demonstrating how to create a Pub/Sub subscription that forwards messages to a BigQuery dataset. Ensure you have the necessary dependencies and authentication configured. ```java /* * Copyright 2023 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package pubsub; import com.google.api.gax.core.FixedCredentialsProvider; import com.google.auth.oauth2.GoogleCredentials; import com.google.cloud.pubsub.v1.SubscriptionAdminClient; import com.google.cloud.pubsub.v1.SubscriptionAdminSettings; import com.google.pubsub.v1.ProjectName; import com.google.pubsub.v1.PushConfig; import com.google.pubsub.v1.SchemaSettings; import com.google.pubsub.v1.Subscription; import com.google.pubsub.v1.SubscriptionName; import com.google.pubsub.v1.TopicName; import java.io.IOException; public class CreateBigQuerySubscriptionExample { public static void createBigQuerySubscription( String projectId, String topicId, String subscriptionId, String datasetId) throws IOException { // TODO(developer): Replace these variables before running the sample. // projectId = "your-project-id"; // topicId = "your-topic-id"; // subscriptionId = "your-subscription-id"; // datasetId = "your-bigquery-dataset-id"; // Use Application Default Credentials (ADC) to authenticate. // See https://cloud.google.com/docs/authentication-overview#adc GoogleCredentials credentials = GoogleCredentials.getApplicationDefault(); SubscriptionAdminSettings subscriptionAdminSettings = SubscriptionAdminSettings.newBuilder() .setCredentialsProvider(FixedCredentialsProvider.create(credentials)) .build(); try ( SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create(subscriptionAdminSettings)) { TopicName topicName = TopicName.of(projectId, topicId); SubscriptionName subscriptionName = SubscriptionName.of(projectId, subscriptionId); // Configure the BigQuery subscription. Subscription subscription = Subscription.newBuilder() .setName(subscriptionName) .setTopic(topicName) .setEnableMessageOrdering(true) .setBigQueryConfig( Subscription.BigQueryConfig.newBuilder() .setDatasetId(datasetId) .build()) .build(); // Create the subscription. Subscription createdSubscription = subscriptionAdminClient.createSubscription(subscription); System.out.println("Subscription created: " + createdSubscription.getName()); } } } ``` -------------------------------- ### Create Avro Schema Example Source: https://github.com/googleapis/java-pubsub/blob/main/README.md Example demonstrating how to create an Avro schema in Pub/Sub. Ensure you have the necessary dependencies and authentication configured. ```java /* * Copyright 2023 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package pubsub; import com.google.api.gax.core.FixedCredentialsProvider; import com.google.auth.oauth2.GoogleCredentials; import com.google.cloud.pubsub.v1.SchemaServiceClient; import com.google.cloud.pubsub.v1.SchemaServiceSettings; import com.google.pubsub.v1.ProjectName; import com.google.pubsub.v1.Schema; import com.google.pubsub.v1.SchemaName; import java.io.IOException; public class CreateAvroSchemaExample { public static void createAvroSchema(String projectId, String schemaId) throws IOException { // TODO(developer): Replace these variables before running the sample. // projectId = "your-project-id"; // schemaId = "your-schema-id"; // Use Application Default Credentials (ADC) to authenticate. // See https://cloud.google.com/docs/authentication-overview#adc GoogleCredentials credentials = GoogleCredentials.getApplicationDefault(); SchemaServiceSettings schemaServiceSettings = SchemaServiceSettings.newBuilder() .setCredentialsProvider(FixedCredentialsProvider.create(credentials)) .build(); try (SchemaServiceClient schemaServiceClient = SchemaServiceClient.create(schemaServiceSettings)) { ProjectName projectName = ProjectName.of(projectId); SchemaName schemaName = SchemaName.of(projectId, schemaId); // Define the schema content. Schema schema = Schema.newBuilder() .setType(Schema.Type.AVRO) .setDefinition("{\"type\": \"record\", \"name\": \"AvroExample\", \"fields\": [{\"name\": \"f1\", \"type\": \"string\"}]}") .build(); // Create the schema. Schema createdSchema = schemaServiceClient.createSchema(projectName, schemaId, schema); System.out.println("Schema created: " + createdSchema.getName()); } } } ``` -------------------------------- ### Create Unwrapped Push Subscription Example (Java) Source: https://github.com/googleapis/java-pubsub/blob/main/README.md Demonstrates how to create a new push subscription that does not wrap messages. Ensure you have the necessary permissions and project setup. ```java /* * Copyright 2023 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package pubsub; import com.google.cloud.pubsub.v1.SubscriptionAdminClient; import com.google.cloud.pubsub.v1.TopicAdminClient; import com.google.cloud.pubsub.v1.TopicAdminSettings; import com.google.iam.v1.Binding; import com.google.iam.v1.Policy; import com.google.pubsub.v1.ProjectName; import com.google.pubsub.v1.PushConfig; import com.google.pubsub.v1.Subscription; import com.google.pubsub.v1.SubscriptionName; import com.google.pubsub.v1.TopicName; import java.io.IOException; import java.util.concurrent.TimeoutException; public class CreateUnwrappedPushSubscriptionExample { public static void main(String[] args) throws IOException, TimeoutException { // TODO(developer) - Replace these variables before running the sample: String projectId = "your-project-id"; String topicId = "your-topic-id"; String subscriptionId = "your-subscription-id"; String pushEndpoint = "https://your-domain.com/push"; createUnwrappedPushSubscriptionExample( projectId, topicId, subscriptionId, pushEndpoint); } public static void createUnwrappedPushSubscriptionExample( String projectId, String topicId, String subscriptionId, String pushEndpoint) throws IOException { // Initialize client that will be used to send requests. // See https://cloud.google.com/java/docs/setup for more information on how to initialize the client. try (TopicAdminClient topicAdminClient = TopicAdminClient.create()) { TopicName topicName = TopicName.of(projectId, topicId); SubscriptionName subscriptionName = SubscriptionName.of(projectId, subscriptionId); // Create a topic if it doesn't exist. try { topicAdminClient.getTopic(topicName); System.out.println("Topic " + topicId + " already exists."); } catch (Exception e) { topicAdminClient.createTopic(topicName); System.out.println("Topic " + topicId + " created."); } // Build the push configuration. PushConfig pushConfig = PushConfig.newBuilder().setPushEndpoint(pushEndpoint).build(); // Build the subscription with the push configuration. Subscription subscription = Subscription.newBuilder() .setName(subscriptionName.toString()) .setTopic(topicName.toString()) .setPushConfig(pushConfig) .build(); // Use SubscriptionAdminClient to create the subscription. try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) { subscriptionAdminClient.createSubscription(subscription); System.out.println("Unwrapped push subscription " + subscriptionId + " created."); } } } } ``` -------------------------------- ### Get Subscription Policy Example (Java) Source: https://github.com/googleapis/java-pubsub/blob/main/README.md Demonstrates how to retrieve the IAM policy for a subscription. This allows you to view who has what access to the subscription. ```java /* * Copyright 2023 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package pubsub; import com.google.cloud.pubsub.v1.SubscriptionAdminClient; import com.google.iam.v1.Policy; import com.google.pubsub.v1.SubscriptionName; import java.io.IOException; public class GetSubscriptionPolicyExample { public static void main(String[] args) throws IOException { // TODO(developer) - Replace these variables before running the sample: String projectId = "your-project-id"; String subscriptionId = "your-subscription-id"; getSubscriptionPolicyExample(projectId, subscriptionId); } public static void getSubscriptionPolicyExample(String projectId, String subscriptionId) throws IOException { // Initialize client that will be used to send requests. // See https://cloud.google.com/java/docs/setup for more information on how to initialize the client. try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) { SubscriptionName subscriptionName = SubscriptionName.of(projectId, subscriptionId); Policy policy = subscriptionAdminClient.getIamPolicy(subscriptionName.toString()); System.out.println("Subscription policy retrieved for: " + subscriptionName); System.out.println("Policy Etag: " + policy.getEtag()); System.out.println("Bindings:"); for (com.google.iam.v1.Binding binding : policy.getBindingsList()) { System.out.println(" Role: " + binding.getRole()); System.out.println(" Members: " + binding.getMembersList()); } } } } ``` -------------------------------- ### List Schemas Example (Java) Source: https://github.com/googleapis/java-pubsub/blob/main/README.md Demonstrates how to list all schemas in a project. This operation retrieves a paginated list of schemas. ```java /* * Copyright 2023 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package pubsub; import com.google.cloud.pubsub.v1.SchemaAdminClient; import com.google.pubsub.v1.ListSchemasRequest; import com.google.pubsub.v1.Schema; import com.google.pubsub.v1.ProjectName; import java.io.IOException; public class ListSchemasExample { public static void main(String[] args) throws IOException { // TODO(developer) - Replace these variables before running the sample: String projectId = "your-project-id"; listSchemasExample(projectId); } public static void listSchemasExample(String projectId) throws IOException { // Initialize client that will be used to send requests. // See https://cloud.google.com/java/docs/setup for more information on how to initialize the client. try (SchemaAdminClient schemaAdminClient = SchemaAdminClient.create()) { ProjectName projectName = ProjectName.of(projectId); ListSchemasRequest listSchemasRequest = ListSchemasRequest.newBuilder() .setProject(projectName.toString()) .build(); System.out.println("Schemas in project: " + projectId); for (Schema schema : schemaAdminClient.listSchemas(listSchemasRequest).iterateAll()) { System.out.println("Schema: " + schema.getName()); System.out.println("Schema type: " + schema.getType()); System.out.println("Schema definition: " + schema.getDefinition()); } } } } ``` -------------------------------- ### List Topics Example Source: https://github.com/googleapis/java-pubsub/blob/main/README.md Demonstrates how to list all topics within a Google Cloud project using the Java client library. ```java /* * Copyright 2024 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package pubsub; import com.google.cloud.pubsub.v1.TopicAdminClient; import com.google.pubsub.v1.ProjectName; import com.google.pubsub.v1.TopicName; import java.io.IOException; public class ListTopicsExample { public static void listTopicsExample(String projectId) throws IOException { // Initialize client that will be used to send requests. // This client only needs to be created once, and can be reused for multiple requests. try (TopicAdminClient topicAdminClient = TopicAdminClient.create()) { ProjectName projectName = ProjectName.of(projectId); // set page size to limit the number of topics returned per page // set page token to retrieve the next page of topics for (TopicName topic : topicAdminClient.listTopics(projectName).iterateAll()) { System.out.println("Topic: " + topic.getTopic()); } System.out.println("Listed all topics in project " + projectId); } } public static void main(String[] args) throws IOException { if (args.length != 1) { System.err.println("Usage: ListTopicsExample "); return; } String projectId = args[0]; listTopicsExample(projectId); } } ``` -------------------------------- ### Commit Proto Schema Example Source: https://github.com/googleapis/java-pubsub/blob/main/README.md Example demonstrating how to commit a Protocol Buffer schema to Pub/Sub. Ensure you have the necessary dependencies and authentication configured. ```java /* * Copyright 2023 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package pubsub; import com.google.api.gax.core.FixedCredentialsProvider; import com.google.auth.oauth2.GoogleCredentials; import com.google.cloud.pubsub.v1.SchemaServiceClient; import com.google.cloud.pubsub.v1.SchemaServiceSettings; import com.google.pubsub.v1.ProjectName; import com.google.pubsub.v1.Schema; import com.google.pubsub.v1.SchemaName; import java.io.IOException; public class CommitProtoSchemaExample { public static void commitProtoSchema(String projectId, String schemaId) throws IOException { // TODO(developer): Replace these variables before running the sample. // projectId = "your-project-id"; // schemaId = "your-schema-id"; // Use Application Default Credentials (ADC) to authenticate. // See https://cloud.google.com/docs/authentication-overview#adc GoogleCredentials credentials = GoogleCredentials.getApplicationDefault(); SchemaServiceSettings schemaServiceSettings = SchemaServiceSettings.newBuilder() .setCredentialsProvider(FixedCredentialsProvider.create(credentials)) .build(); try (SchemaServiceClient schemaServiceClient = SchemaServiceClient.create(schemaServiceSettings)) { ProjectName projectName = ProjectName.of(projectId); SchemaName schemaName = SchemaName.of(projectId, schemaId); // Define the schema content. Schema schema = Schema.newBuilder() .setType(Schema.Type.PROTOCOL_BUFFER) .setDefinition("syntax = \"proto3\";\n\nmessage Hello {\n string message = 1;\n}") .build(); // Commit the schema. Schema committedSchema = schemaServiceClient.createSchema(projectName, schemaId, schema); System.out.println("Schema committed: " + committedSchema.getName()); } } } ``` -------------------------------- ### Subscribe Async Example - Java Source: https://github.com/googleapis/java-pubsub/blob/main/README.md Demonstrates how to subscribe to messages asynchronously. Ensure you have the necessary Pub/Sub client library dependencies. ```java /* * Copyright 2024 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package pubsub; import com.google.cloud.pubsub.v1.AckReplyConsumer; import com.google.cloud.pubsub.v1.MessageReceiver; import com.google.cloud.pubsub.v1.Subscriber; import com.google.cloud.pubsub.v1.SubscriptionAdminClient; import com.google.pubsub.v1.ProjectSubscriptionName; import com.google.pubsub.v1.Subscription; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; public class SubscribeAsyncExample { // use pull subscription to receive messages public static void main(String[] args) throws Exception { ProjectSubscriptionName subscriptionName = ProjectSubscriptionName.of(args[0], args[1]); // TODO(developer) - Replace these variables before running the sample: // String projectId = "your-project-id"; // String subscriptionId = "your-subscription-id"; // Instantiate an asynchronous MessageReceiver to handle incoming messages. MessageReceiver receiver = (pubsubMessage, ackReplyConsumer) -> { String data = pubsubMessage.getData().toStringUtf8(); System.out.println("Message : " + data); // Acknowledge the message. If you do not acknowledge the message, it will be // redelivered according to the subscription's backoff policy. ackReplyConsumer.ack(); }; Subscriber subscriber = null; try { // Create a subscriber instance with the subscription name and MessageReceiver. subscriber = Subscriber.newBuilder(subscriptionName, receiver).build(); // Start the subscriber. subscriber.startAsync().awaitRunning(); System.out.println("Listening for messages on " + subscriptionName); // Example of how to stop the subscriber. In a real application, this would // typically be in response to a shutdown signal. // subscriber.stopAsync().awaitTerminated(1, TimeUnit.MINUTES); } catch (TimeoutException timeoutException) { // Stop subscriber in case of an unexpected exception. if (subscriber != null) { subscriber.stopAsync(); } throw timeoutException; } } // SubscribeAsyncExample.java public static void subscribeAsync(String projectId, String subscriptionId) { ProjectSubscriptionName subscriptionName = ProjectSubscriptionName.of(projectId, subscriptionId); // Instantiate an asynchronous MessageReceiver to handle incoming messages. MessageReceiver receiver = (pubsubMessage, ackReplyConsumer) -> { String data = pubsubMessage.getData().toStringUtf8(); System.out.println("Message : " + data); // Acknowledge the message. If you do not acknowledge the message, it will be // redelivered according to the subscription's backoff policy. ackReplyConsumer.ack(); }; Subscriber subscriber = null; try { // Create a subscriber instance with the subscription name and MessageReceiver. subscriber = Subscriber.newBuilder(subscriptionName, receiver).build(); // Start the subscriber. subscriber.startAsync().awaitRunning(); System.out.println("Listening for messages on " + subscriptionName); // Example of how to stop the subscriber. In a real application, this would // typically be in response to a shutdown signal. // subscriber.stopAsync().awaitTerminated(1, TimeUnit.MINUTES); } catch (TimeoutException timeoutException) { // Stop subscriber in case of an unexpected exception. if (subscriber != null) { subscriber.stopAsync(); } throw timeoutException; } } } ``` -------------------------------- ### List Subscriptions in Project Example Source: https://github.com/googleapis/java-pubsub/blob/main/README.md Demonstrates how to list all subscriptions within a Google Cloud project using the Java client library. ```java /* * Copyright 2024 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package pubsub; import com.google.cloud.pubsub.v1.SubscriptionAdminClient; import com.google.pubsub.v1.ProjectName; import com.google.pubsub.v1.ProjectSubscriptionName; import java.io.IOException; public class ListSubscriptionsInProjectExample { public static void listSubscriptionsInProjectExample(String projectId) throws IOException { // Initialize client that will be used to send requests. // This client only needs to be created once, and can be reused for multiple requests. try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) { ProjectName projectName = ProjectName.of(projectId); // set page size to limit the number of subscriptions returned per page // set page token to retrieve the next page of subscriptions for (ProjectSubscriptionName subscription : subscriptionAdminClient.listSubscriptions(projectName).iterateAll()) { System.out.println("Subscription: " + subscription.getSubscription()); } System.out.println("Listed all subscriptions in project " + projectId); } } public static void main(String[] args) throws IOException { if (args.length != 1) { System.err.println("Usage: ListSubscriptionsInProjectExample "); return; } String projectId = args[0]; listSubscriptionsInProjectExample(projectId); } } ``` -------------------------------- ### Create Subscription With Dead Letter Policy Example Source: https://github.com/googleapis/java-pubsub/blob/main/README.md Example demonstrating how to create a Pub/Sub subscription with a dead-letter policy. This ensures messages that cannot be processed are sent to a designated topic. Ensure you have the necessary dependencies and authentication configured. ```java /* * Copyright 2023 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package pubsub; import com.google.api.gax.core.FixedCredentialsProvider; import com.google.auth.oauth2.GoogleCredentials; import com.google.cloud.pubsub.v1.SubscriptionAdminClient; import com.google.cloud.pubsub.v1.SubscriptionAdminSettings; import com.google.pubsub.v1.DeadLetterPolicy; import com.google.pubsub.v1.ProjectName; import com.google.pubsub.v1.SchemaSettings; import com.google.pubsub.v1.Subscription; import com.google.pubsub.v1.SubscriptionName; import com.google.pubsub.v1.TopicName; import java.io.IOException; public class CreateSubscriptionWithDeadLetterPolicyExample { public static void createSubscriptionWithDeadLetterPolicy( String projectId, String topicId, String subscriptionId, String deadLetterTopicId) throws IOException { // TODO(developer): Replace these variables before running the sample. // projectId = "your-project-id"; // topicId = "your-topic-id"; // subscriptionId = "your-subscription-id"; // deadLetterTopicId = "your-dead-letter-topic-id"; // Use Application Default Credentials (ADC) to authenticate. // See https://cloud.google.com/docs/authentication-overview#adc GoogleCredentials credentials = GoogleCredentials.getApplicationDefault(); SubscriptionAdminSettings subscriptionAdminSettings = SubscriptionAdminSettings.newBuilder() .setCredentialsProvider(FixedCredentialsProvider.create(credentials)) .build(); try ( SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create(subscriptionAdminSettings)) { TopicName topicName = TopicName.of(projectId, topicId); SubscriptionName subscriptionName = SubscriptionName.of(projectId, subscriptionId); TopicName deadLetterTopicName = TopicName.of(projectId, deadLetterTopicId); // Configure the dead-letter policy. DeadLetterPolicy deadLetterPolicy = DeadLetterPolicy.newBuilder() .setDeadLetterTopic(deadLetterTopicName.toString()) .setMaxDeliveryAttempts(10) .build(); Subscription subscription = Subscription.newBuilder() .setName(subscriptionName) .setTopic(topicName) .setDeadLetterPolicy(deadLetterPolicy) .setEnableMessageOrdering(true) .build(); // Create the subscription. Subscription createdSubscription = subscriptionAdminClient.createSubscription(subscription); System.out.println("Subscription created: " + createdSubscription.getName()); } } } ``` -------------------------------- ### Test Subscription Permissions Example (Java) Source: https://github.com/googleapis/java-pubsub/blob/main/README.md Demonstrates how to test permissions for a Pub/Sub subscription using the Java client library. ```java /* * Copyright 2023 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package pubsub; import com.google.cloud.pubsub.v1.SubscriptionAdminClient; import com.google.iam.v1.TestIamPermissionsRequest; import com.google.iam.v1.TestIamPermissionsResponse; import java.io.IOException; import java.util.Arrays; import java.util.HashSet; import java.util.Set; public class TestSubscriptionPermissionsExample { public static void testSubscriptionPermissions() throws IOException { // TODO(developer) - Replace these variables before running the sample: // String projectId = "your-project-id"; // String subscriptionId = "your-subscription-id"; String projectId = "your-project-id"; String subscriptionId = "your-subscription-id"; try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) { String subscriptionName = String.format( "projects/%s/subscriptions/%s", projectId, subscriptionId); Set permissions = new HashSet<>(Arrays.asList("pubsub.subscriptions.consume", "pubsub.subscriptions.update")); TestIamPermissionsRequest request = TestIamPermissionsRequest.newBuilder() .setResource(subscriptionName) .addAllPermissions(permissions) .build(); TestIamPermissionsResponse response = subscriptionAdminClient.testIamPermissions(request); System.out.println("Permissions granted:"); for (String permission : response.getPermissionsList()) { System.out.println(permission); } } } } ``` -------------------------------- ### Test Topic Permissions Example (Java) Source: https://github.com/googleapis/java-pubsub/blob/main/README.md Demonstrates how to test permissions for a Pub/Sub topic using the Java client library. ```java /* * Copyright 2023 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package pubsub; import com.google.cloud.pubsub.v1.TopicAdminClient; import com.google.iam.v1.TestIamPermissionsRequest; import com.google.iam.v1.TestIamPermissionsResponse; import java.io.IOException; import java.util.Arrays; import java.util.HashSet; import java.util.Set; public class TestTopicPermissionsExample { public static void testTopicPermissions() throws IOException { // TODO(developer) - Replace these variables before running the sample: // String projectId = "your-project-id"; // String topicId = "your-topic-id"; String projectId = "your-project-id"; String topicId = "your-topic-id"; try (TopicAdminClient topicAdminClient = TopicAdminClient.create()) { String topicName = String.format("projects/%s/topics/%s", projectId, topicId); Set permissions = new HashSet<>(Arrays.asList("pubsub.topics.publish", "pubsub.topics.update")); TestIamPermissionsRequest request = TestIamPermissionsRequest.newBuilder() .setResource(topicName) .addAllPermissions(permissions) .build(); TestIamPermissionsResponse response = topicAdminClient.testIamPermissions(request); System.out.println("Permissions granted:"); for (String permission : response.getPermissionsList()) { System.out.println(permission); } } } } ``` -------------------------------- ### Get Schema Example (Java) Source: https://github.com/googleapis/java-pubsub/blob/main/README.md Demonstrates how to retrieve a schema. This operation retrieves the schema's definition and metadata. ```java /* * Copyright 2023 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package pubsub; import com.google.cloud.pubsub.v1.SchemaAdminClient; import com.google.pubsub.v1.GetSchemaRequest; import com.google.pubsub.v1.Schema; import com.google.pubsub.v1.SchemaName; import java.io.IOException; public class GetSchemaExample { public static void main(String[] args) throws IOException { // TODO(developer) - Replace these variables before running the sample: String projectId = "your-project-id"; String schemaId = "your-schema-id"; getSchemaExample(projectId, schemaId); } public static void getSchemaExample(String projectId, String schemaId) throws IOException { // Initialize client that will be used to send requests. // See https://cloud.google.com/java/docs/setup for more information on how to initialize the client. try (SchemaAdminClient schemaAdminClient = SchemaAdminClient.create()) { SchemaName schemaName = SchemaName.of(projectId, schemaId); GetSchemaRequest getSchemaRequest = GetSchemaRequest.newBuilder() .setSchema(schemaName.toString()) .build(); Schema schema = schemaAdminClient.getSchema(getSchemaRequest); System.out.println("Schema retrieved: " + schema.getName()); System.out.println("Schema type: " + schema.getType()); System.out.println("Schema definition: " + schema.getDefinition()); } } } ```