### Quickstart Example for Java Logging Source: https://github.com/googleapis/google-cloud-java/blob/main/java-logging-logback/README.md A basic example demonstrating how to get started with Java logging. This snippet is useful for initial setup and understanding core functionality. ```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 com.example.logging.logback; import ch.qos.logback.classic.Logger; import ch.qos.logback.classic.LoggerContext; import ch.qos.logback.classic.encoder.PatternLayoutEncoder; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.Appender; import ch.qos.logback.core.ConsoleAppender; import ch.qos.logback.core.FileAppender; import ch.qos.logback.core.rolling.RollingFileAppender; import ch.qos.logback.core.rolling.TimeBasedRollingPolicy; /** * Sample showing how to use the Logback appender for Cloud Logging. */ public class Quickstart { public static void main(String[] args) { // Use the root logger Logger rootLogger = (Logger) org.slf4j.LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME); LoggerContext loggerContext = rootLogger.getLoggerContext(); // Clear all existing appenders rootLogger.detachAndStopAllAppenders(); // Create a ConsoleAppender ConsoleAppender consoleAppender = new ConsoleAppender<>(); consoleAppender.setContext(loggerContext); consoleAppender.setName("console"); // Create a PatternLayoutEncoder for the console appender PatternLayoutEncoder encoder = new PatternLayoutEncoder(); encoder.setContext(loggerContext); encoder.setPattern("%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n"); encoder.start(); consoleAppender.setEncoder(encoder); consoleAppender.start(); // Add the console appender to the root logger rootLogger.addAppender(consoleAppender); // Create a FileAppender FileAppender fileAppender = new FileAppender<>(); fileAppender.setContext(loggerContext); fileAppender.setName("file"); fileAppender.setFile("output.log"); fileAppender.setEncoder(encoder); fileAppender.start(); // Add the file appender to the root logger rootLogger.addAppender(fileAppender); // Create a RollingFileAppender RollingFileAppender rollingFileAppender = new RollingFileAppender<>(); rollingFileAppender.setContext(loggerContext); rollingFileAppender.setName("rolling-file"); rollingFileAppender.setFile("rolling-output.log"); rollingFileAppender.setEncoder(encoder); // Setup rolling policy TimeBasedRollingPolicy rollingPolicy = new TimeBasedRollingPolicy<>(); rollingPolicy.setContext(loggerContext); rollingPolicy.setFileNamePattern("rolling-output.%d{yyyy-MM-dd}.log"); rollingPolicy.setMaxHistory(7); rollingPolicy.setParent(rollingFileAppender); rollingPolicy.start(); rollingFileAppender.setRollingPolicy(rollingPolicy); rollingFileAppender.start(); // Add the rolling file appender to the root logger rootLogger.addAppender(rollingFileAppender); // Log messages rootLogger.debug("This is a debug message."); rootLogger.info("This is an info message."); rootLogger.warn("This is a warning message."); rootLogger.error("This is an error message."); } } ``` -------------------------------- ### Quickstart Example - Java Source: https://github.com/googleapis/google-cloud-java/blob/main/java-bigtable/README.md A quickstart guide for Bigtable. It covers basic setup and operations like creating a table, writing data, and reading data. ```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 com.example.bigtable; import com.google.cloud.bigtable.data.v2.BigtableDataClient; import com.google.cloud.bigtable.data.v2.models.Row; import com.google.cloud.bigtable.data.v2.models.RowMutation; import com.google.cloud.bigtable.data.v2.models.TableId; import java.io.IOException; public class Quickstart { /** * A quickstart guide for Bigtable. It covers basic setup and operations like creating a table, * writing data, and reading data. * * @param projectId The Google Cloud project ID. * @param instanceId The Bigtable instance ID. * @param tableId The Bigtable table ID. * @throws IOException if an error occurs during client initialization. */ public static void quickstart(String projectId, String instanceId, String tableId) throws IOException { // [START bigtable_quickstart] try (BigtableDataClient dataClient = BigtableDataClient.create(projectId, instanceId)) { String rowKey = "quickstart-row"; String columnFamily = "cf1"; String columnQualifier = "greeting"; String value = "Hello Bigtable!"; // Write a row to the table. RowMutation rowMutation = RowMutation.create(TableId.of(tableId), rowKey) .setCell(columnFamily, columnQualifier, value); dataClient.mutateRow(rowMutation); System.out.println("Wrote row: " + rowKey); // Read the row from the table. Row row = dataClient.readRow(TableId.of(tableId), rowKey); if (row != null) { System.out.println("Read row: " + row.getKey()); row.getCells().forEach(cell -> System.out.printf(" Cell: %s:%s @ %d = %s\n", cell.getFamily(), cell.getQualifier(), cell.getTimestamp(), cell.getValue())); } else { System.out.println("Row \"%s\" not found.\n".formatted(rowKey)); } } // [END bigtable_quickstart] } public static void main(String[] args) throws IOException { // TODO(developer): // Replace these variable values with your own: String projectId = "your-project-id"; String instanceId = "your-instance-id"; String tableId = "your-table-id"; quickstart(projectId, instanceId, tableId); } } ``` -------------------------------- ### Firestore Quickstart Example Source: https://github.com/googleapis/google-cloud-java/blob/main/java-firestore/README.md A basic example to get started with Firestore operations in Java. This is a good starting point for new users. ```java /** * This sample demonstrates basic Firestore operations. */ public class Quickstart { public static void main(String[] args) throws Exception { // TODO(developer): // Insert your code here } } ``` -------------------------------- ### Quickstart Sample Source: https://github.com/googleapis/google-cloud-java/blob/main/java-spanner/README.md A basic quickstart sample to get started with Google Cloud Spanner using Java. ```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 com.example.spanner; import com.google.cloud.spanner.DatabaseId; import com.google.cloud.spanner.Spanner; import com.google.cloud.spanner.SpannerOptions; import com.google.cloud.spanner.Statement; import com.google.cloud.spanner.ResultSet; public class QuickstartSample { // Use a try-with-resources statement to ensure that the Spanner client is // closed after use. public static void quickstartSample() { // TODO(developer): Replace these variables before running the sample. String projectId = "your-project-id"; String instanceId = "your-instance-id"; String databaseId = "your-database-id"; SpannerOptions options = SpannerOptions.newBuilder().build(); try (Spanner spanner = options.getService()) { DatabaseId db = DatabaseId.of(projectId, instanceId, databaseId); System.out.println("Using database: " + db); // Example: Execute a simple query. try (ResultSet resultSet = spanner.getDatabaseClient(db).singleUse().executeQuery( Statement.newBuilder("SELECT 1").build())) { while (resultSet.next()) { System.out.println("Query result: " + resultSet.getLong(0)); } } } } } ``` -------------------------------- ### Quickstart Sample for Google Cloud Storage Source: https://github.com/googleapis/google-cloud-java/blob/main/java-storage/README.md A basic quickstart sample for Google Cloud Storage operations. This is a good starting point for new users. ```java /* * Copyright 2022 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 com.example.storage; import com.google.cloud.storage.Storage; import com.google.cloud.storage.StorageOptions; import java.io.IOException; public class QuickstartSample { public static void quickstart() throws IOException { // [START storage_quickstart] // This example requires the google-cloud-storage library to be added to your project. // See https://cloud.google.com/java/docs/setup // Initialize client that will be used to send requests. This client only needs to be created // once, and an application can reuse it for all requests. Storage storage = StorageOptions.newBuilder().build().getService(); // The name of the bucket to create String bucketName = "your-unique-bucket-name"; System.out.println("Bucket " + bucketName + " created."); // [END storage_quickstart] } public static void main(String[] args) throws IOException { quickstart(); } } ``` -------------------------------- ### Install Showcase Server with Go Source: https://github.com/googleapis/google-cloud-java/blob/main/sdk-platform-java/AGENTS.md Install the Showcase server binary using Go's install command. Ensure Go is installed and configured in your PATH. ```sh go install github.com/googleapis/gapic-showcase/cmd/gapic-showcase@latest ``` -------------------------------- ### Quickstart gRPC DirectPath Sample for Google Cloud Storage Source: https://github.com/googleapis/google-cloud-java/blob/main/java-storage/README.md A quickstart sample demonstrating the use of gRPC with DirectPath for Google Cloud Storage operations. This sample requires specific setup for gRPC. ```java /* * Copyright 2022 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 com.example.storage; import com.google.cloud.storage.Storage; import com.google.cloud.storage.StorageOptions; import java.io.IOException; public class QuickstartGrpcDpSample { public static void quickstart() throws IOException { // [START storage_quickstart_grpc_dp] // This example requires the google-cloud-storage library to be added to your project. // See https://cloud.google.com/java/docs/setup // Initialize client that will be used to send requests. This client only needs to be created // once, and an application can reuse it for all requests. Storage storage = StorageOptions.newBuilder().build().getService(); // The name of the bucket to create String bucketName = "your-unique-bucket-name"; System.out.println("Bucket " + bucketName + " created using gRPC DirectPath."); // [END storage_quickstart_grpc_dp] } public static void main(String[] args) throws IOException { quickstart(); } } ``` -------------------------------- ### Quickstart gRPC Sample for Google Cloud Storage Source: https://github.com/googleapis/google-cloud-java/blob/main/java-storage/README.md A quickstart sample demonstrating basic Google Cloud Storage operations using gRPC. Ensure gRPC is enabled in your project setup. ```java /* * Copyright 2022 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 com.example.storage; import com.google.cloud.storage.Storage; import com.google.cloud.storage.StorageOptions; import java.io.IOException; public class QuickstartGrpcSample { public static void quickstart() throws IOException { // [START storage_quickstart_grpc] // This example requires the google-cloud-storage library to be added to your project. // See https://cloud.google.com/java/docs/setup // Initialize client that will be used to send requests. This client only needs to be created // once, and an application can reuse it for all requests. Storage storage = StorageOptions.newBuilder().build().getService(); // The name of the bucket to create String bucketName = "your-unique-bucket-name"; System.out.println("Bucket " + bucketName + " created using gRPC."); // [END storage_quickstart_grpc] } public static void main(String[] args) throws IOException { quickstart(); } } ``` -------------------------------- ### Quickstart Sample Source: https://github.com/googleapis/google-cloud-java/blob/main/java-logging/README.md A basic quickstart sample for Cloud Logging. This demonstrates writing a simple log entry. Ensure your project ID is 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 * * 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 com.example.logging; import com.google.cloud.logging.LogEntry; import com.google.cloud.logging.Logging; import com.google.cloud.logging.LoggingOptions; import com.google.cloud.logging.Payload; import com.google.cloud.logging.Severity; /** * A simple quickstart sample for Cloud Logging. */ public class QuickstartSample { public static void main(String[] args) throws Exception { // TODO(developer): Set these values before running the sample. // String projectId = "your-project-id"; // Logging logging = LoggingOptions.newBuilder().setProjectId(projectId).build().getService(); Logging logging = LoggingOptions.getDefaultInstance().getService(); LogEntry entry = LogEntry.newBuilder(Payload.textOf("Hello, world!")) .setSeverity(Severity.INFO) .build(); logging.write(entry); System.out.println("Log entry written."); } } ``` -------------------------------- ### Create Push Subscription Example Source: https://github.com/googleapis/google-cloud-java/blob/main/java-pubsub/README.md Example demonstrating how to create a push subscription in Google Cloud Pub/Sub. ```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.Subscription; import com.google.pubsub.v1.SubscriptionName; import com.google.pubsub.v1.TopicName; import java.io.IOException; public class CreatePushSubscriptionExample { public static void createPushSubscription() throws IOException { // 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-cloud-function-url"; createPushSubscription(projectId, topicId, subscriptionId, pushEndpoint); } public static void createPushSubscription( String projectId, String topicId, String subscriptionId, String pushEndpoint) throws IOException { // Use default credentials. For more information, see // https://cloud.google.com/docs/authentication/provide-credentials-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.toString()) .setTopic(topicName.toString()) .setPushConfig(pushConfig) .setEnableMessageOrdering(true) .build(); Subscription response = subscriptionAdminClient.createSubscription(subscription); System.out.println("Subscription created: " + response.getName()); } } } ``` -------------------------------- ### Install Java and Maven on Ubuntu Source: https://github.com/googleapis/google-cloud-java/blob/main/java-spanner-jdbc/samples/quickperf/readme.md Installs OpenJDK 8 and Maven on an Ubuntu system. These are prerequisites for running QuickPerf. ```bash sudo apt-get install openjdk-8-jdk sudo apt install maven ``` -------------------------------- ### Install Showcase Server Source: https://github.com/googleapis/google-cloud-java/blob/main/java-showcase/README.md Installs the showcase server using Go. Ensure Go is in your PATH. The version is determined by the pom.xml. ```shell cd java-showcase go install github.com/googleapis/gapic-showcase/cmd/gapic-showcase@v"$(cd gapic-showcase;mvn help:evaluate -Dexpression=gapic-showcase.version -q -DforceStdout |sed 's/\\|b\[[0-9;]*m//g')" PATH=$PATH:`go env GOPATH`/bin gapic-showcase --help ``` -------------------------------- ### Quickstart OpenTelemetry Sample for Google Cloud Storage Source: https://github.com/googleapis/google-cloud-java/blob/main/java-storage/README.md Demonstrates integrating Google Cloud Storage operations with OpenTelemetry for distributed tracing. Requires OpenTelemetry setup. ```java /* * Copyright 2022 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 com.example.storage; import com.google.cloud.storage.Storage; import com.google.cloud.storage.StorageOptions; import java.io.IOException; public class QuickstartOpenTelemetrySample { public static void quickstart() throws IOException { // [START storage_quickstart_open_telemetry] // This example requires the google-cloud-storage library to be added to your project. // See https://cloud.google.com/java/docs/setup // and OpenTelemetry setup for your environment. // Initialize client that will be used to send requests. This client only needs to be created // once, and an application can reuse it for all requests. Storage storage = StorageOptions.newBuilder().build().getService(); // The name of the bucket to create String bucketName = "your-unique-bucket-name"; System.out.println("Bucket " + bucketName + " created with OpenTelemetry tracing enabled."); // [END storage_quickstart_open_telemetry] } public static void main(String[] args) throws IOException { quickstart(); } } ``` -------------------------------- ### Instance Admin Example - Java Source: https://github.com/googleapis/google-cloud-java/blob/main/java-bigtable/README.md Demonstrates how to manage Bigtable instances using the Admin client. This includes creating, getting, and listing instances. ```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 com.example.bigtable; import com.google.cloud.bigtable.admin.v2.BigtableInstanceAdminClient; import com.google.cloud.bigtable.admin.v2.models.Instance; import com.google.cloud.bigtable.admin.v2.models.Instance.Type; import com.google.cloud.bigtable.admin.v2.models.ListInstancesRequest; import com.google.cloud.bigtable.admin.v2.models.ListInstancesResponse; import java.io.IOException; import java.util.concurrent.ExecutionException; public class InstanceAdminExample { /** * Creates a Bigtable instance. * * @param projectId The Google Cloud project ID. * @param instanceId The ID of the instance to create. * @param displayName The display name for the instance. * @throws IOException if an error occurs during client initialization. * @throws ExecutionException if an error occurs during the asynchronous operation. * @throws InterruptedException if the operation is interrupted. */ public static void createInstance(String projectId, String instanceId, String displayName) throws IOException, ExecutionException, InterruptedException { try (BigtableInstanceAdminClient instanceAdminClient = BigtableInstanceAdminClient.create(projectId)) { Instance instance = Instance.newBuilder() .setId(instanceId) .setDisplayName(displayName) .setType(Type.DEVELOPMENT) // Use PRODUCTION for production environments .build(); instanceAdminClient.createInstance(instance).get(); System.out.println("Instance \"%s\" created.\n".formatted(instanceId)); } } /** * Gets a Bigtable instance. * * @param projectId The Google Cloud project ID. * @param instanceId The ID of the instance to get. * @throws IOException if an error occurs during client initialization. */ public static void getInstance(String projectId, String instanceId) throws IOException { try (BigtableInstanceAdminClient instanceAdminClient = BigtableInstanceAdminClient.create(projectId)) { Instance instance = instanceAdminClient.getInstance(instanceId); System.out.println("Instance details:\n%s\n".formatted(instance.toString())); } } /** * Lists all Bigtable instances in a project. * * @param projectId The Google Cloud project ID. * @throws IOException if an error occurs during client initialization. */ public static void listInstances(String projectId) throws IOException { try (BigtableInstanceAdminClient instanceAdminClient = BigtableInstanceAdminClient.create(projectId)) { ListInstancesRequest listInstancesRequest = ListInstancesRequest.of(); ListInstancesResponse response = instanceAdminClient.listInstances(listInstancesRequest); System.out.println("Instances in project \"%s\":\n".formatted(projectId)); for (Instance instance : response.getInstances()) { System.out.println(instance.toString()); } System.out.println(); } } /** * Deletes a Bigtable instance. * * @param projectId The Google Cloud project ID. * @param instanceId The ID of the instance to delete. * @throws IOException if an error occurs during client initialization. */ public static void deleteInstance(String projectId, String instanceId) throws IOException { try (BigtableInstanceAdminClient instanceAdminClient = BigtableInstanceAdminClient.create(projectId)) { instanceAdminClient.deleteInstance(instanceId); System.out.println("Instance \"%s\" deleted.\n".formatted(instanceId)); } } public static void main(String[] args) throws IOException, ExecutionException, InterruptedException { // TODO(developer): // Replace these variable values with your own: String projectId = "your-project-id"; String instanceId = "your-instance-id"; String displayName = "My Instance"; createInstance(projectId, instanceId, displayName); getInstance(projectId, instanceId); listInstances(projectId); deleteInstance(projectId, instanceId); } } ``` -------------------------------- ### Create BigQuery Subscription Example Source: https://github.com/googleapis/google-cloud-java/blob/main/java-pubsub/README.md Example demonstrating how to create a Pub/Sub subscription that exports messages to BigQuery. ```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 com.google.pubsub.v1.TopicSchemaSettings; import java.io.IOException; public class CreateBigQuerySubscriptionExample { public static void createBigQuerySubscription() throws IOException { // 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 datasetId = "your-bigquery-dataset-id"; String tableId = "your-bigquery-table-id"; createBigQuerySubscription( projectId, topicId, subscriptionId, datasetId, tableId); } public static void createBigQuerySubscription( String projectId, String topicId, String subscriptionId, String datasetId, String tableId) throws IOException { // Use default credentials. For more information, see // https://cloud.google.com/docs/authentication/provide-credentials-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. String writeDisposition = "WRITE_APPEND"; // or "WRITE_TRUNCATE" String useTopicSchema = "true"; // or "false" String dropUnknownFields = "true"; // or "false" Subscription subscription = Subscription.newBuilder() .setName(subscriptionName.toString()) .setTopic(topicName.toString()) .setEnableMessageOrdering(true) .setBigQueryConfig( Subscription.BigQueryConfig.newBuilder() .setDatasetId(datasetId) .setTableId(tableId) .setWriteDisposition(writeDisposition) .setUseTopicSchema(Boolean.parseBoolean(useTopicSchema)) .setDropUnknownFields(Boolean.parseBoolean(dropUnknownFields)) .build()) .build(); Subscription response = subscriptionAdminClient.createSubscription(subscription); System.out.println("Subscription created: " + response.getName()); } } } ``` -------------------------------- ### Datastore Quickstart Sample in Java Source: https://github.com/googleapis/google-cloud-java/blob/main/java-datastore/README.md A basic quickstart sample for Google Cloud Datastore in Java. It covers essential operations like creating entities and performing simple queries. ```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 com.example.datastore; import com.google.cloud.datastore.Datastore; import com.google.cloud.datastore.DatastoreOptions; import com.google.cloud.datastore.Entity; import com.google.cloud.datastore.Key; import com.google.cloud.datastore.KeyFactory; import com.google.cloud.datastore.Query; import com.google.cloud.datastore.QueryResults; import com.google.cloud.datastore.StringValue; import com.google.cloud.datastore.TimestampValue; import com.google.cloud.datastore.IncompleteKey; import com.google.cloud.datastore.Datastore.Query import com.google.cloud.datastore.Datastore.Query.Builder; import com.google.cloud.datastore.Datastore.Query.Filter; import com.google.cloud.datastore.Datastore.Query.Filter.Operator; import com.google.cloud.datastore.Datastore.Query.Order; import com.google.cloud.datastore.Datastore.Query.Order.Direction; import java.util.ArrayList; import java.util.List; public class QuickstartSample { public static void main(String[] args) { // TODO(developer): Replace these variables before running the sample. // String projectId = "your-project-id"; Datastore datastore = DatastoreOptions.newBuilder().setProjectId(/* projectId */ "your-project-id").build().getService(); KeyFactory keyFactory = datastore.newKeyFactory().setKind("Task"); // Create a Key for a new Task. IncompleteKey incompleteKey = keyFactory.newKey(); // Create a Task entity. Entity task = Entity.newBuilder(incompleteKey) .set("description", StringValue.newBuilder("Learn Cloud Datastore").setExcludeFromIndexes(true).build()) .set("created", TimestampValue.now()) .build(); // Save the Task entity. Entity savedTask = datastore.put(task); System.out.println("Saved task: " + savedTask.getKey().getName()); // Retrieve the Task entity. Entity fetchedTask = datastore.get(savedTask.getKey()); System.out.println("Fetched task description: " + fetchedTask.getString("description")); // Query for all Tasks. Query query = Query.newEntityQueryBuilder().setKind("Task").build(); QueryResults results = datastore.run(query); List tasks = new ArrayList<>(); results.forEach(tasks::add); System.out.println("Found " + tasks.size() + " tasks:"); for (Entity t : tasks) { System.out.println("- " + t.getKey().getName() + ": " + t.getTimestamp("created")); } // Delete the Task entity. datastore.delete(savedTask.getKey()); System.out.println("Deleted task: " + savedTask.getKey().getName()); datastore.close(); } } ``` -------------------------------- ### Create Cloud Storage Subscription Example Source: https://github.com/googleapis/google-cloud-java/blob/main/java-pubsub/README.md Example demonstrating how to create a Pub/Sub subscription that exports messages to Cloud Storage. ```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 com.google.pubsub.v1.TopicSchemaSettings; import java.io.IOException; public class CreateCloudStorageSubscriptionExample { public static void createCloudStorageSubscription() throws IOException { // 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 bucketName = "your-cloud-storage-bucket-name"; createCloudStorageSubscription(projectId, topicId, subscriptionId, bucketName); } public static void createCloudStorageSubscription( String projectId, String topicId, String subscriptionId, String bucketName) throws IOException { // Use default credentials. For more information, see // https://cloud.google.com/docs/authentication/provide-credentials-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. String avroSchemaName = "your-avro-schema-id"; // Optional: specify if using Avro schema String avroSchemaVersion = "your-avro-schema-version"; // Optional: specify if using Avro schema String useTopicSchema = "true"; // or "false" String dropUnknownFields = "true"; // or "false" Subscription subscription = Subscription.newBuilder() .setName(subscriptionName.toString()) .setTopic(topicName.toString()) .setCloudStorageConfig( Subscription.CloudStorageConfig.newBuilder() .setBucket(bucketName) .setAvroSchema(TopicSchemaSettings.newBuilder().setSchemaId(avroSchemaName).setSchemaVersion(avroSchemaVersion).build()) .setUseTopicSchema(Boolean.parseBoolean(useTopicSchema)) .setDropUnknownFields(Boolean.parseBoolean(dropUnknownFields)) .build()) .build(); Subscription response = subscriptionAdminClient.createSubscription(subscription); System.out.println("Subscription created: " + response.getName()); } } } ``` -------------------------------- ### Resource Manager Examples Source: https://github.com/googleapis/google-cloud-java/blob/main/google-cloud-examples/README.md Demonstrates operations for Google Cloud Resource Manager, including creating, listing, and getting project details. Replace 'your-project-id' with your actual project ID. ```bash target/appassembler/bin/ResourceManagerExample create your-project-id ``` ```bash target/appassembler/bin/ResourceManagerExample list ``` ```bash target/appassembler/bin/ResourceManagerExample get your-project-id ``` -------------------------------- ### Quickstart Sample for BigQuery Java Source: https://github.com/googleapis/google-cloud-java/blob/main/java-bigquery/README.md A basic quickstart sample demonstrating how to initialize the BigQuery client and perform a simple operation. Ensure you have the Google Cloud client libraries for Java configured. ```java import com.google.cloud.bigquery.BigQuery; import com.google.cloud.bigquery.BigQueryOptions; import com.google.cloud.bigquery.TableId; import com.google.cloud.bigquery.TableInfo; public class QuickstartSample { public static void main(String[] args) { // TODO(developer): Replace these variables before running the sample. String projectId = "your-project-id"; String datasetName = "your-dataset-name"; String tableName = "your-table-name"; // Initialize client that will be used to send requests matching the client's configuration. BigQuery bigquery = BigQueryOptions.newBuilder().setProjectId(projectId).build().getService(); TableId tableId = TableId.of(projectId, datasetName, tableName); TableInfo tableInfo = bigquery.getTable(tableId).getTableInfo(); System.out.println("BigQuery Java quickstart finished."); } } ``` -------------------------------- ### Create Subscription With Smt Example (Java) Source: https://github.com/googleapis/google-cloud-java/blob/main/java-pubsub/README.md This sample demonstrates creating a Pub/Sub subscription with an SMT (Structured Message Transformation) example. Consult Pub/Sub documentation for SMT details. ```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.api.gax.rpc.ApiException; import com.google.cloud.pubsub.v1.SubscriptionAdminClient; 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 java.io.IOException; public class CreateSubscriptionWithSmtExample { public static void createSubscriptionWithSmtExample( 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"; try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) { SubscriptionName subscriptionName = SubscriptionName.of(projectId, subscriptionId); ProjectName projectName = ProjectName.of(projectId); // Build the subscription with SMT configuration. Subscription subscription = { subscriptionAdminClient.createSubscription(Subscription.newBuilder() .setName(subscriptionName.toString()) .setTopic(topicId) .setAckDeadlineSeconds(20) .setPushConfig(PushConfig.newBuilder().build()) .build()) }; System.out.println("Created subscription: " + subscription.getName()); } } public static void main(String[] args) throws IOException { // TODO(developer): Replace these variables before running the sample. String projectId = System.getenv("GOOGLE_CLOUD_PROJECT"); String topicId = "your-topic-id"; String subscriptionId = "your-subscription-id"; if (projectId == null || projectId.isEmpty()) { System.err.println("Project ID not set. Set GOOGLE_CLOUD_PROJECT environment variable."); return; } try { createSubscriptionWithSmtExample(projectId, topicId, subscriptionId); } catch (ApiException e) { System.err.println("Failed to create the subscription: " + e.getMessage()); } } } ``` -------------------------------- ### Create Proto Schema Example Source: https://github.com/googleapis/google-cloud-java/blob/main/java-pubsub/README.md Example demonstrating how to create a Protocol Buffer schema in Google Cloud Pub/Sub. ```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 com.google.pubsub.v1.Schema.Type; import java.io.IOException; public class CreateProtoSchemaExample { public static void createProtoSchema() throws IOException { // TODO(developer): Replace these variables before running the sample. String projectId = "your-project-id"; String schemaId = "your-schema-id"; String schemaType = "PROTOBUF"; // or "AVRO" createProtoSchema(projectId, schemaId, schemaType); } public static void createProtoSchema(String projectId, String schemaId, String schemaType) throws IOException { // Use default credentials. For more information, see // https://cloud.google.com/docs/authentication/provide-credentials-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); Schema schema = Schema.newBuilder() .setSchema("syntax = \"proto3\";\nmessage MyMessage {\n string name = 1;\n}") .setType(Type.valueOf(schemaType)) .build(); Schema response = schemaServiceClient.createSchema(projectName, schemaId, schema); System.out.println("Schema created: " + response.getName()); } } } ``` -------------------------------- ### Create Avro Schema Example Source: https://github.com/googleapis/google-cloud-java/blob/main/java-pubsub/README.md Example demonstrating how to create an Avro schema in Google Cloud Pub/Sub. ```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 com.google.pubsub.v1.Schema.Type; import java.io.IOException; public class CreateAvroSchemaExample { public static void createAvroSchema() throws IOException { // TODO(developer): Replace these variables before running the sample. String projectId = "your-project-id"; String schemaId = "your-schema-id"; String schemaType = "AVRO"; // or "PROTOBUF" createAvroSchema(projectId, schemaId, schemaType); } public static void createAvroSchema(String projectId, String schemaId, String schemaType) throws IOException { // Use default credentials. For more information, see // https://cloud.google.com/docs/authentication/provide-credentials-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); Schema schema = Schema.newBuilder() .setSchema("{\"type\": \"record\", \"name\": \"MyRecord\", \"fields\": [{\"name\": \"f1\", \"type\": \"string\"}]}") .setType(Type.valueOf(schemaType)) .build(); Schema response = schemaServiceClient.createSchema(projectName, schemaId, schema); System.out.println("Schema created: " + response.getName()); } } } ```