diff --git a/dialogflow/snippets/pom.xml b/dialogflow/snippets/pom.xml
new file mode 100644
index 00000000000..0d7425bc6d1
--- /dev/null
+++ b/dialogflow/snippets/pom.xml
@@ -0,0 +1,69 @@
+
+
+ 4.0.0
+ com.example.dialogflow
+ dialogflow-snippets
+ jar
+ Google Dialogflow API Snippets
+ https://github.com/GoogleCloudPlatform/java-docs-samples/tree/main/dialogflow
+
+
+
+ com.google.cloud.samples
+ shared-configuration
+ 1.2.0
+
+
+
+ 1.8
+ 1.8
+ UTF-8
+
+
+
+
+
+
+
+ com.google.cloud
+ libraries-bom
+ 26.1.3
+ pom
+ import
+
+
+
+
+
+
+ com.google.cloud
+ google-cloud-dialogflow
+
+
+
+
+ com.google.cloud
+ google-cloud-core
+ 2.8.20
+ test
+ tests
+
+
+
+
+ junit
+ junit
+ 4.13.2
+ test
+
+
+ com.google.truth
+ truth
+ 1.1.3
+ test
+
+
+
diff --git a/dialogflow/snippets/resources/230pm.wav b/dialogflow/snippets/resources/230pm.wav
new file mode 100644
index 00000000000..7509eca784d
Binary files /dev/null and b/dialogflow/snippets/resources/230pm.wav differ
diff --git a/dialogflow/snippets/resources/RoomReservation.zip b/dialogflow/snippets/resources/RoomReservation.zip
new file mode 100644
index 00000000000..7873fb628c8
Binary files /dev/null and b/dialogflow/snippets/resources/RoomReservation.zip differ
diff --git a/dialogflow/snippets/resources/book_a_room.wav b/dialogflow/snippets/resources/book_a_room.wav
new file mode 100644
index 00000000000..9124e927946
Binary files /dev/null and b/dialogflow/snippets/resources/book_a_room.wav differ
diff --git a/dialogflow/snippets/resources/half_an_hour.wav b/dialogflow/snippets/resources/half_an_hour.wav
new file mode 100644
index 00000000000..71010a871bb
Binary files /dev/null and b/dialogflow/snippets/resources/half_an_hour.wav differ
diff --git a/dialogflow/snippets/resources/mountain_view.wav b/dialogflow/snippets/resources/mountain_view.wav
new file mode 100644
index 00000000000..1c5437f7cb5
Binary files /dev/null and b/dialogflow/snippets/resources/mountain_view.wav differ
diff --git a/dialogflow/snippets/resources/today.wav b/dialogflow/snippets/resources/today.wav
new file mode 100644
index 00000000000..d47ed78b351
Binary files /dev/null and b/dialogflow/snippets/resources/today.wav differ
diff --git a/dialogflow/snippets/resources/two_people.wav b/dialogflow/snippets/resources/two_people.wav
new file mode 100644
index 00000000000..5114ebbd310
Binary files /dev/null and b/dialogflow/snippets/resources/two_people.wav differ
diff --git a/dialogflow/snippets/src/main/dialogflow/Example.java b/dialogflow/snippets/src/main/dialogflow/Example.java
new file mode 100644
index 00000000000..24f5aaeba19
--- /dev/null
+++ b/dialogflow/snippets/src/main/dialogflow/Example.java
@@ -0,0 +1,72 @@
+/*
+ * Copyright 2021 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 dialogflow;
+
+// [START dialogflow_webhook]
+
+// TODO: add GSON dependency to Pom file
+// (https://mvnrepository.com/artifact/com.google.code.gson/gson/2.8.5)
+// TODO: Uncomment the line bellow before running cloud function
+// package com.example;
+
+import com.google.cloud.functions.HttpFunction;
+import com.google.cloud.functions.HttpRequest;
+import com.google.cloud.functions.HttpResponse;
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import com.google.gson.JsonObject;
+import com.google.gson.JsonParser;
+import java.io.BufferedWriter;
+
+public class Example implements HttpFunction {
+
+ public void service(HttpRequest request, HttpResponse response) throws Exception {
+ JsonParser parser = new JsonParser();
+ Gson gson = new GsonBuilder().create();
+
+ JsonObject job = gson.fromJson(request.getReader(), JsonObject.class);
+ String str =
+ job.getAsJsonObject("queryResult")
+ .getAsJsonObject("intent")
+ .getAsJsonPrimitive("displayName")
+ .toString();
+ JsonObject o = null;
+ String a = '"' + "Default Welcome Intent" + '"';
+ String b = '"' + "get-agent-name" + '"';
+ String responseText = "";
+
+ if (str.equals(a)) {
+ responseText = '"' + "Hello from a Java GCF Webhook" + '"';
+ } else if (str.equals(b)) {
+ responseText = '"' + "My name is Flowhook" + '"';
+ } else {
+ responseText = '"' + "Sorry I didn't get that" + '"';
+ }
+
+ o =
+ parser
+ .parse(
+ "{\"fulfillmentMessages\": [ { \"text\": { \"text\": [ "
+ + responseText
+ + " ] } } ] }")
+ .getAsJsonObject();
+
+ BufferedWriter writer = response.getWriter();
+ writer.write(o.toString());
+ }
+}
+// [END dialogflow_webhook]
diff --git a/dialogflow/snippets/src/main/dialogflow/SetAgent.java b/dialogflow/snippets/src/main/dialogflow/SetAgent.java
new file mode 100644
index 00000000000..cfa73edf26d
--- /dev/null
+++ b/dialogflow/snippets/src/main/dialogflow/SetAgent.java
@@ -0,0 +1,57 @@
+/*
+ * Copyright 2021 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 dialogflow;
+
+// [START dialogflow_es_create_agent]
+
+import com.google.cloud.dialogflow.v2.Agent;
+import com.google.cloud.dialogflow.v2.Agent.Builder;
+import com.google.cloud.dialogflow.v2.AgentsClient;
+import com.google.cloud.dialogflow.v2.AgentsSettings;
+import java.io.IOException;
+
+public class SetAgent {
+
+ public static void main(String[] args) throws IOException {
+ String projectId = "my-project-id";
+
+ // The display name will set the name of your agent
+ String displayName = "my-display-name";
+
+ setAgent(projectId, displayName);
+ }
+
+ public static Agent setAgent(String parent, String displayName) throws IOException {
+
+ AgentsSettings agentsSettings = AgentsSettings.newBuilder().build();
+ try (AgentsClient client = AgentsClient.create(agentsSettings)) {
+ // Set the details of the Agent to create
+ Builder build = Agent.newBuilder();
+
+ build.setDefaultLanguageCode("en");
+ build.setDisplayName(displayName);
+
+ Agent agent = build.build();
+
+ // Make API request to create agent
+ Agent response = client.setAgent(agent);
+ System.out.println(response);
+ return response;
+ }
+ }
+}
+// [END dialogflow_es_create_agent]
diff --git a/dialogflow/snippets/src/main/java/com/example/dialogflow/DetectIntentAudio.java b/dialogflow/snippets/src/main/java/com/example/dialogflow/DetectIntentAudio.java
new file mode 100644
index 00000000000..0d3a6955a4a
--- /dev/null
+++ b/dialogflow/snippets/src/main/java/com/example/dialogflow/DetectIntentAudio.java
@@ -0,0 +1,95 @@
+/*
+ * Copyright 2018 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.dialogflow;
+
+// [START dialogflow_detect_intent_audio]
+
+import com.google.api.gax.rpc.ApiException;
+import com.google.cloud.dialogflow.v2.AudioEncoding;
+import com.google.cloud.dialogflow.v2.DetectIntentRequest;
+import com.google.cloud.dialogflow.v2.DetectIntentResponse;
+import com.google.cloud.dialogflow.v2.InputAudioConfig;
+import com.google.cloud.dialogflow.v2.QueryInput;
+import com.google.cloud.dialogflow.v2.QueryResult;
+import com.google.cloud.dialogflow.v2.SessionName;
+import com.google.cloud.dialogflow.v2.SessionsClient;
+import com.google.protobuf.ByteString;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+
+public class DetectIntentAudio {
+
+ // DialogFlow API Detect Intent sample with audio files.
+ public static QueryResult detectIntentAudio(
+ String projectId, String audioFilePath, String sessionId, String languageCode)
+ throws IOException, ApiException {
+ // Instantiates a client
+ try (SessionsClient sessionsClient = SessionsClient.create()) {
+ // Set the session name using the sessionId (UUID) and projectID (my-project-id)
+ SessionName session = SessionName.of(projectId, sessionId);
+ System.out.println("Session Path: " + session.toString());
+
+ // Note: hard coding audioEncoding and sampleRateHertz for simplicity.
+ // Audio encoding of the audio content sent in the query request.
+ AudioEncoding audioEncoding = AudioEncoding.AUDIO_ENCODING_LINEAR_16;
+ int sampleRateHertz = 16000;
+
+ // Instructs the speech recognizer how to process the audio content.
+ InputAudioConfig inputAudioConfig =
+ InputAudioConfig.newBuilder()
+ .setAudioEncoding(
+ audioEncoding) // audioEncoding = AudioEncoding.AUDIO_ENCODING_LINEAR_16
+ .setLanguageCode(languageCode) // languageCode = "en-US"
+ .setSampleRateHertz(sampleRateHertz) // sampleRateHertz = 16000
+ .build();
+
+ // Build the query with the InputAudioConfig
+ QueryInput queryInput = QueryInput.newBuilder().setAudioConfig(inputAudioConfig).build();
+
+ // Read the bytes from the audio file
+ byte[] inputAudio = Files.readAllBytes(Paths.get(audioFilePath));
+
+ // Build the DetectIntentRequest
+ DetectIntentRequest request =
+ DetectIntentRequest.newBuilder()
+ .setSession(session.toString())
+ .setQueryInput(queryInput)
+ .setInputAudio(ByteString.copyFrom(inputAudio))
+ .build();
+
+ // Performs the detect intent request
+ DetectIntentResponse response = sessionsClient.detectIntent(request);
+
+ // Display the query result
+ QueryResult queryResult = response.getQueryResult();
+ System.out.println("====================");
+ System.out.format("Query Text: '%s'\n", queryResult.getQueryText());
+ System.out.format(
+ "Detected Intent: %s (confidence: %f)\n",
+ queryResult.getIntent().getDisplayName(), queryResult.getIntentDetectionConfidence());
+ System.out.format(
+ "Fulfillment Text: '%s'\n",
+ queryResult.getFulfillmentMessagesCount() > 0
+ ? queryResult.getFulfillmentMessages(0).getText()
+ : "Triggered Default Fallback Intent");
+
+ return queryResult;
+ }
+ }
+}
+// [END dialogflow_detect_intent_audio]
diff --git a/dialogflow/snippets/src/main/java/com/example/dialogflow/DetectIntentKnowledge.java b/dialogflow/snippets/src/main/java/com/example/dialogflow/DetectIntentKnowledge.java
new file mode 100644
index 00000000000..04484eb50df
--- /dev/null
+++ b/dialogflow/snippets/src/main/java/com/example/dialogflow/DetectIntentKnowledge.java
@@ -0,0 +1,101 @@
+/*
+ * Copyright 2018 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.dialogflow;
+
+// [START dialogflow_detect_intent_knowledge]
+
+import com.google.api.gax.rpc.ApiException;
+import com.google.cloud.dialogflow.v2beta1.DetectIntentRequest;
+import com.google.cloud.dialogflow.v2beta1.DetectIntentResponse;
+import com.google.cloud.dialogflow.v2beta1.KnowledgeAnswers;
+import com.google.cloud.dialogflow.v2beta1.KnowledgeAnswers.Answer;
+import com.google.cloud.dialogflow.v2beta1.QueryInput;
+import com.google.cloud.dialogflow.v2beta1.QueryParameters;
+import com.google.cloud.dialogflow.v2beta1.QueryResult;
+import com.google.cloud.dialogflow.v2beta1.SessionName;
+import com.google.cloud.dialogflow.v2beta1.SessionsClient;
+import com.google.cloud.dialogflow.v2beta1.TextInput;
+import com.google.common.collect.Maps;
+import java.io.IOException;
+import java.util.List;
+import java.util.Map;
+
+public class DetectIntentKnowledge {
+
+ // DialogFlow API Detect Intent sample with querying knowledge connector.
+ public static Map detectIntentKnowledge(
+ String projectId,
+ String knowledgeBaseName,
+ String sessionId,
+ String languageCode,
+ List texts)
+ throws IOException, ApiException {
+ // Instantiates a client
+ Map allKnowledgeAnswers = Maps.newHashMap();
+ try (SessionsClient sessionsClient = SessionsClient.create()) {
+ // Set the session name using the sessionId (UUID) and projectID (my-project-id)
+ SessionName session = SessionName.of(projectId, sessionId);
+ System.out.println("Session Path: " + session.toString());
+
+ // Detect intents for each text input
+ for (String text : texts) {
+ // Set the text and language code (en-US) for the query
+ TextInput.Builder textInput =
+ TextInput.newBuilder().setText(text).setLanguageCode(languageCode);
+ // Build the query with the TextInput
+ QueryInput queryInput = QueryInput.newBuilder().setText(textInput).build();
+
+ QueryParameters queryParameters =
+ QueryParameters.newBuilder().addKnowledgeBaseNames(knowledgeBaseName).build();
+
+ DetectIntentRequest detectIntentRequest =
+ DetectIntentRequest.newBuilder()
+ .setSession(session.toString())
+ .setQueryInput(queryInput)
+ .setQueryParams(queryParameters)
+ .build();
+ // Performs the detect intent request
+ DetectIntentResponse response = sessionsClient.detectIntent(detectIntentRequest);
+
+ // Display the query result
+ QueryResult queryResult = response.getQueryResult();
+
+ System.out.format("Knowledge results:\n");
+ System.out.format("====================\n");
+ System.out.format("Query Text: '%s'\n", queryResult.getQueryText());
+ System.out.format(
+ "Detected Intent: %s (confidence: %f)\n",
+ queryResult.getIntent().getDisplayName(), queryResult.getIntentDetectionConfidence());
+ System.out.format(
+ "Fulfillment Text: '%s'\n",
+ queryResult.getFulfillmentMessagesCount() > 0
+ ? queryResult.getFulfillmentMessages(0).getText()
+ : "Triggered Default Fallback Intent");
+ KnowledgeAnswers knowledgeAnswers = queryResult.getKnowledgeAnswers();
+ for (Answer answer : knowledgeAnswers.getAnswersList()) {
+ System.out.format(" - Answer: '%s'\n", answer.getAnswer());
+ System.out.format(" - Confidence: '%s'\n", answer.getMatchConfidence());
+ }
+
+ KnowledgeAnswers answers = queryResult.getKnowledgeAnswers();
+ allKnowledgeAnswers.put(text, answers);
+ }
+ }
+ return allKnowledgeAnswers;
+ }
+}
+// [END dialogflow_detect_intent_knowledge]
diff --git a/dialogflow/snippets/src/main/java/com/example/dialogflow/DetectIntentStream.java b/dialogflow/snippets/src/main/java/com/example/dialogflow/DetectIntentStream.java
new file mode 100644
index 00000000000..27febe126a7
--- /dev/null
+++ b/dialogflow/snippets/src/main/java/com/example/dialogflow/DetectIntentStream.java
@@ -0,0 +1,108 @@
+/*
+ * Copyright 2018 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.dialogflow;
+
+// [START dialogflow_detect_intent_streaming]
+
+import com.google.api.gax.rpc.ApiException;
+import com.google.api.gax.rpc.BidiStream;
+import com.google.cloud.dialogflow.v2.AudioEncoding;
+import com.google.cloud.dialogflow.v2.InputAudioConfig;
+import com.google.cloud.dialogflow.v2.QueryInput;
+import com.google.cloud.dialogflow.v2.QueryResult;
+import com.google.cloud.dialogflow.v2.SessionName;
+import com.google.cloud.dialogflow.v2.SessionsClient;
+import com.google.cloud.dialogflow.v2.StreamingDetectIntentRequest;
+import com.google.cloud.dialogflow.v2.StreamingDetectIntentResponse;
+import com.google.protobuf.ByteString;
+import java.io.FileInputStream;
+import java.io.IOException;
+
+class DetectIntentStream {
+
+ // DialogFlow API Detect Intent sample with audio files processes as an audio stream.
+ static void detectIntentStream(String projectId, String audioFilePath, String sessionId)
+ throws IOException, ApiException {
+ // String projectId = "YOUR_PROJECT_ID";
+ // String audioFilePath = "path_to_your_audio_file";
+ // Using the same `sessionId` between requests allows continuation of the conversation.
+ // String sessionId = "Identifier of the DetectIntent session";
+
+ // Instantiates a client
+ try (SessionsClient sessionsClient = SessionsClient.create()) {
+ // Set the session name using the sessionId (UUID) and projectID (my-project-id)
+ SessionName session = SessionName.of(projectId, sessionId);
+
+ // Instructs the speech recognizer how to process the audio content.
+ // Note: hard coding audioEncoding and sampleRateHertz for simplicity.
+ // Audio encoding of the audio content sent in the query request.
+ InputAudioConfig inputAudioConfig =
+ InputAudioConfig.newBuilder()
+ .setAudioEncoding(AudioEncoding.AUDIO_ENCODING_LINEAR_16)
+ .setLanguageCode("en-US") // languageCode = "en-US"
+ .setSampleRateHertz(16000) // sampleRateHertz = 16000
+ .build();
+
+ // Build the query with the InputAudioConfig
+ QueryInput queryInput = QueryInput.newBuilder().setAudioConfig(inputAudioConfig).build();
+
+ // Create the Bidirectional stream
+ BidiStream bidiStream =
+ sessionsClient.streamingDetectIntentCallable().call();
+
+ // The first request must **only** contain the audio configuration:
+ bidiStream.send(
+ StreamingDetectIntentRequest.newBuilder()
+ .setSession(session.toString())
+ .setQueryInput(queryInput)
+ .build());
+
+ try (FileInputStream audioStream = new FileInputStream(audioFilePath)) {
+ // Subsequent requests must **only** contain the audio data.
+ // Following messages: audio chunks. We just read the file in fixed-size chunks. In reality
+ // you would split the user input by time.
+ byte[] buffer = new byte[4096];
+ int bytes;
+ while ((bytes = audioStream.read(buffer)) != -1) {
+ bidiStream.send(
+ StreamingDetectIntentRequest.newBuilder()
+ .setInputAudio(ByteString.copyFrom(buffer, 0, bytes))
+ .build());
+ }
+ }
+
+ // Tell the service you are done sending data
+ bidiStream.closeSend();
+
+ for (StreamingDetectIntentResponse response : bidiStream) {
+ QueryResult queryResult = response.getQueryResult();
+ System.out.println("====================");
+ System.out.format("Intent Display Name: %s\n", queryResult.getIntent().getDisplayName());
+ System.out.format("Query Text: '%s'\n", queryResult.getQueryText());
+ System.out.format(
+ "Detected Intent: %s (confidence: %f)\n",
+ queryResult.getIntent().getDisplayName(), queryResult.getIntentDetectionConfidence());
+ System.out.format(
+ "Fulfillment Text: '%s'\n",
+ queryResult.getFulfillmentMessagesCount() > 0
+ ? queryResult.getFulfillmentMessages(0).getText()
+ : "Triggered Default Fallback Intent");
+ }
+ }
+ }
+}
+// [END dialogflow_detect_intent_streaming]
diff --git a/dialogflow/snippets/src/main/java/com/example/dialogflow/DetectIntentTexts.java b/dialogflow/snippets/src/main/java/com/example/dialogflow/DetectIntentTexts.java
new file mode 100644
index 00000000000..0eb5b415bdb
--- /dev/null
+++ b/dialogflow/snippets/src/main/java/com/example/dialogflow/DetectIntentTexts.java
@@ -0,0 +1,78 @@
+/*
+ * Copyright 2018 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.dialogflow;
+
+// [START dialogflow_detect_intent_text]
+
+import com.google.api.gax.rpc.ApiException;
+import com.google.cloud.dialogflow.v2.DetectIntentResponse;
+import com.google.cloud.dialogflow.v2.QueryInput;
+import com.google.cloud.dialogflow.v2.QueryResult;
+import com.google.cloud.dialogflow.v2.SessionName;
+import com.google.cloud.dialogflow.v2.SessionsClient;
+import com.google.cloud.dialogflow.v2.TextInput;
+import com.google.common.collect.Maps;
+import java.io.IOException;
+import java.util.List;
+import java.util.Map;
+
+public class DetectIntentTexts {
+
+ // DialogFlow API Detect Intent sample with text inputs.
+ public static Map detectIntentTexts(
+ String projectId, List texts, String sessionId, String languageCode)
+ throws IOException, ApiException {
+ Map queryResults = Maps.newHashMap();
+ // Instantiates a client
+ try (SessionsClient sessionsClient = SessionsClient.create()) {
+ // Set the session name using the sessionId (UUID) and projectID (my-project-id)
+ SessionName session = SessionName.of(projectId, sessionId);
+ System.out.println("Session Path: " + session.toString());
+
+ // Detect intents for each text input
+ for (String text : texts) {
+ // Set the text (hello) and language code (en-US) for the query
+ TextInput.Builder textInput =
+ TextInput.newBuilder().setText(text).setLanguageCode(languageCode);
+
+ // Build the query with the TextInput
+ QueryInput queryInput = QueryInput.newBuilder().setText(textInput).build();
+
+ // Performs the detect intent request
+ DetectIntentResponse response = sessionsClient.detectIntent(session, queryInput);
+
+ // Display the query result
+ QueryResult queryResult = response.getQueryResult();
+
+ System.out.println("====================");
+ System.out.format("Query Text: '%s'\n", queryResult.getQueryText());
+ System.out.format(
+ "Detected Intent: %s (confidence: %f)\n",
+ queryResult.getIntent().getDisplayName(), queryResult.getIntentDetectionConfidence());
+ System.out.format(
+ "Fulfillment Text: '%s'\n",
+ queryResult.getFulfillmentMessagesCount() > 0
+ ? queryResult.getFulfillmentMessages(0).getText()
+ : "Triggered Default Fallback Intent");
+
+ queryResults.put(text, queryResult);
+ }
+ }
+ return queryResults;
+ }
+}
+// [END dialogflow_detect_intent_text]
diff --git a/dialogflow/snippets/src/main/java/com/example/dialogflow/DetectIntentWithLocation.java b/dialogflow/snippets/src/main/java/com/example/dialogflow/DetectIntentWithLocation.java
new file mode 100644
index 00000000000..6c825812577
--- /dev/null
+++ b/dialogflow/snippets/src/main/java/com/example/dialogflow/DetectIntentWithLocation.java
@@ -0,0 +1,88 @@
+/*
+ * Copyright 2020 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.dialogflow;
+
+// [START dialogflow_detect_intent_with_location]
+
+import com.google.api.gax.rpc.ApiException;
+import com.google.cloud.dialogflow.v2beta1.DetectIntentResponse;
+import com.google.cloud.dialogflow.v2beta1.QueryInput;
+import com.google.cloud.dialogflow.v2beta1.QueryResult;
+import com.google.cloud.dialogflow.v2beta1.SessionName;
+import com.google.cloud.dialogflow.v2beta1.SessionsClient;
+import com.google.cloud.dialogflow.v2beta1.SessionsSettings;
+import com.google.cloud.dialogflow.v2beta1.TextInput;
+import com.google.common.collect.Maps;
+import java.io.IOException;
+import java.util.List;
+import java.util.Map;
+
+public class DetectIntentWithLocation {
+
+ // DialogFlow API Detect Intent sample with text inputs.
+ public static Map detectIntentWithLocation(
+ String projectId,
+ String locationId,
+ List texts,
+ String sessionId,
+ String languageCode)
+ throws IOException, ApiException {
+ SessionsSettings sessionsSettings =
+ SessionsSettings.newBuilder()
+ .setEndpoint(locationId + "-dialogflow.googleapis.com:443")
+ .build();
+ Map queryResults = Maps.newHashMap();
+ // Instantiates a client
+ try (SessionsClient sessionsClient = SessionsClient.create(sessionsSettings)) {
+ // Set the session name using the projectId (my-project-id), locationId and sessionId (UUID)
+ SessionName session =
+ SessionName.ofProjectLocationSessionName(projectId, locationId, sessionId);
+ System.out.println("Session Path: " + session.toString());
+
+ // Detect intents for each text input
+ for (String text : texts) {
+ // Set the text (hello) and language code (en-US) for the query
+ TextInput.Builder textInput =
+ TextInput.newBuilder().setText(text).setLanguageCode(languageCode);
+
+ // Build the query with the TextInput
+ QueryInput queryInput = QueryInput.newBuilder().setText(textInput).build();
+
+ // Performs the detect intent request
+ DetectIntentResponse response = sessionsClient.detectIntent(session, queryInput);
+
+ // Display the query result
+ QueryResult queryResult = response.getQueryResult();
+
+ System.out.println("====================");
+ System.out.format("Query Text: '%s'\n", queryResult.getQueryText());
+ System.out.format(
+ "Detected Intent: %s (confidence: %f)\n",
+ queryResult.getIntent().getDisplayName(), queryResult.getIntentDetectionConfidence());
+ System.out.format(
+ "Fulfillment Text: '%s'\n",
+ queryResult.getFulfillmentMessagesCount() > 0
+ ? queryResult.getFulfillmentMessages(0).getText()
+ : "Triggered Default Fallback Intent");
+
+ queryResults.put(text, queryResult);
+ }
+ }
+ return queryResults;
+ }
+}
+// [END dialogflow_detect_intent_with_location]
diff --git a/dialogflow/snippets/src/main/java/com/example/dialogflow/DetectIntentWithSentimentAnalysis.java b/dialogflow/snippets/src/main/java/com/example/dialogflow/DetectIntentWithSentimentAnalysis.java
new file mode 100644
index 00000000000..4a9133a3e50
--- /dev/null
+++ b/dialogflow/snippets/src/main/java/com/example/dialogflow/DetectIntentWithSentimentAnalysis.java
@@ -0,0 +1,98 @@
+/*
+ * Copyright 2018 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.dialogflow;
+
+// [START dialogflow_detect_intent_with_sentiment_analysis]
+
+import com.google.api.gax.rpc.ApiException;
+import com.google.cloud.dialogflow.v2.DetectIntentRequest;
+import com.google.cloud.dialogflow.v2.DetectIntentResponse;
+import com.google.cloud.dialogflow.v2.QueryInput;
+import com.google.cloud.dialogflow.v2.QueryParameters;
+import com.google.cloud.dialogflow.v2.QueryResult;
+import com.google.cloud.dialogflow.v2.SentimentAnalysisRequestConfig;
+import com.google.cloud.dialogflow.v2.SessionName;
+import com.google.cloud.dialogflow.v2.SessionsClient;
+import com.google.cloud.dialogflow.v2.TextInput;
+import com.google.common.collect.Maps;
+import java.io.IOException;
+import java.util.List;
+import java.util.Map;
+
+public class DetectIntentWithSentimentAnalysis {
+
+ public static Map detectIntentSentimentAnalysis(
+ String projectId, List texts, String sessionId, String languageCode)
+ throws IOException, ApiException {
+ Map queryResults = Maps.newHashMap();
+ // Instantiates a client
+ try (SessionsClient sessionsClient = SessionsClient.create()) {
+ // Set the session name using the sessionId (UUID) and projectID (my-project-id)
+ SessionName session = SessionName.of(projectId, sessionId);
+ System.out.println("Session Path: " + session.toString());
+
+ // Detect intents for each text input
+ for (String text : texts) {
+ // Set the text (hello) and language code (en-US) for the query
+ TextInput.Builder textInput =
+ TextInput.newBuilder().setText(text).setLanguageCode(languageCode);
+
+ // Build the query with the TextInput
+ QueryInput queryInput = QueryInput.newBuilder().setText(textInput).build();
+
+ //
+ SentimentAnalysisRequestConfig sentimentAnalysisRequestConfig =
+ SentimentAnalysisRequestConfig.newBuilder().setAnalyzeQueryTextSentiment(true).build();
+
+ QueryParameters queryParameters =
+ QueryParameters.newBuilder()
+ .setSentimentAnalysisRequestConfig(sentimentAnalysisRequestConfig)
+ .build();
+ DetectIntentRequest detectIntentRequest =
+ DetectIntentRequest.newBuilder()
+ .setSession(session.toString())
+ .setQueryInput(queryInput)
+ .setQueryParams(queryParameters)
+ .build();
+
+ // Performs the detect intent request
+ DetectIntentResponse response = sessionsClient.detectIntent(detectIntentRequest);
+
+ // Display the query result
+ QueryResult queryResult = response.getQueryResult();
+
+ System.out.println("====================");
+ System.out.format("Query Text: '%s'\n", queryResult.getQueryText());
+ System.out.format(
+ "Detected Intent: %s (confidence: %f)\n",
+ queryResult.getIntent().getDisplayName(), queryResult.getIntentDetectionConfidence());
+ System.out.format(
+ "Fulfillment Text: '%s'\n",
+ queryResult.getFulfillmentMessagesCount() > 0
+ ? queryResult.getFulfillmentMessages(0).getText()
+ : "Triggered Default Fallback Intent");
+ System.out.format(
+ "Sentiment Score: '%s'\n",
+ queryResult.getSentimentAnalysisResult().getQueryTextSentiment().getScore());
+
+ queryResults.put(text, queryResult);
+ }
+ }
+ return queryResults;
+ }
+}
+// [END dialogflow_detect_intent_with_sentiment_analysis]
diff --git a/dialogflow/snippets/src/main/java/com/example/dialogflow/DetectIntentWithTextToSpeechResponse.java b/dialogflow/snippets/src/main/java/com/example/dialogflow/DetectIntentWithTextToSpeechResponse.java
new file mode 100644
index 00000000000..fbe97131846
--- /dev/null
+++ b/dialogflow/snippets/src/main/java/com/example/dialogflow/DetectIntentWithTextToSpeechResponse.java
@@ -0,0 +1,96 @@
+/*
+ * Copyright 2018 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.dialogflow;
+
+// [START dialogflow_detect_intent_with_texttospeech_response]
+
+import com.google.api.gax.rpc.ApiException;
+import com.google.cloud.dialogflow.v2.DetectIntentRequest;
+import com.google.cloud.dialogflow.v2.DetectIntentResponse;
+import com.google.cloud.dialogflow.v2.OutputAudioConfig;
+import com.google.cloud.dialogflow.v2.OutputAudioEncoding;
+import com.google.cloud.dialogflow.v2.QueryInput;
+import com.google.cloud.dialogflow.v2.QueryResult;
+import com.google.cloud.dialogflow.v2.SessionName;
+import com.google.cloud.dialogflow.v2.SessionsClient;
+import com.google.cloud.dialogflow.v2.TextInput;
+import com.google.common.collect.Maps;
+import java.io.IOException;
+import java.util.List;
+import java.util.Map;
+
+public class DetectIntentWithTextToSpeechResponse {
+
+ public static Map detectIntentWithTexttoSpeech(
+ String projectId, List texts, String sessionId, String languageCode)
+ throws IOException, ApiException {
+ Map queryResults = Maps.newHashMap();
+ // Instantiates a client
+ try (SessionsClient sessionsClient = SessionsClient.create()) {
+ // Set the session name using the sessionId (UUID) and projectID (my-project-id)
+ SessionName session = SessionName.of(projectId, sessionId);
+ System.out.println("Session Path: " + session.toString());
+
+ // Detect intents for each text input
+ for (String text : texts) {
+ // Set the text (hello) and language code (en-US) for the query
+ TextInput.Builder textInput =
+ TextInput.newBuilder().setText(text).setLanguageCode(languageCode);
+
+ // Build the query with the TextInput
+ QueryInput queryInput = QueryInput.newBuilder().setText(textInput).build();
+
+ //
+ OutputAudioEncoding audioEncoding = OutputAudioEncoding.OUTPUT_AUDIO_ENCODING_LINEAR_16;
+ int sampleRateHertz = 16000;
+ OutputAudioConfig outputAudioConfig =
+ OutputAudioConfig.newBuilder()
+ .setAudioEncoding(audioEncoding)
+ .setSampleRateHertz(sampleRateHertz)
+ .build();
+
+ DetectIntentRequest dr =
+ DetectIntentRequest.newBuilder()
+ .setQueryInput(queryInput)
+ .setOutputAudioConfig(outputAudioConfig)
+ .setSession(session.toString())
+ .build();
+
+ // Performs the detect intent request
+ DetectIntentResponse response = sessionsClient.detectIntent(dr);
+
+ // Display the query result
+ QueryResult queryResult = response.getQueryResult();
+
+ System.out.println("====================");
+ System.out.format("Query Text: '%s'\n", queryResult.getQueryText());
+ System.out.format(
+ "Detected Intent: %s (confidence: %f)\n",
+ queryResult.getIntent().getDisplayName(), queryResult.getIntentDetectionConfidence());
+ System.out.format(
+ "Fulfillment Text: '%s'\n",
+ queryResult.getFulfillmentMessagesCount() > 0
+ ? queryResult.getFulfillmentMessages(0).getText()
+ : "Triggered Default Fallback Intent");
+
+ queryResults.put(text, queryResult);
+ }
+ }
+ return queryResults;
+ }
+}
+// [END dialogflow_detect_intent_with_texttospeech_response]
diff --git a/dialogflow/snippets/src/main/java/com/example/dialogflow/DocumentManagement.java b/dialogflow/snippets/src/main/java/com/example/dialogflow/DocumentManagement.java
new file mode 100644
index 00000000000..08431689008
--- /dev/null
+++ b/dialogflow/snippets/src/main/java/com/example/dialogflow/DocumentManagement.java
@@ -0,0 +1,71 @@
+/*
+ * Copyright 2018 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.dialogflow;
+
+// [START dialogflow_create_document]
+
+import com.google.api.gax.longrunning.OperationFuture;
+import com.google.api.gax.rpc.ApiException;
+import com.google.cloud.dialogflow.v2.CreateDocumentRequest;
+import com.google.cloud.dialogflow.v2.Document;
+import com.google.cloud.dialogflow.v2.Document.KnowledgeType;
+import com.google.cloud.dialogflow.v2.DocumentsClient;
+import com.google.cloud.dialogflow.v2.KnowledgeOperationMetadata;
+import java.io.IOException;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+
+public class DocumentManagement {
+
+ public static void createDocument(
+ String knowledgeBaseName,
+ String displayName,
+ String mimeType,
+ String knowledgeType,
+ String contentUri)
+ throws IOException, ApiException, InterruptedException, ExecutionException, TimeoutException {
+ // Instantiates a client
+ try (DocumentsClient documentsClient = DocumentsClient.create()) {
+ Document document =
+ Document.newBuilder()
+ .setDisplayName(displayName)
+ .setContentUri(contentUri)
+ .setMimeType(mimeType)
+ .addKnowledgeTypes(KnowledgeType.valueOf(knowledgeType))
+ .build();
+ CreateDocumentRequest createDocumentRequest =
+ CreateDocumentRequest.newBuilder()
+ .setDocument(document)
+ .setParent(knowledgeBaseName)
+ .build();
+ OperationFuture response =
+ documentsClient.createDocumentAsync(createDocumentRequest);
+ Document createdDocument = response.get(180, TimeUnit.SECONDS);
+ System.out.format("Created Document:\n");
+ System.out.format(" - Display Name: %s\n", createdDocument.getDisplayName());
+ System.out.format(" - Document Name: %s\n", createdDocument.getName());
+ System.out.format(" - MIME Type: %s\n", createdDocument.getMimeType());
+ System.out.format(" - Knowledge Types:\n");
+ for (KnowledgeType knowledgeTypeId : document.getKnowledgeTypesList()) {
+ System.out.format(" - %s \n", knowledgeTypeId.getValueDescriptor());
+ }
+ System.out.format(" - Source: %s \n", document.getContentUri());
+ }
+ }
+}
+// [END dialogflow_create_document]
diff --git a/dialogflow/snippets/src/main/java/com/example/dialogflow/IntentManagement.java b/dialogflow/snippets/src/main/java/com/example/dialogflow/IntentManagement.java
new file mode 100644
index 00000000000..a9ed0f51880
--- /dev/null
+++ b/dialogflow/snippets/src/main/java/com/example/dialogflow/IntentManagement.java
@@ -0,0 +1,167 @@
+/*
+ * Copyright 2018 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.dialogflow;
+
+// Imports the Google Cloud client library
+
+import com.google.api.gax.rpc.ApiException;
+import com.google.cloud.dialogflow.v2.AgentName;
+import com.google.cloud.dialogflow.v2.Context;
+import com.google.cloud.dialogflow.v2.Intent;
+import com.google.cloud.dialogflow.v2.Intent.Message;
+import com.google.cloud.dialogflow.v2.Intent.Message.Text;
+import com.google.cloud.dialogflow.v2.Intent.TrainingPhrase;
+import com.google.cloud.dialogflow.v2.Intent.TrainingPhrase.Part;
+import com.google.cloud.dialogflow.v2.IntentName;
+import com.google.cloud.dialogflow.v2.IntentsClient;
+import com.google.common.collect.Lists;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+
+/** DialogFlow API Intent sample. */
+public class IntentManagement {
+ // [START dialogflow_list_intents]
+
+ /**
+ * List intents
+ *
+ * @param projectId Project/Agent Id.
+ * @return Intents found.
+ */
+ public static List listIntents(String projectId) throws ApiException, IOException {
+ List intents = Lists.newArrayList();
+ // Instantiates a client
+ try (IntentsClient intentsClient = IntentsClient.create()) {
+ // Set the project agent name using the projectID (my-project-id)
+ AgentName parent = AgentName.of(projectId);
+
+ // Performs the list intents request
+ for (Intent intent : intentsClient.listIntents(parent).iterateAll()) {
+ System.out.println("====================");
+ System.out.format("Intent name: '%s'\n", intent.getName());
+ System.out.format("Intent display name: '%s'\n", intent.getDisplayName());
+ System.out.format("Action: '%s'\n", intent.getAction());
+ System.out.format("Root followup intent: '%s'\n", intent.getRootFollowupIntentName());
+ System.out.format("Parent followup intent: '%s'\n", intent.getParentFollowupIntentName());
+
+ System.out.format("Input contexts:\n");
+ for (String inputContextName : intent.getInputContextNamesList()) {
+ System.out.format("\tName: %s\n", inputContextName);
+ }
+ System.out.format("Output contexts:\n");
+ for (Context outputContext : intent.getOutputContextsList()) {
+ System.out.format("\tName: %s\n", outputContext.getName());
+ }
+
+ intents.add(intent);
+ }
+ }
+ return intents;
+ }
+ // [END dialogflow_list_intents]
+
+ // [START dialogflow_create_intent]
+
+ /**
+ * Create an intent of the given intent type
+ *
+ * @param displayName The display name of the intent.
+ * @param projectId Project/Agent Id.
+ * @param trainingPhrasesParts Training phrases.
+ * @param messageTexts Message texts for the agent's response when the intent is detected.
+ * @return The created Intent.
+ */
+ public static Intent createIntent(
+ String displayName,
+ String projectId,
+ List trainingPhrasesParts,
+ List messageTexts)
+ throws ApiException, IOException {
+ // Instantiates a client
+ try (IntentsClient intentsClient = IntentsClient.create()) {
+ // Set the project agent name using the projectID (my-project-id)
+ AgentName parent = AgentName.of(projectId);
+
+ // Build the trainingPhrases from the trainingPhrasesParts
+ List trainingPhrases = new ArrayList<>();
+ for (String trainingPhrase : trainingPhrasesParts) {
+ trainingPhrases.add(
+ TrainingPhrase.newBuilder()
+ .addParts(Part.newBuilder().setText(trainingPhrase).build())
+ .build());
+ }
+
+ // Build the message texts for the agent's response
+ Message message =
+ Message.newBuilder().setText(Text.newBuilder().addAllText(messageTexts).build()).build();
+
+ // Build the intent
+ Intent intent =
+ Intent.newBuilder()
+ .setDisplayName(displayName)
+ .addMessages(message)
+ .addAllTrainingPhrases(trainingPhrases)
+ .build();
+
+ // Performs the create intent request
+ Intent response = intentsClient.createIntent(parent, intent);
+ System.out.format("Intent created: %s\n", response);
+
+ return response;
+ }
+ }
+ // [END dialogflow_create_intent]
+
+ // [START dialogflow_delete_intent]
+
+ /**
+ * Delete intent with the given intent type and intent value
+ *
+ * @param intentId The id of the intent.
+ * @param projectId Project/Agent Id.
+ */
+ public static void deleteIntent(String intentId, String projectId)
+ throws ApiException, IOException {
+ // Instantiates a client
+ try (IntentsClient intentsClient = IntentsClient.create()) {
+ IntentName name = IntentName.of(projectId, intentId);
+ // Performs the delete intent request
+ intentsClient.deleteIntent(name);
+ }
+ }
+ // [END dialogflow_delete_intent]
+
+ /** Helper method for testing to get intentIds from displayName. */
+ public static List getIntentIds(String displayName, String projectId)
+ throws ApiException, IOException {
+ List intentIds = new ArrayList<>();
+
+ // Instantiates a client
+ try (IntentsClient intentsClient = IntentsClient.create()) {
+ AgentName parent = AgentName.of(projectId);
+ for (Intent intent : intentsClient.listIntents(parent).iterateAll()) {
+ if (intent.getDisplayName().equals(displayName)) {
+ String[] splitName = intent.getName().split("/");
+ intentIds.add(splitName[splitName.length - 1]);
+ }
+ }
+ }
+
+ return intentIds;
+ }
+}
diff --git a/dialogflow/snippets/src/main/java/com/example/dialogflow/KnowledgeBaseManagement.java b/dialogflow/snippets/src/main/java/com/example/dialogflow/KnowledgeBaseManagement.java
new file mode 100644
index 00000000000..e3d30664a6c
--- /dev/null
+++ b/dialogflow/snippets/src/main/java/com/example/dialogflow/KnowledgeBaseManagement.java
@@ -0,0 +1,58 @@
+/*
+ * Copyright 2018 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.dialogflow;
+
+// [START dialogflow_create_knowledge_base]
+
+import com.google.api.gax.rpc.ApiException;
+import com.google.cloud.dialogflow.v2.KnowledgeBase;
+import com.google.cloud.dialogflow.v2.KnowledgeBasesClient;
+import com.google.cloud.dialogflow.v2.LocationName;
+import java.io.IOException;
+
+public class KnowledgeBaseManagement {
+
+ public static void main(String[] args) throws ApiException, IOException {
+ // TODO(developer): Replace these variables before running the sample.
+ String projectId = "my-project-id";
+ String location = "my-location";
+
+ // Set display name of the new knowledge base
+ String knowledgeBaseDisplayName = "my-knowledge-base-display-name";
+
+ // Create a knowledge base
+ createKnowledgeBase(projectId, location, knowledgeBaseDisplayName);
+ }
+
+ // Create a Knowledge base
+ public static void createKnowledgeBase(String projectId, String location, String displayName)
+ throws ApiException, IOException {
+ // Instantiates a client
+ try (KnowledgeBasesClient knowledgeBasesClient = KnowledgeBasesClient.create()) {
+ KnowledgeBase targetKnowledgeBase =
+ KnowledgeBase.newBuilder().setDisplayName(displayName).build();
+ LocationName parent = LocationName.of(projectId, location);
+ KnowledgeBase createdKnowledgeBase =
+ knowledgeBasesClient.createKnowledgeBase(parent, targetKnowledgeBase);
+ System.out.println("====================");
+ System.out.format("Knowledgebase created:\n");
+ System.out.format("Display Name: %s\n", createdKnowledgeBase.getDisplayName());
+ System.out.format("Name: %s\n", createdKnowledgeBase.getName());
+ }
+ }
+}
+// [END dialogflow_create_knowledge_base]
diff --git a/dialogflow/snippets/src/main/java/com/example/dialogflow/UpdateIntent.java b/dialogflow/snippets/src/main/java/com/example/dialogflow/UpdateIntent.java
new file mode 100644
index 00000000000..8b18afe7e75
--- /dev/null
+++ b/dialogflow/snippets/src/main/java/com/example/dialogflow/UpdateIntent.java
@@ -0,0 +1,64 @@
+/*
+ * Copyright 2021 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.dialogflow;
+
+// [START dialogflow_es_update_intent]
+import com.google.cloud.dialogflow.v2.Intent;
+import com.google.cloud.dialogflow.v2.Intent.Builder;
+import com.google.cloud.dialogflow.v2.IntentsClient;
+import com.google.cloud.dialogflow.v2.UpdateIntentRequest;
+import com.google.protobuf.FieldMask;
+import java.io.IOException;
+
+public class UpdateIntent {
+
+ public static void main(String[] args) throws IOException {
+ // TODO(developer): Replace these variables before running the sample.
+ String projectId = "my-project-id";
+ String intentId = "my-intent-id";
+ String location = "my-location";
+ String displayName = "my-display-name";
+ updateIntent(projectId, intentId, location, displayName);
+ }
+
+ // DialogFlow API Update Intent sample.
+ public static void updateIntent(
+ String projectId, String intentId, String location, String displayName) throws IOException {
+ try (IntentsClient client = IntentsClient.create()) {
+ String intentPath =
+ "projects/" + projectId + "/locations/" + location + "/agent/intents/" + intentId;
+
+ Builder intentBuilder = client.getIntent(intentPath).toBuilder();
+
+ intentBuilder.setDisplayName(displayName);
+ FieldMask fieldMask = FieldMask.newBuilder().addPaths("display_name").build();
+
+ Intent intent = intentBuilder.build();
+ UpdateIntentRequest request =
+ UpdateIntentRequest.newBuilder()
+ .setIntent(intent)
+ .setLanguageCode("en")
+ .setUpdateMask(fieldMask)
+ .build();
+
+ // Make API request to update intent using fieldmask
+ Intent response = client.updateIntent(request);
+ System.out.println(response);
+ }
+ }
+}
+// [END dialogflow_es_update_intent]
diff --git a/dialogflow/snippets/src/test/dialogflow/ExampleIT.java b/dialogflow/snippets/src/test/dialogflow/ExampleIT.java
new file mode 100644
index 00000000000..3a64c266070
--- /dev/null
+++ b/dialogflow/snippets/src/test/dialogflow/ExampleIT.java
@@ -0,0 +1,70 @@
+/*
+ * Copyright 2021 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 dialogflow;
+
+import static com.google.common.truth.Truth.assertThat;
+import static org.mockito.Mockito.when;
+
+import com.google.cloud.functions.HttpRequest;
+import com.google.cloud.functions.HttpResponse;
+import com.google.gson.Gson;
+import java.io.BufferedReader;
+import java.io.BufferedWriter;
+import java.io.IOException;
+import java.io.StringReader;
+import java.io.StringWriter;
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+
+public class ExampleIT {
+ @Mock private HttpRequest request;
+ @Mock private HttpResponse response;
+
+ private BufferedWriter writerOut;
+ private StringWriter responseOut;
+ private static final Gson gson = new Gson();
+
+ @Before
+ public void beforeTest() throws IOException {
+ MockitoAnnotations.initMocks(this);
+
+ // use an empty string as the default request content
+ BufferedReader reader = new BufferedReader(new StringReader(""));
+ when(request.getReader()).thenReturn(reader);
+
+ responseOut = new StringWriter();
+ writerOut = new BufferedWriter(responseOut);
+ when(response.getWriter()).thenReturn(writerOut);
+ }
+
+ @Test
+ public void helloHttp_bodyParamsPost() throws IOException {
+ BufferedReader jsonReader =
+ new BufferedReader(
+ new StringReader(
+ "{'queryResult': { 'intent': { 'name': 'projects', 'displayName': 'Default Welcome Intent' } } })"));
+
+ when(request.getReader()).thenReturn(jsonReader);
+
+ new Webhook().service(request, response);
+ writerOut.flush();
+
+ assertThat(responseOut.toString()).contains("Hello from a Java GCF Webhook");
+ }
+}
diff --git a/dialogflow/snippets/src/test/dialogflow/SetAgentIT.java b/dialogflow/snippets/src/test/dialogflow/SetAgentIT.java
new file mode 100644
index 00000000000..cf7417ca263
--- /dev/null
+++ b/dialogflow/snippets/src/test/dialogflow/SetAgentIT.java
@@ -0,0 +1,32 @@
+/*
+ * Copyright 2021 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 dialogflow;
+
+import org.junit.Assert;
+import org.junit.Test;
+
+public class SetAgentIT {
+ /*
+ * We cannot test setAgent because Dialogflow ES can only have one agent
+ * and if we create a agent it will delete the exisitng testing agent and
+ * would cause all tests to fail
+ */
+ @Test
+ public void testCreateAgent() {
+ Assert.assertTrue(true);
+ }
+}
diff --git a/dialogflow/snippets/src/test/java/com/example/dialogflow/CreateDocumentTest.java b/dialogflow/snippets/src/test/java/com/example/dialogflow/CreateDocumentTest.java
new file mode 100644
index 00000000000..e59508a521e
--- /dev/null
+++ b/dialogflow/snippets/src/test/java/com/example/dialogflow/CreateDocumentTest.java
@@ -0,0 +1,109 @@
+/*
+ * Copyright 2020 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.dialogflow;
+
+import static com.google.common.truth.Truth.assertThat;
+import static junit.framework.TestCase.assertNotNull;
+
+import com.google.cloud.dialogflow.v2.DeleteKnowledgeBaseRequest;
+import com.google.cloud.dialogflow.v2.KnowledgeBase;
+import com.google.cloud.dialogflow.v2.KnowledgeBasesClient;
+import com.google.cloud.dialogflow.v2.LocationName;
+import com.google.cloud.testing.junit4.MultipleAttemptsRule;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.PrintStream;
+import java.util.UUID;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+@RunWith(JUnit4.class)
+@SuppressWarnings("checkstyle:abbreviationaswordinname")
+public class CreateDocumentTest {
+
+ private static final String PROJECT_ID = System.getenv("GOOGLE_CLOUD_PROJECT");
+ private static final String LOCATION = "global";
+ private static String KNOWLEDGE_DISPLAY_NAME = UUID.randomUUID().toString();
+ private static String DOCUMENT_DISPLAY_NAME = UUID.randomUUID().toString();
+ private String knowledgeBaseName;
+ private ByteArrayOutputStream bout;
+ private PrintStream newOutputStream;
+ private PrintStream originalOutputStream;
+
+ private static void requireEnvVar(String varName) {
+ assertNotNull(String.format(varName));
+ }
+
+ @BeforeClass
+ public static void checkRequirements() {
+ requireEnvVar("GOOGLE_APPLICATION_CREDENTIALS");
+ requireEnvVar("GOOGLE_CLOUD_PROJECT");
+ }
+
+ @Before
+ public void setUp() throws IOException {
+ originalOutputStream = System.out;
+ bout = new ByteArrayOutputStream();
+ newOutputStream = new PrintStream(bout);
+ System.setOut(newOutputStream);
+
+ // Create a knowledge base for the document
+ try (KnowledgeBasesClient client = KnowledgeBasesClient.create()) {
+ KnowledgeBase knowledgeBase =
+ KnowledgeBase.newBuilder().setDisplayName(KNOWLEDGE_DISPLAY_NAME).build();
+ LocationName parent = LocationName.of(PROJECT_ID, LOCATION);
+ KnowledgeBase response = client.createKnowledgeBase(parent, knowledgeBase);
+ // Save the full name for deletion
+ knowledgeBaseName = response.getName();
+ }
+ }
+
+ @After
+ public void tearDown() throws IOException {
+ if (knowledgeBaseName == null) {
+ return;
+ }
+
+ // Delete the created knowledge base
+ try (KnowledgeBasesClient client = KnowledgeBasesClient.create()) {
+ DeleteKnowledgeBaseRequest request =
+ DeleteKnowledgeBaseRequest.newBuilder().setName(knowledgeBaseName).setForce(true).build();
+ client.deleteKnowledgeBase(request);
+ }
+
+ System.setOut(originalOutputStream);
+ }
+
+ @Rule public MultipleAttemptsRule multipleAttemptsRule = new MultipleAttemptsRule(3);
+
+ @Test
+ public void testCreateDocument() throws Exception {
+ DocumentManagement.createDocument(
+ knowledgeBaseName,
+ DOCUMENT_DISPLAY_NAME,
+ "text/html",
+ "FAQ",
+ "https://cloud.google.com/storage/docs/faq");
+ String got = bout.toString();
+ assertThat(got).contains(DOCUMENT_DISPLAY_NAME);
+ }
+}
diff --git a/dialogflow/snippets/src/test/java/com/example/dialogflow/CreateKnowledgeBaseTest.java b/dialogflow/snippets/src/test/java/com/example/dialogflow/CreateKnowledgeBaseTest.java
new file mode 100644
index 00000000000..a8e00f5e9e7
--- /dev/null
+++ b/dialogflow/snippets/src/test/java/com/example/dialogflow/CreateKnowledgeBaseTest.java
@@ -0,0 +1,94 @@
+/*
+ * Copyright 2020 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.dialogflow;
+
+import static com.google.common.truth.Truth.assertThat;
+import static junit.framework.TestCase.assertNotNull;
+
+import com.google.cloud.dialogflow.v2.DeleteKnowledgeBaseRequest;
+import com.google.cloud.dialogflow.v2.KnowledgeBasesClient;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.PrintStream;
+import java.util.UUID;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+@RunWith(JUnit4.class)
+@SuppressWarnings("checkstyle:abbreviationaswordinname")
+public class CreateKnowledgeBaseTest {
+
+ private static final String PROJECT_ID = System.getenv("GOOGLE_CLOUD_PROJECT");
+ private static final String LOCATION = "global";
+ private static final String ID_PREFIX_IN_OUTPUT = "Name: ";
+ private static String KNOWLEDGE_DISPLAY_NAME = UUID.randomUUID().toString();
+ private String knowledgeBaseName;
+ private ByteArrayOutputStream bout;
+ private PrintStream newOutputStream;
+ private PrintStream originalOutputStream;
+
+ private static void requireEnvVar(String varName) {
+ assertNotNull(System.getenv(varName));
+ }
+
+ // Extract the name of created resource from "Name: %s\n" in sample code output
+ private static String getResourceNameFromOutputString(String output) {
+ return output.substring(
+ output.lastIndexOf(ID_PREFIX_IN_OUTPUT) + ID_PREFIX_IN_OUTPUT.length(),
+ output.length() - 1);
+ }
+
+ @BeforeClass
+ public static void checkRequirements() {
+ requireEnvVar("GOOGLE_APPLICATION_CREDENTIALS");
+ requireEnvVar("GOOGLE_CLOUD_PROJECT");
+ }
+
+ @Before
+ public void setUp() {
+ bout = new ByteArrayOutputStream();
+ newOutputStream = new PrintStream(bout);
+ System.setOut(newOutputStream);
+ }
+
+ @After
+ public void tearDown() throws IOException {
+ if (knowledgeBaseName == null) {
+ return;
+ }
+
+ // Delete the created knowledge base
+ try (KnowledgeBasesClient client = KnowledgeBasesClient.create()) {
+ DeleteKnowledgeBaseRequest request =
+ DeleteKnowledgeBaseRequest.newBuilder().setName(knowledgeBaseName).setForce(true).build();
+ client.deleteKnowledgeBase(request);
+ }
+ System.setOut(originalOutputStream);
+ }
+
+ @Test
+ public void testCreateKnowledgeBase() throws Exception {
+ KnowledgeBaseManagement.createKnowledgeBase(PROJECT_ID, LOCATION, KNOWLEDGE_DISPLAY_NAME);
+ String output = bout.toString();
+ assertThat(output).contains(KNOWLEDGE_DISPLAY_NAME);
+ knowledgeBaseName = getResourceNameFromOutputString(output);
+ }
+}
diff --git a/dialogflow/snippets/src/test/java/com/example/dialogflow/DetectIntentKnowledgeTest.java b/dialogflow/snippets/src/test/java/com/example/dialogflow/DetectIntentKnowledgeTest.java
new file mode 100644
index 00000000000..0f1aa54d880
--- /dev/null
+++ b/dialogflow/snippets/src/test/java/com/example/dialogflow/DetectIntentKnowledgeTest.java
@@ -0,0 +1,100 @@
+/*
+ * Copyright 2018 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.dialogflow;
+
+import static com.google.common.truth.Truth.assertThat;
+import static org.junit.Assert.assertEquals;
+
+import com.google.cloud.dialogflow.v2beta1.DocumentName;
+import com.google.cloud.dialogflow.v2beta1.KnowledgeAnswers;
+import com.google.cloud.dialogflow.v2beta1.KnowledgeAnswers.Answer;
+import com.google.cloud.dialogflow.v2beta1.KnowledgeBaseName;
+import com.google.common.collect.ImmutableList;
+import java.io.ByteArrayOutputStream;
+import java.io.PrintStream;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+@RunWith(JUnit4.class)
+@SuppressWarnings("checkstyle:abbreviationaswordinname")
+public class DetectIntentKnowledgeTest {
+
+ private static String PROJECT_ID = System.getenv().get("GOOGLE_CLOUD_PROJECT");
+ private static String TEST_KNOWLEDGE_BASE_ID = "MTA4MzE0ODY5NTczMTQzNzU2ODA";
+ private static String TEST_DOCUMENT_ID = "MTUwNjk0ODg1NTU4NzkzMDExMg";
+ private static String SESSION_ID = UUID.randomUUID().toString();
+ private static String LANGUAGE_CODE = "en-US";
+
+ private static List TEXTS =
+ ImmutableList.of(
+ "How do I sign up?",
+ "Is my data redundant?",
+ "Where can I find pricing information?",
+ "Where is my data stored?",
+ "What are my support options?",
+ "How can I maximize the availability of my data?");
+
+ @Before
+ public void setUp() {
+ System.setOut(new PrintStream(new ByteArrayOutputStream()));
+ }
+
+ @After
+ public void tearDown() {
+ System.setOut(null);
+ }
+
+ @Test
+ public void testDetectIntentKnowledge() throws Exception {
+ KnowledgeBaseName knowledgeBaseName =
+ KnowledgeBaseName.newBuilder()
+ .setProject(PROJECT_ID)
+ .setKnowledgeBase(TEST_KNOWLEDGE_BASE_ID)
+ .build();
+
+ DocumentName documentName =
+ DocumentName.newBuilder()
+ .setProject(PROJECT_ID)
+ .setKnowledgeBase(TEST_KNOWLEDGE_BASE_ID)
+ .setDocument(TEST_DOCUMENT_ID)
+ .build();
+
+ Map allAnswers =
+ DetectIntentKnowledge.detectIntentKnowledge(
+ PROJECT_ID, knowledgeBaseName.toString(), SESSION_ID, LANGUAGE_CODE, TEXTS);
+ assertEquals(TEXTS.size(), allAnswers.size());
+ int answersFound = 0;
+ for (String text : TEXTS) {
+ KnowledgeAnswers knowledgeAnswers = allAnswers.get(text);
+ if (knowledgeAnswers.getAnswersCount() > 0) {
+ Answer answer = knowledgeAnswers.getAnswers(0);
+ if (text.equals(answer.getFaqQuestion())
+ && documentName.toString().equals(answer.getSource())) {
+ answersFound++;
+ }
+ }
+ }
+ // To make the test less flaky, check that half of the texts got a result.
+ assertThat(answersFound).isGreaterThan(TEXTS.size() / 2);
+ }
+}
diff --git a/dialogflow/snippets/src/test/java/com/example/dialogflow/DetectIntentStreamIT.java b/dialogflow/snippets/src/test/java/com/example/dialogflow/DetectIntentStreamIT.java
new file mode 100644
index 00000000000..a29f03be3a8
--- /dev/null
+++ b/dialogflow/snippets/src/test/java/com/example/dialogflow/DetectIntentStreamIT.java
@@ -0,0 +1,62 @@
+/*
+ * Copyright 2018 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.dialogflow;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.PrintStream;
+import java.util.UUID;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+/** Integration (system) tests for {@link DetectIntentStream}. */
+@RunWith(JUnit4.class)
+@SuppressWarnings("checkstyle:abbreviationaswordinname")
+public class DetectIntentStreamIT {
+
+ private static String audioFilePath = "resources/book_a_room.wav";
+ private static String PROJECT_ID = System.getenv().get("GOOGLE_CLOUD_PROJECT");
+ private static String SESSION_ID = UUID.randomUUID().toString();
+ private ByteArrayOutputStream bout;
+
+ @Before
+ public void setUp() {
+ bout = new ByteArrayOutputStream();
+ System.setOut(new PrintStream(bout));
+ }
+
+ @After
+ public void tearDown() {
+ System.setOut(null);
+ bout.reset();
+ }
+
+ @Test
+ public void testStreamingDetectIntentCallable() throws IOException {
+ DetectIntentStream.detectIntentStream(PROJECT_ID, audioFilePath, SESSION_ID);
+
+ String output = bout.toString();
+
+ assertThat(output).contains("Intent Display Name: room.reservation");
+ assertThat(output).contains("book");
+ }
+}
diff --git a/dialogflow/snippets/src/test/java/com/example/dialogflow/DetectIntentWithAudioTest.java b/dialogflow/snippets/src/test/java/com/example/dialogflow/DetectIntentWithAudioTest.java
new file mode 100644
index 00000000000..51649607304
--- /dev/null
+++ b/dialogflow/snippets/src/test/java/com/example/dialogflow/DetectIntentWithAudioTest.java
@@ -0,0 +1,94 @@
+/*
+ * Copyright 2018 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.dialogflow;
+
+import static com.google.common.truth.Truth.assertThat;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import java.io.ByteArrayOutputStream;
+import java.io.PrintStream;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+@RunWith(JUnit4.class)
+@SuppressWarnings("checkstyle:abbreviationaswordinname")
+public class DetectIntentWithAudioTest {
+ protected static String PROJECT_ID = System.getenv().get("GOOGLE_CLOUD_PROJECT");
+ protected static String SESSION_ID = UUID.randomUUID().toString();
+ protected static String LANGUAGE_CODE = "en-US";
+ protected static List QUESTIONS =
+ ImmutableList.of(
+ "What date?",
+ "What time will the meeting start?",
+ "How long will it last?",
+ "Thanks. How many people are attending?",
+ "I can help with that. Where would you like to reserve a room?");
+ protected static Map ANSWERS =
+ ImmutableMap.of(
+ "I can help with that. Where would you like to reserve a room?",
+ "resources/mountain_view.wav",
+ "What date?",
+ "resources/today.wav",
+ "What time will the meeting start?",
+ "resources/230pm.wav",
+ "How long will it last?",
+ "resources/half_an_hour.wav",
+ "Thanks. How many people are attending?",
+ "resources/two_people.wav");
+
+ @Before
+ public void setUp() {
+ System.setOut(new PrintStream(new ByteArrayOutputStream()));
+ }
+
+ @After
+ public void tearDown() {
+ System.setOut(null);
+ }
+
+ @Test
+ public void testDetectIntentAudio() throws Exception {
+ List askedQuestions = Lists.newArrayList();
+ com.google.cloud.dialogflow.v2.QueryResult result =
+ DetectIntentAudio.detectIntentAudio(
+ PROJECT_ID, "resources/book_a_room.wav", SESSION_ID, LANGUAGE_CODE);
+ String fulfillmentText = result.getFulfillmentText();
+ while (!result.getAllRequiredParamsPresent()
+ && ANSWERS.containsKey(fulfillmentText)
+ && !askedQuestions.contains(fulfillmentText)) {
+ askedQuestions.add(result.getFulfillmentText());
+ assertEquals("room.reservation", result.getAction());
+ assertThat(QUESTIONS).contains(fulfillmentText);
+ result =
+ DetectIntentAudio.detectIntentAudio(
+ PROJECT_ID, ANSWERS.get(fulfillmentText), SESSION_ID, LANGUAGE_CODE);
+ fulfillmentText = result.getFulfillmentText();
+ }
+ assertTrue(result.getAllRequiredParamsPresent());
+ assertEquals("Choose a room please.", fulfillmentText);
+ }
+}
diff --git a/dialogflow/snippets/src/test/java/com/example/dialogflow/DetectIntentWithSentimentAndTextToSpeechIT.java b/dialogflow/snippets/src/test/java/com/example/dialogflow/DetectIntentWithSentimentAndTextToSpeechIT.java
new file mode 100644
index 00000000000..64962cc77de
--- /dev/null
+++ b/dialogflow/snippets/src/test/java/com/example/dialogflow/DetectIntentWithSentimentAndTextToSpeechIT.java
@@ -0,0 +1,106 @@
+/*
+ * Copyright 2018 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.dialogflow;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
+import com.google.cloud.dialogflow.v2.QueryResult;
+import java.io.ByteArrayOutputStream;
+import java.io.PrintStream;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+/** Integration (system) tests for {@link DetectIntentWithSentimentAnalysis}. */
+@RunWith(JUnit4.class)
+@SuppressWarnings("checkstyle:abbreviationaswordinname")
+public class DetectIntentWithSentimentAndTextToSpeechIT {
+
+ private static String PROJECT_ID = System.getenv().get("GOOGLE_CLOUD_PROJECT");
+ private static String LOCATION_ID = "asia-northeast1";
+ private static String SESSION_ID = UUID.randomUUID().toString();
+ private static String LANGUAGE_CODE = "en-US";
+ private static List TEXTS =
+ Arrays.asList(
+ "hello",
+ "book a meeting room",
+ "Mountain View",
+ "tomorrow",
+ "10 am",
+ "2 hours",
+ "10 people",
+ "A",
+ "yes");
+
+ @Before
+ public void setUp() {
+ System.setOut(new PrintStream(new ByteArrayOutputStream()));
+ }
+
+ @After
+ public void tearDown() {
+ System.setOut(null);
+ }
+
+ @Test
+ public void testDetectIntentTexts() throws Exception {
+ Map queryResults =
+ DetectIntentTexts.detectIntentTexts(PROJECT_ID, TEXTS, SESSION_ID, LANGUAGE_CODE);
+ com.google.cloud.dialogflow.v2.QueryResult finalResult =
+ queryResults.get(TEXTS.get(TEXTS.size() - 1));
+ assertTrue(finalResult.getAllRequiredParamsPresent());
+ assertEquals("All set!", finalResult.getFulfillmentText());
+ }
+
+ @Test
+ public void testDetectIntentTextsWithLocation() throws Exception {
+ Map queryResults =
+ DetectIntentWithLocation.detectIntentWithLocation(
+ PROJECT_ID, LOCATION_ID, TEXTS, SESSION_ID, LANGUAGE_CODE);
+ com.google.cloud.dialogflow.v2beta1.QueryResult finalResult =
+ queryResults.get(TEXTS.get(TEXTS.size() - 1));
+ assertTrue(finalResult.getAllRequiredParamsPresent());
+ assertEquals("All set!", finalResult.getFulfillmentText());
+ }
+
+ @Test
+ public void testDetectIntentWithSentimentAnalysis() throws Exception {
+ assertResults(
+ DetectIntentWithSentimentAnalysis.detectIntentSentimentAnalysis(
+ PROJECT_ID, TEXTS, SESSION_ID, LANGUAGE_CODE));
+ }
+
+ @Test
+ public void testDetectIntentTextToSpeech() throws Exception {
+ assertResults(
+ DetectIntentWithTextToSpeechResponse.detectIntentWithTexttoSpeech(
+ PROJECT_ID, TEXTS, SESSION_ID, LANGUAGE_CODE));
+ }
+
+ private void assertResults(Map queryResults) {
+ QueryResult finalResult = queryResults.get(TEXTS.get(TEXTS.size() - 1));
+ assertTrue(finalResult.getAllRequiredParamsPresent());
+ assertEquals("All set!", finalResult.getFulfillmentText());
+ }
+}
diff --git a/dialogflow/snippets/src/test/java/com/example/dialogflow/IntentManagementIT.java b/dialogflow/snippets/src/test/java/com/example/dialogflow/IntentManagementIT.java
new file mode 100644
index 00000000000..09bdf8299dc
--- /dev/null
+++ b/dialogflow/snippets/src/test/java/com/example/dialogflow/IntentManagementIT.java
@@ -0,0 +1,98 @@
+/*
+ * Copyright 2018 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.dialogflow;
+
+import static com.google.common.truth.Truth.assertThat;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+
+import com.google.cloud.dialogflow.v2.AgentName;
+import com.google.cloud.dialogflow.v2.Intent;
+import com.google.cloud.dialogflow.v2.IntentsClient;
+import java.io.ByteArrayOutputStream;
+import java.io.PrintStream;
+import java.util.Arrays;
+import java.util.List;
+import java.util.UUID;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+/** Integration (system) tests for {@link IntentManagement}. */
+@RunWith(JUnit4.class)
+@SuppressWarnings("checkstyle:abbreviationaswordinname")
+public class IntentManagementIT {
+ private static String INTENT_DISPLAY_NAME = UUID.randomUUID().toString();
+ private static List MESSAGE_TEXTS =
+ Arrays.asList("fake_message_text_for_testing_1", "fake_message_text_for_testing_2");
+ private static List TRAINING_PHRASE_PARTS =
+ Arrays.asList("fake_training_phrase_part_1", "fake_training_phrase_part_2");
+ private static String PROJECT_ID = System.getenv().get("GOOGLE_CLOUD_PROJECT");
+
+ @Before
+ public void setUp() {
+ System.setOut(new PrintStream(new ByteArrayOutputStream()));
+ }
+
+ @After
+ public void tearDown() throws Exception {
+ try (IntentsClient intentsClient = IntentsClient.create()) {
+ // Set the project agent name using the projectID (my-project-id)
+ AgentName parent = AgentName.of(PROJECT_ID);
+
+ // Performs the list intents request
+ for (Intent intent : intentsClient.listIntents(parent).iterateAll()) {
+ if (intent.getDisplayName().equals(INTENT_DISPLAY_NAME)) {
+ intentsClient.deleteIntent(intent.getName());
+ }
+ }
+ }
+ System.setOut(null);
+ }
+
+ @Test
+ public void testCreateIntent() throws Exception {
+ // Create the intent
+ Intent intent =
+ IntentManagement.createIntent(
+ INTENT_DISPLAY_NAME, PROJECT_ID, TRAINING_PHRASE_PARTS, MESSAGE_TEXTS);
+ assertNotNull(intent);
+
+ List intentIds = IntentManagement.getIntentIds(intent.getDisplayName(), PROJECT_ID);
+ assertThat(intentIds.size()).isEqualTo(1);
+
+ List intents = IntentManagement.listIntents(PROJECT_ID);
+ assertTrue(intents.size() > 0);
+ assertThat(intents).contains(intent);
+ for (String messageText : MESSAGE_TEXTS) {
+ assertTrue(
+ intent.getMessagesList().stream()
+ .anyMatch(message -> message.getText().toString().contains(messageText)));
+ }
+
+ for (String intentId : intentIds) {
+ IntentManagement.deleteIntent(intentId, PROJECT_ID);
+ }
+
+ int numIntents = intents.size();
+ intents = IntentManagement.listIntents(PROJECT_ID);
+ assertEquals(numIntents - 1, intents.size());
+ }
+}
diff --git a/dialogflow/snippets/src/test/java/com/example/dialogflow/UpdateIntentIT.java b/dialogflow/snippets/src/test/java/com/example/dialogflow/UpdateIntentIT.java
new file mode 100644
index 00000000000..84d9cfb08fd
--- /dev/null
+++ b/dialogflow/snippets/src/test/java/com/example/dialogflow/UpdateIntentIT.java
@@ -0,0 +1,78 @@
+/*
+ * Copyright 2021 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.dialogflow;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import com.google.cloud.dialogflow.v2.Intent;
+import com.google.cloud.dialogflow.v2.IntentsClient;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.PrintStream;
+import java.util.UUID;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+
+public class UpdateIntentIT {
+
+ private static String PROJECT_ID = System.getenv().get("GOOGLE_CLOUD_PROJECT");
+
+ private static String parent = "projects/" + PROJECT_ID + "/locations/global/agent";
+ private static String intentID = "";
+ private static String intentPath = "";
+
+ private ByteArrayOutputStream stdOut;
+
+ @Before
+ public void setUp() throws IOException {
+
+ stdOut = new ByteArrayOutputStream();
+ System.setOut(new PrintStream(stdOut));
+
+ try (IntentsClient intentsClient = IntentsClient.create()) {
+ com.google.cloud.dialogflow.v2.Intent.Builder intent = Intent.newBuilder();
+ intent.setDisplayName("temp_intent_" + UUID.randomUUID().toString());
+
+ UpdateIntentIT.intentPath = intentsClient.createIntent(parent, intent.build()).getName();
+ UpdateIntentIT.intentID = UpdateIntentIT.intentPath.split("/")[6];
+ }
+ }
+
+ @After
+ public void tearDown() throws IOException {
+ stdOut = null;
+ System.setOut(null);
+
+ IntentsClient client = IntentsClient.create();
+
+ String intentPath =
+ "projects/" + PROJECT_ID + "/locations/global/agent/intents/" + UpdateIntentIT.intentID;
+
+ client.deleteIntent(intentPath);
+ }
+
+ @Test
+ public void testUpdateIntent() throws IOException {
+
+ String fakeIntent = "fake_intent_" + UUID.randomUUID().toString();
+
+ UpdateIntent.updateIntent(PROJECT_ID, UpdateIntentIT.intentID, "global", fakeIntent);
+
+ assertThat(stdOut.toString()).contains(fakeIntent);
+ }
+}