diff --git a/developer-knowledge/README.md b/developer-knowledge/README.md new file mode 100644 index 00000000000..d77995fbb1c --- /dev/null +++ b/developer-knowledge/README.md @@ -0,0 +1,28 @@ +# Google Developer Knowledge API Java Samples + +This directory contains Java code samples demonstrating how to use the [Google Developer Knowledge API](https://developers.google.com/knowledge) client library (`com.google.cloud:google-cloud-developer-knowledge`). + +## Setup + +1. Enable the Developer Knowledge API on your Google Cloud project: + ```bash + gcloud services enable developerknowledge.googleapis.com + ``` + +2. Build with Maven: + ```bash + mvn clean compile + ``` + +## Samples + +* **[Search Document Chunks](src/main/java/developerknowledge/SearchDocumentChunks.java)**: Search public developer documentation chunks by query (`developerknowledge_search_document_chunks`). +* **[Get Document](src/main/java/developerknowledge/GetDocument.java)**: Retrieve a single documentation page with full markdown content (`developerknowledge_get_document`). +* **[Batch Get Documents](src/main/java/developerknowledge/BatchGetDocuments.java)**: Fetch multiple documentation pages in one call (`developerknowledge_batch_get_documents`). +* **[Answer Query](src/main/java/developerknowledge/AnswerQuery.java)**: Get a grounded, cited answer to a technical question (`developerknowledge_answer_query`). + +## Running Tests + +```bash +mvn test +``` diff --git a/developer-knowledge/pom.xml b/developer-knowledge/pom.xml new file mode 100644 index 00000000000..5b2e0ff69c2 --- /dev/null +++ b/developer-knowledge/pom.xml @@ -0,0 +1,59 @@ + + + 4.0.0 + + com.example.developerknowledge + developer-knowledge-samples + 1.0.0 + jar + Google Developer Knowledge Snippets + + + com.google.cloud.samples + shared-configuration + 1.2.0 + + + + 11 + 11 + UTF-8 + + + + + com.google.cloud + google-cloud-developer-knowledge + 0.3.0 + + + junit + junit + 4.13.2 + test + + + com.google.truth + truth + 1.4.2 + test + + + diff --git a/developer-knowledge/src/main/java/developerknowledge/AnswerQuery.java b/developer-knowledge/src/main/java/developerknowledge/AnswerQuery.java new file mode 100644 index 00000000000..aa831ec6ba9 --- /dev/null +++ b/developer-knowledge/src/main/java/developerknowledge/AnswerQuery.java @@ -0,0 +1,52 @@ +/* + * Copyright 2026 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 developerknowledge; + +// [START developerknowledge_answer_query] +import com.google.developers.knowledge.v1.AnswerQueryRequest; +import com.google.developers.knowledge.v1.AnswerQueryResponse; +import com.google.developers.knowledge.v1.DeveloperKnowledgeClient; +import java.io.IOException; + +public class AnswerQuery { + + public static void main(String[] args) throws IOException { + // TODO(developer): Replace these variables before running the sample. + String query = "How do I create a Google Cloud Storage bucket?"; + answerQuery(query); + } + + // Answers a developer question grounded in Google developer documentation. + public static AnswerQueryResponse answerQuery(String query) 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. After completing all of your requests, call + // the "close" method on the client to safely clean up any remaining background resources. + try (DeveloperKnowledgeClient client = DeveloperKnowledgeClient.create()) { + AnswerQueryRequest request = + AnswerQueryRequest.newBuilder().setQuery(query).build(); + + AnswerQueryResponse response = client.answerQuery(request); + + System.out.println("Answer:\n" + response.getAnswer().getAnswerText() + "\n"); + System.out.println("Citations count: " + response.getAnswer().getCitationsCount()); + System.out.println("References count: " + response.getAnswer().getReferencesCount()); + + return response; + } + } +} +// [END developerknowledge_answer_query] diff --git a/developer-knowledge/src/main/java/developerknowledge/BatchGetDocuments.java b/developer-knowledge/src/main/java/developerknowledge/BatchGetDocuments.java new file mode 100644 index 00000000000..8e87619c872 --- /dev/null +++ b/developer-knowledge/src/main/java/developerknowledge/BatchGetDocuments.java @@ -0,0 +1,60 @@ +/* + * Copyright 2026 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 developerknowledge; + +// [START developerknowledge_batch_get_documents] +import com.google.developers.knowledge.v1.BatchGetDocumentsRequest; +import com.google.developers.knowledge.v1.BatchGetDocumentsResponse; +import com.google.developers.knowledge.v1.DeveloperKnowledgeClient; +import com.google.developers.knowledge.v1.Document; +import java.io.IOException; +import java.util.Arrays; +import java.util.List; + +public class BatchGetDocuments { + + public static void main(String[] args) throws IOException { + // TODO(developer): Replace these variables before running the sample. + List names = + Arrays.asList( + "documents/docs.cloud.google.com/storage/docs/creating-buckets", + "documents/docs.cloud.google.com/storage/docs/deleting-buckets"); + batchGetDocuments(names); + } + + // Retrieves multiple developer documentation pages in a single request. + public static BatchGetDocumentsResponse batchGetDocuments(List names) 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. After completing all of your requests, call + // the "close" method on the client to safely clean up any remaining background resources. + try (DeveloperKnowledgeClient client = DeveloperKnowledgeClient.create()) { + BatchGetDocumentsRequest request = + BatchGetDocumentsRequest.newBuilder().addAllNames(names).build(); + + BatchGetDocumentsResponse response = client.batchGetDocuments(request); + + for (Document doc : response.getDocumentsList()) { + System.out.println("Title: " + doc.getTitle()); + System.out.println("URI: " + doc.getUri()); + System.out.println("Content Length: " + doc.getContentLengthBytes() + " bytes\n"); + } + + return response; + } + } +} +// [END developerknowledge_batch_get_documents] diff --git a/developer-knowledge/src/main/java/developerknowledge/GetDocument.java b/developer-knowledge/src/main/java/developerknowledge/GetDocument.java new file mode 100644 index 00000000000..77aac16a1d5 --- /dev/null +++ b/developer-knowledge/src/main/java/developerknowledge/GetDocument.java @@ -0,0 +1,57 @@ +/* + * Copyright 2026 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 developerknowledge; + +// [START developerknowledge_get_document] +import com.google.developers.knowledge.v1.DeveloperKnowledgeClient; +import com.google.developers.knowledge.v1.Document; +import com.google.developers.knowledge.v1.GetDocumentRequest; +import java.io.IOException; + +public class GetDocument { + + public static void main(String[] args) throws IOException { + // TODO(developer): Replace these variables before running the sample. + String name = "documents/docs.cloud.google.com/storage/docs/creating-buckets"; + getDocument(name); + } + + // Retrieves a single developer documentation page by its resource name. + public static Document getDocument(String name) 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. After completing all of your requests, call + // the "close" method on the client to safely clean up any remaining background resources. + try (DeveloperKnowledgeClient client = DeveloperKnowledgeClient.create()) { + GetDocumentRequest request = GetDocumentRequest.newBuilder().setName(name).build(); + + Document document = client.getDocument(request); + + System.out.println("Title: " + document.getTitle()); + System.out.println("URI: " + document.getUri()); + System.out.println("Data Source: " + document.getDataSource()); + System.out.println("Content Length: " + document.getContentLengthBytes() + " bytes"); + String preview = document.getContent(); + if (preview.length() > 150) { + preview = preview.substring(0, 150) + "..."; + } + System.out.println("Content Preview: " + preview + "\n"); + + return document; + } + } +} +// [END developerknowledge_get_document] diff --git a/developer-knowledge/src/main/java/developerknowledge/SearchDocumentChunks.java b/developer-knowledge/src/main/java/developerknowledge/SearchDocumentChunks.java new file mode 100644 index 00000000000..c1ae3b8bebe --- /dev/null +++ b/developer-knowledge/src/main/java/developerknowledge/SearchDocumentChunks.java @@ -0,0 +1,64 @@ +/* + * Copyright 2026 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 developerknowledge; + +// [START developerknowledge_search_document_chunks] +import com.google.developers.knowledge.v1.DeveloperKnowledgeClient; +import com.google.developers.knowledge.v1.DeveloperKnowledgeClient.SearchDocumentChunksPagedResponse; +import com.google.developers.knowledge.v1.DocumentChunk; +import com.google.developers.knowledge.v1.SearchDocumentChunksRequest; +import java.io.IOException; + +public class SearchDocumentChunks { + + public static void main(String[] args) throws IOException { + // TODO(developer): Replace these variables before running the sample. + String query = "How to create a Cloud Storage bucket"; + int pageSize = 5; + searchDocumentChunks(query, pageSize); + } + + // Searches developer documentation chunks for a given query. + public static SearchDocumentChunksPagedResponse searchDocumentChunks( + String query, int pageSize) 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. After completing all of your requests, call + // the "close" method on the client to safely clean up any remaining background resources. + try (DeveloperKnowledgeClient client = DeveloperKnowledgeClient.create()) { + SearchDocumentChunksRequest request = + SearchDocumentChunksRequest.newBuilder() + .setQuery(query) + .setPageSize(pageSize) + .build(); + + SearchDocumentChunksPagedResponse response = client.searchDocumentChunks(request); + + for (DocumentChunk chunk : response.getPage().getValues()) { + System.out.println("Parent Document: " + chunk.getParent()); + System.out.println("Chunk ID: " + chunk.getId()); + String preview = chunk.getContent(); + if (preview.length() > 100) { + preview = preview.substring(0, 100) + "..."; + } + System.out.println("Content: " + preview + "\n"); + } + + return response; + } + } +} +// [END developerknowledge_search_document_chunks] diff --git a/developer-knowledge/src/test/java/developerknowledge/SnippetsIT.java b/developer-knowledge/src/test/java/developerknowledge/SnippetsIT.java new file mode 100644 index 00000000000..7a4c40e1172 --- /dev/null +++ b/developer-knowledge/src/test/java/developerknowledge/SnippetsIT.java @@ -0,0 +1,75 @@ +/* + * Copyright 2026 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 developerknowledge; + +import static com.google.common.truth.Truth.assertThat; + +import com.google.developers.knowledge.v1.AnswerQueryResponse; +import com.google.developers.knowledge.v1.BatchGetDocumentsResponse; +import com.google.developers.knowledge.v1.DeveloperKnowledgeClient.SearchDocumentChunksPagedResponse; +import com.google.developers.knowledge.v1.Document; +import com.google.developers.knowledge.v1.DocumentChunk; +import java.io.IOException; +import java.util.Arrays; +import java.util.List; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +@RunWith(JUnit4.class) +public class SnippetsIT { + + @Test + public void testSearchDocumentChunks() throws IOException { + SearchDocumentChunksPagedResponse response = + SearchDocumentChunks.searchDocumentChunks("Cloud Storage bucket creation", 3); + assertThat(response).isNotNull(); + assertThat(response.getPage().getValues()).isNotEmpty(); + DocumentChunk firstChunk = response.getPage().getValues().iterator().next(); + assertThat(firstChunk.getParent()).startsWith("documents/"); + assertThat(firstChunk.getContent()).isNotEmpty(); + } + + @Test + public void testGetDocument() throws IOException { + String name = "documents/docs.cloud.google.com/storage/docs/creating-buckets"; + Document doc = GetDocument.getDocument(name); + assertThat(doc).isNotNull(); + assertThat(doc.getName()).isEqualTo(name); + assertThat(doc.getTitle()).isNotEmpty(); + assertThat(doc.getContent()).isNotEmpty(); + } + + @Test + public void testBatchGetDocuments() throws IOException { + List names = + Arrays.asList( + "documents/docs.cloud.google.com/storage/docs/creating-buckets", + "documents/docs.cloud.google.com/storage/docs/deleting-buckets"); + BatchGetDocumentsResponse response = BatchGetDocuments.batchGetDocuments(names); + assertThat(response).isNotNull(); + assertThat(response.getDocumentsList()).hasSize(2); + } + + @Test + public void testAnswerQuery() throws IOException { + AnswerQueryResponse response = + AnswerQuery.answerQuery("How to create a Cloud Storage bucket"); + assertThat(response).isNotNull(); + assertThat(response.getAnswer().getAnswerText()).isNotEmpty(); + } +}