contexts = Lists.newArrayList();
// Instantiates a client
try (ContextsClient contextsClient = ContextsClient.create()) {
// Set the session name using the sessionId (UUID) and projectId (my-project-id)
SessionName session = SessionName.of(projectId, sessionId);
// Performs the list contexts request
- System.out.format("Contexts for session %s:\n", session.toString());
for (Context context : contextsClient.listContexts(session).iterateAll()) {
System.out.format("Context name: %s\n", context.getName());
System.out.format("Lifespan Count: %d\n", context.getLifespanCount());
@@ -61,20 +58,29 @@ public static void listContexts(String sessionId, String projectId) throws Excep
System.out.format("\t%s: %s\n", entry.getKey(), entry.getValue());
}
}
+
+ contexts.add(context);
}
}
+ return contexts;
}
// [END dialogflow_list_contexts]
// [START dialogflow_create_context]
+
/**
* Create an entity type with the given display name
- * @param contextId The Id of the context.
- * @param sessionId Identifier of the DetectIntent session.
+ *
+ * @param contextId The Id of the context.
+ * @param sessionId Identifier of the DetectIntent session.
* @param lifespanCount The lifespan count of the context.
- * @param projectId Project/Agent Id.
+ * @param projectId Project/Agent Id.
+ * @return The new Context.
*/
- public static void createContext(String contextId, String sessionId, String projectId,
+ public static Context createContext(
+ String contextId,
+ String sessionId,
+ String projectId,
int lifespanCount) throws Exception {
// Instantiates a client
try (ContextsClient contextsClient = ContextsClient.create()) {
@@ -97,13 +103,17 @@ public static void createContext(String contextId, String sessionId, String proj
// Performs the create context request
Context response = contextsClient.createContext(session, context);
System.out.format("Context created: %s\n", response);
+
+ return response;
}
}
// [END dialogflow_create_context]
// [START dialogflow_delete_context]
+
/**
* Delete entity type with the given entity type name
+ *
* @param contextId The Id of the context.
* @param sessionId Identifier of the DetectIntent session.
* @param projectId Project/Agent Id.
@@ -119,59 +129,4 @@ public static void deleteContext(String contextId, String sessionId, String proj
}
}
// [END dialogflow_delete_context]
-
- public static void main(String[] args) throws Exception {
- ArgumentParser parser =
- ArgumentParsers.newFor("ContextManagement")
- .build()
- .defaultHelp(true)
- .description("Create / List / Delete a context.");
-
- Subparsers subparsers = parser.addSubparsers().dest("command").title("Commands");
-
- Subparser listParser = subparsers.addParser("list")
- .help("mvn exec:java -DContextManagement -Dexec.args='list --sessionId SESSION_ID "
- + "--projectId PROJECT_ID'");
- listParser.addArgument("--sessionId")
- .help("Identifier of the DetectIntent session").required(true);
- listParser.addArgument("--projectId").help("Project/Agent Id").required(true);
-
- Subparser createParser = subparsers.addParser("create")
- .help("mvn exec:java -DContextManagement -Dexec.args='create --sessionId SESSION_ID "
- + "--projectId PROJECT_ID --contextId CONTEXT_ID'");
- createParser.addArgument("--sessionId")
- .help("Identifier of the DetectIntent session").required(true);
- createParser.addArgument("--projectId").help("Project/Agent Id").required(true);
- createParser.addArgument("--contextId")
- .help("The Id of the context")
- .required(true);
- createParser.addArgument("--lifespanCount")
- .help("The lifespan count of the context (Default: 1)").setDefault(1);
-
- Subparser deleteParser = subparsers.addParser("delete")
- .help("mvn exec:java -DContextManagement -Dexec.args='delete --sessionId SESSION_ID "
- + "--projectId PROJECT_ID --contextId CONTEXT_ID'");
- deleteParser.addArgument("--sessionId")
- .help("Identifier of the DetectIntent session").required(true);
- deleteParser.addArgument("--projectId").help("Project/Agent Id").required(true);
- deleteParser.addArgument("--contextId")
- .help("The Id of the context")
- .required(true);
-
- try {
- Namespace namespace = parser.parseArgs(args);
-
- if (namespace.get("command").equals("list")) {
- listContexts(namespace.get("sessionId"), namespace.get("projectId"));
- } else if (namespace.get("command").equals("create")) {
- createContext(namespace.get("contextId"), namespace.get("sessionId"),
- namespace.get("projectId"), namespace.get("lifespanCount"));
- } else if (namespace.get("command").equals("delete")) {
- deleteContext(namespace.get("contextId"), namespace.get("sessionId"),
- namespace.get("projectId"));
- }
- } catch (ArgumentParserException e) {
- parser.handleError(e);
- }
- }
}
diff --git a/dialogflow/cloud-client/src/main/java/com/example/dialogflow/DetectIntentAudio.java b/dialogflow/cloud-client/src/main/java/com/example/dialogflow/DetectIntentAudio.java
index c5d0c9a6fe8..6e3efd9d632 100644
--- a/dialogflow/cloud-client/src/main/java/com/example/dialogflow/DetectIntentAudio.java
+++ b/dialogflow/cloud-client/src/main/java/com/example/dialogflow/DetectIntentAudio.java
@@ -17,6 +17,7 @@
package com.example.dialogflow;
// Imports the Google Cloud client library
+
import com.google.cloud.dialogflow.v2.AudioEncoding;
import com.google.cloud.dialogflow.v2.DetectIntentRequest;
import com.google.cloud.dialogflow.v2.DetectIntentResponse;
@@ -29,29 +30,29 @@
import java.nio.file.Files;
import java.nio.file.Paths;
-import java.util.UUID;
-import net.sourceforge.argparse4j.ArgumentParsers;
-import net.sourceforge.argparse4j.inf.ArgumentParser;
-import net.sourceforge.argparse4j.inf.ArgumentParserException;
-import net.sourceforge.argparse4j.inf.Namespace;
/**
* DialogFlow API Detect Intent sample with audio files.
*/
public class DetectIntentAudio {
-
// [START dialogflow_detect_intent_audio]
+
/**
* Returns the result of detect intent with an audio file as input.
*
* Using the same `session_id` between requests allows continuation of the conversation.
- * @param projectId Project/Agent Id.
+ *
+ * @param projectId Project/Agent Id.
* @param audioFilePath Path to the audio file.
- * @param sessionId Identifier of the DetectIntent session.
- * @param languageCode Language code of the query.
+ * @param sessionId Identifier of the DetectIntent session.
+ * @param languageCode Language code of the query.
+ * @return QueryResult for the request.
*/
- public static void detectIntentAudio(String projectId, String audioFilePath, String sessionId,
+ public static QueryResult detectIntentAudio(
+ String projectId,
+ String audioFilePath,
+ String sessionId,
String languageCode)
throws Exception {
// Instantiates a client
@@ -95,40 +96,9 @@ public static void detectIntentAudio(String projectId, String audioFilePath, Str
System.out.format("Detected Intent: %s (confidence: %f)\n",
queryResult.getIntent().getDisplayName(), queryResult.getIntentDetectionConfidence());
System.out.format("Fulfillment Text: '%s'\n", queryResult.getFulfillmentText());
- }
- }
- // [END dialogflow_detect_intent_audio]
- public static void main(String[] args) throws Exception {
- ArgumentParser parser =
- ArgumentParsers.newFor("DetectIntentAudio")
- .build()
- .defaultHelp(true)
- .description("Returns the result of detect intent with an audio file as input.\n"
- + "mvn exec:java -DDetectIntentAudio -Dexec.args='--projectId PROJECT_ID "
- + "--audioFilePath resources/book_a_room.wav --sessionId SESSION_ID'");
-
- parser.addArgument("--projectId").help("Project/Agent Id").required(true);
-
- parser.addArgument("--audioFilePath")
- .help("Path to the audio file")
- .required(true);
-
- parser.addArgument("--sessionId")
- .help("Identifier of the DetectIntent session (Default: UUID.)")
- .setDefault(UUID.randomUUID().toString());
-
- parser.addArgument("--languageCode")
- .help("Language Code of the query (Default: en-US")
- .setDefault("en-US");
-
- try {
- Namespace namespace = parser.parseArgs(args);
-
- detectIntentAudio(namespace.get("projectId"), namespace.get("audioFilePath"),
- namespace.get("sessionId"), namespace.get("languageCode"));
- } catch (ArgumentParserException e) {
- parser.handleError(e);
+ return queryResult;
}
}
+ // [END dialogflow_detect_intent_audio]
}
diff --git a/dialogflow/cloud-client/src/main/java/com/example/dialogflow/DetectIntentKnowledge.java b/dialogflow/cloud-client/src/main/java/com/example/dialogflow/DetectIntentKnowledge.java
index 854803d964e..5205337bcb7 100644
--- a/dialogflow/cloud-client/src/main/java/com/example/dialogflow/DetectIntentKnowledge.java
+++ b/dialogflow/cloud-client/src/main/java/com/example/dialogflow/DetectIntentKnowledge.java
@@ -16,13 +16,12 @@
package com.example.dialogflow;
-
// Imports the Google Cloud client library
+
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.KnowledgeBaseName;
import com.google.cloud.dialogflow.v2beta1.QueryInput;
import com.google.cloud.dialogflow.v2beta1.QueryParameters;
import com.google.cloud.dialogflow.v2beta1.QueryResult;
@@ -30,38 +29,37 @@
import com.google.cloud.dialogflow.v2beta1.SessionsClient;
import com.google.cloud.dialogflow.v2beta1.TextInput;
import com.google.cloud.dialogflow.v2beta1.TextInput.Builder;
+import com.google.common.collect.Maps;
import java.util.List;
-import java.util.UUID;
-import net.sourceforge.argparse4j.ArgumentParsers;
-import net.sourceforge.argparse4j.inf.ArgumentParser;
-import net.sourceforge.argparse4j.inf.ArgumentParserException;
-import net.sourceforge.argparse4j.inf.Namespace;
-
+import java.util.Map;
-/** DialogFlow API Detect Intent sample with querying knowledge connector. */
+/**
+ * DialogFlow API Detect Intent sample with querying knowledge connector.
+ */
public class DetectIntentKnowledge {
-
// [START dialogflow_detect_intent_knowledge]
+
/**
* Returns the result of detect intent with text as input.
*
* Using the same `session_id` between requests allows continuation of the conversation.
*
- * @param projectId Project/Agent Id.
- * @param knowledgeBaseId Knowledge base Id.
- * @param sessionId Identifier of the DetectIntent session.
- * @param languageCode Language code of the query.
- * @param texts The texts to be processed.
+ * @param projectId Project/Agent Id.
+ * @param knowledgeBaseName Knowledge base Id.
+ * @param sessionId Identifier of the DetectIntent session.
+ * @param languageCode Language code of the query.
+ * @param texts The texts to be processed.
+ * @return The KnowledgeAnswers found for each text.
*/
- public static void detectIntentKnowledge(
+ public static Map detectIntentKnowledge(
String projectId,
- String knowledgeBaseId,
+ String knowledgeBaseName,
String sessionId,
String languageCode,
- List texts)
- throws Exception {
+ List texts) throws Exception {
// 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);
@@ -74,10 +72,9 @@ public static void detectIntentKnowledge(
// Build the query with the TextInput
QueryInput queryInput = QueryInput.newBuilder().setText(textInput).build();
- KnowledgeBaseName knowledgeBaseName = KnowledgeBaseName.of(projectId, knowledgeBaseId);
QueryParameters queryParameters =
QueryParameters.newBuilder()
- .addKnowledgeBaseNames(knowledgeBaseName.toString())
+ .addKnowledgeBaseNames(knowledgeBaseName)
.build();
DetectIntentRequest detectIntentRequest =
@@ -104,48 +101,12 @@ public static void detectIntentKnowledge(
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]
-
- public static void main(String[] args) throws Exception {
- ArgumentParser parser =
- ArgumentParsers.newFor("DetectIntentKnowledge")
- .build()
- .defaultHelp(true)
- .description("Returns the result of detect intent with text as input for a Knowledge "
- + "Base.\n"
- + "mvn exec:java -DDetectIntentKnowledge -Dexec.args=\"--projectId PROJECT_ID "
- + "--knowledgeBaseId KNOWLEDGE_BASE_ID -sessionId SESSION_ID "
- + "'Where can I find pricing information?'\"\n");
-
- parser.addArgument("--projectId").help("Project/Agent Id").required(true);
-
- parser.addArgument("--knowledgeBaseId")
- .help("The ID of the Knowledge Base")
- .required(true);
-
- parser.addArgument("--sessionId")
- .help("Identifier of the DetectIntent session (Default: UUID.)")
- .setDefault(UUID.randomUUID().toString());
-
- parser.addArgument("--languageCode")
- .help("Language Code of the query (Default: en-US")
- .setDefault("en-US");
-
- parser.addArgument("texts")
- .nargs("+")
- .help("Text: 'Where can I find pricing information?'")
- .required(true);
-
- try {
- Namespace namespace = parser.parseArgs(args);
-
- detectIntentKnowledge(namespace.get("projectId"), namespace.get("knowledgeBaseId"),
- namespace.get("sessionId"), namespace.get("languageCode"), namespace.get("texts"));
- } catch (ArgumentParserException e) {
- parser.handleError(e);
- }
- }
}
diff --git a/dialogflow/cloud-client/src/main/java/com/example/dialogflow/DetectIntentStream.java b/dialogflow/cloud-client/src/main/java/com/example/dialogflow/DetectIntentStream.java
index 2594b1bfb34..b531fd180d3 100644
--- a/dialogflow/cloud-client/src/main/java/com/example/dialogflow/DetectIntentStream.java
+++ b/dialogflow/cloud-client/src/main/java/com/example/dialogflow/DetectIntentStream.java
@@ -33,30 +33,29 @@
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;
-import java.util.UUID;
import java.util.concurrent.CountDownLatch;
-import net.sourceforge.argparse4j.ArgumentParsers;
-import net.sourceforge.argparse4j.inf.ArgumentParser;
-import net.sourceforge.argparse4j.inf.ArgumentParserException;
-import net.sourceforge.argparse4j.inf.Namespace;
-
/**
* DialogFlow API Detect Intent sample with audio files processes as an audio stream.
*/
public class DetectIntentStream {
-
// [START dialogflow_detect_intent_streaming]
+
/**
* Returns the result of detect intent with streaming audio as input.
*
* Using the same `session_id` between requests allows continuation of the conversation.
- * @param projectId Project/Agent Id.
+ *
+ * @param projectId Project/Agent Id.
* @param audioFilePath The audio file to be processed.
- * @param sessionId Identifier of the DetectIntent session.
- * @param languageCode Language code of the query.
+ * @param sessionId Identifier of the DetectIntent session.
+ * @param languageCode Language code of the query.
+ * @return The List of StreamingDetectIntentResponses to the input audio inputs.
*/
- public static void detectIntentStream(String projectId, String audioFilePath, String sessionId,
+ public static List detectIntentStream(
+ String projectId,
+ String audioFilePath,
+ String sessionId,
String languageCode) throws Throwable {
// Start bi-directional StreamingDetectIntent stream.
final CountDownLatch notification = new CountDownLatch(1);
@@ -159,40 +158,9 @@ public void onCompleted() {
System.out.format("Detected Intent: %s (confidence: %f)\n",
queryResult.getIntent().getDisplayName(), queryResult.getIntentDetectionConfidence());
System.out.format("Fulfillment Text: '%s'\n", queryResult.getFulfillmentText());
- }
- }
- // [END dialogflow_detect_intent_streaming]
- public static void main(String[] args) throws Throwable {
- ArgumentParser parser =
- ArgumentParsers.newFor("DetectIntentStream")
- .build()
- .defaultHelp(true)
- .description("Returns the result of detect intent with streaming audio as input.\n"
- + "mvn exec:java -DDetectIntentStream -Dexec.args='--projectId PROJECT_ID "
- + "--audioFilePath resources/book_a_room.wav --sessionId SESSION_ID'");
-
- parser.addArgument("--projectId").help("Project/Agent Id").required(true);
-
- parser.addArgument("--audioFilePath")
- .help("Path to the audio file")
- .required(true);
-
- parser.addArgument("--sessionId")
- .help("Identifier of the DetectIntent session (Default: UUID.)")
- .setDefault(UUID.randomUUID().toString());
-
- parser.addArgument("--languageCode")
- .help("Language Code of the query (Default: en-US")
- .setDefault("en-US");
-
- try {
- Namespace namespace = parser.parseArgs(args);
-
- detectIntentStream(namespace.get("projectId"), namespace.get("audioFilePath"),
- namespace.get("sessionId"), namespace.get("languageCode"));
- } catch (ArgumentParserException e) {
- parser.handleError(e);
+ return responses;
}
}
+ // [END dialogflow_detect_intent_streaming]
}
diff --git a/dialogflow/cloud-client/src/main/java/com/example/dialogflow/DetectIntentTexts.java b/dialogflow/cloud-client/src/main/java/com/example/dialogflow/DetectIntentTexts.java
index 388147fa231..19cad13bb3e 100644
--- a/dialogflow/cloud-client/src/main/java/com/example/dialogflow/DetectIntentTexts.java
+++ b/dialogflow/cloud-client/src/main/java/com/example/dialogflow/DetectIntentTexts.java
@@ -17,6 +17,7 @@
package com.example.dialogflow;
// Imports the Google Cloud client library
+
import com.google.cloud.dialogflow.v2.DetectIntentResponse;
import com.google.cloud.dialogflow.v2.QueryInput;
import com.google.cloud.dialogflow.v2.QueryResult;
@@ -24,32 +25,34 @@
import com.google.cloud.dialogflow.v2.SessionsClient;
import com.google.cloud.dialogflow.v2.TextInput;
import com.google.cloud.dialogflow.v2.TextInput.Builder;
+import com.google.common.collect.Maps;
import java.util.List;
-import java.util.UUID;
-import net.sourceforge.argparse4j.ArgumentParsers;
-import net.sourceforge.argparse4j.inf.ArgumentParser;
-import net.sourceforge.argparse4j.inf.ArgumentParserException;
-import net.sourceforge.argparse4j.inf.Namespace;
-
+import java.util.Map;
/**
* DialogFlow API Detect Intent sample with text inputs.
*/
public class DetectIntentTexts {
-
// [START dialogflow_detect_intent_text]
+
/**
* Returns the result of detect intent with texts as inputs.
*
* Using the same `session_id` between requests allows continuation of the conversation.
- * @param projectId Project/Agent Id.
- * @param texts The text intents to be detected based on what a user says.
- * @param sessionId Identifier of the DetectIntent session.
+ *
+ * @param projectId Project/Agent Id.
+ * @param texts The text intents to be detected based on what a user says.
+ * @param sessionId Identifier of the DetectIntent session.
* @param languageCode Language code of the query.
+ * @return The QueryResult for each input text.
*/
- public static void detectIntentTexts(String projectId, List texts, String sessionId,
+ public static Map detectIntentTexts(
+ String projectId,
+ List texts,
+ String sessionId,
String languageCode) throws Exception {
+ 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)
@@ -75,44 +78,11 @@ public static void detectIntentTexts(String projectId, List texts, Strin
System.out.format("Detected Intent: %s (confidence: %f)\n",
queryResult.getIntent().getDisplayName(), queryResult.getIntentDetectionConfidence());
System.out.format("Fulfillment Text: '%s'\n", queryResult.getFulfillmentText());
+
+ queryResults.put(text, queryResult);
}
}
+ return queryResults;
}
// [END dialogflow_detect_intent_text]
-
- public static void main(String[] args) throws Exception {
- ArgumentParser parser =
- ArgumentParsers.newFor("DetectIntentTexts")
- .build()
- .defaultHelp(true)
- .description("Returns the result of detect intent with text as input for a Knowledge "
- + "Base.\n"
- + "mvn exec:java -DDetectIntentTexts -Dexec.args=\"--projectId PROJECT_ID "
- + "--sessionId SESSION_ID 'hello' 'book a meeting room' 'Mountain View' 'tomorrow' "
- + "'10 am' '2 hours' '10 people' 'A' 'yes'\"\n");
-
- parser.addArgument("--projectId").help("Project/Agent Id").required(true);
-
- parser.addArgument("--sessionId")
- .help("Identifier of the DetectIntent session (Default: UUID.)")
- .setDefault(UUID.randomUUID().toString());
-
- parser.addArgument("--languageCode")
- .help("Language Code of the query (Default: en-US")
- .setDefault("en-US");
-
- parser.addArgument("texts")
- .nargs("+")
- .help("Text: 'Where can I find pricing information?'")
- .required(true);
-
- try {
- Namespace namespace = parser.parseArgs(args);
-
- detectIntentTexts(namespace.get("projectId"), namespace.get("texts"),
- namespace.get("sessionId"), namespace.get("languageCode"));
- } catch (ArgumentParserException e) {
- parser.handleError(e);
- }
- }
}
diff --git a/dialogflow/cloud-client/src/main/java/com/example/dialogflow/DetectIntentWithModelSelection.java b/dialogflow/cloud-client/src/main/java/com/example/dialogflow/DetectIntentWithModelSelection.java
index e4b842a45d6..f7dd04657ae 100644
--- a/dialogflow/cloud-client/src/main/java/com/example/dialogflow/DetectIntentWithModelSelection.java
+++ b/dialogflow/cloud-client/src/main/java/com/example/dialogflow/DetectIntentWithModelSelection.java
@@ -28,28 +28,26 @@
import java.nio.file.Files;
import java.nio.file.Paths;
-import java.util.UUID;
-import net.sourceforge.argparse4j.ArgumentParsers;
-import net.sourceforge.argparse4j.inf.ArgumentParser;
-import net.sourceforge.argparse4j.inf.ArgumentParserException;
-import net.sourceforge.argparse4j.inf.Namespace;
public class DetectIntentWithModelSelection {
-
// [START dialogflow_detect_intent_with_model_selection]
+
/**
* Returns the result of detect intent with an audio file as input.
*
* Using the same `session_id` between requests allows continuation of the conversation.
*
- * @param projectId Project/Agent Id.
+ * @param projectId Project/Agent Id.
* @param audioFilePath Path to the audio file.
- * @param sessionId Identifier of the DetectIntent session.
- * @param languageCode Language code of the query.
+ * @param sessionId Identifier of the DetectIntent session.
+ * @param languageCode Language code of the query.
+ * @return The QueryResult for the audio query.
*/
- public static void detectIntentWithModelSelection(
- String projectId, String sessionId, String audioFilePath, String languageCode)
- throws Exception {
+ public static QueryResult detectIntentWithModelSelection(
+ String projectId,
+ String audioFilePath,
+ String sessionId,
+ String languageCode) throws Exception {
// Instantiates a client
try (SessionsClient sessionsClient = SessionsClient.create()) {
// Set the session name using the sessionId (UUID) and projectID (my-project-id)
@@ -95,42 +93,9 @@ public static void detectIntentWithModelSelection(
"Detected Intent: %s (confidence: %f)\n",
queryResult.getIntent().getDisplayName(), queryResult.getIntentDetectionConfidence());
System.out.format("Fulfillment Text: '%s'\n", queryResult.getFulfillmentText());
- }
- }
- // [END dialogflow_detect_intent_with_model_selection]
-
-
- public static void main(String[] args) throws Exception {
- ArgumentParser parser =
- ArgumentParsers.newFor("DetectIntentWithModelSelection")
- .build()
- .defaultHelp(true)
- .description("Returns the result of detect intent with an audio file as input.\n"
- + "mvn exec:java -DDetectIntentWithModelSelection -Dexec.args='--projectId "
- + "PROJECT_ID --audioFilePath resources/book_a_room.wav --sessionId SESSION_ID'");
- parser.addArgument("--projectId").help("Project/Agent Id").required(true);
-
- parser.addArgument("--audioFilePath")
- .help("Path to the audio file")
- .required(true);
-
- parser.addArgument("--sessionId")
- .help("Identifier of the DetectIntent session (Default: UUID.)")
- .setDefault(UUID.randomUUID().toString());
-
- parser.addArgument("--languageCode")
- .help("Language Code of the query (Default: en-US")
- .setDefault("en-US");
-
- try {
- Namespace namespace = parser.parseArgs(args);
-
- detectIntentWithModelSelection(namespace.get("projectId"), namespace.get("audioFilePath"),
- namespace.get("sessionId"), namespace.get("languageCode"));
- } catch (ArgumentParserException e) {
- parser.handleError(e);
+ return queryResult;
}
}
-
+ // [END dialogflow_detect_intent_with_model_selection]
}
diff --git a/dialogflow/cloud-client/src/main/java/com/example/dialogflow/DetectIntentWithSentimentAnalysis.java b/dialogflow/cloud-client/src/main/java/com/example/dialogflow/DetectIntentWithSentimentAnalysis.java
index 4194074e716..b75e1a541cd 100644
--- a/dialogflow/cloud-client/src/main/java/com/example/dialogflow/DetectIntentWithSentimentAnalysis.java
+++ b/dialogflow/cloud-client/src/main/java/com/example/dialogflow/DetectIntentWithSentimentAnalysis.java
@@ -26,30 +26,31 @@
import com.google.cloud.dialogflow.v2beta1.SessionsClient;
import com.google.cloud.dialogflow.v2beta1.TextInput;
import com.google.cloud.dialogflow.v2beta1.TextInput.Builder;
+import com.google.common.collect.Maps;
import java.util.List;
-import java.util.UUID;
-import net.sourceforge.argparse4j.ArgumentParsers;
-import net.sourceforge.argparse4j.inf.ArgumentParser;
-import net.sourceforge.argparse4j.inf.ArgumentParserException;
-import net.sourceforge.argparse4j.inf.Namespace;
+import java.util.Map;
public class DetectIntentWithSentimentAnalysis {
-
// [START dialogflow_detect_intent_with_sentiment_analysis]
+
/**
* Returns the result of detect intent with texts as inputs.
*
*
Using the same `session_id` between requests allows continuation of the conversation.
*
- * @param projectId Project/Agent Id.
- * @param texts The text intents to be detected based on what a user says.
- * @param sessionId Identifier of the DetectIntent session.
+ * @param projectId Project/Agent Id.
+ * @param texts The text intents to be detected based on what a user says.
+ * @param sessionId Identifier of the DetectIntent session.
* @param languageCode Language code of the query.
+ * @return The QueryResult for each text in query.
*/
- public static void detectIntentSentimentAnalysis(
- String projectId, List texts, String sessionId, String languageCode)
- throws Exception {
+ public static Map detectIntentSentimentAnalysis(
+ String projectId,
+ List texts,
+ String sessionId,
+ String languageCode) throws Exception {
+ 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)
@@ -94,47 +95,11 @@ public static void detectIntentSentimentAnalysis(
System.out.format(
"Sentiment Score: '%s'\n",
queryResult.getSentimentAnalysisResult().getQueryTextSentiment().getScore());
+
+ queryResults.put(text, queryResult);
}
}
+ return queryResults;
}
// [END dialogflow_detect_intent_with_sentiment_analysis]
-
-
- public static void main(String[] args) throws Exception {
- ArgumentParser parser =
- ArgumentParsers.newFor("DetectIntentWithSentimentAnalysis")
- .build()
- .defaultHelp(true)
- .description("Returns the result of detect intent with text as input"
- + "Base.\n"
- + "mvn exec:java -DDetectIntentWithSentimentAnalysis -Dexec.args=\"--projectId "
- + "PROJECT_ID --sessionId SESSION_ID 'hello' 'book a meeting room' 'Mountain View' "
- + "'tomorrow' '10 am' '2 hours' '10 people' 'A' 'yes'\"\n");
-
- parser.addArgument("--projectId").help("Project/Agent Id").required(true);
-
- parser.addArgument("--sessionId")
- .help("Identifier of the DetectIntent session (Default: UUID.)")
- .setDefault(UUID.randomUUID().toString());
-
- parser.addArgument("--languageCode")
- .help("Language Code of the query (Default: en-US")
- .setDefault("en-US");
-
- parser.addArgument("texts")
- .nargs("+")
- .help("Text: 'Where can I find pricing information?'")
- .required(true);
-
- try {
- Namespace namespace = parser.parseArgs(args);
-
- detectIntentSentimentAnalysis(namespace.get("projectId"), namespace.get("texts"),
- namespace.get("sessionId"), namespace.get("languageCode"));
- } catch (ArgumentParserException e) {
- parser.handleError(e);
- }
- }
-
-
}
diff --git a/dialogflow/cloud-client/src/main/java/com/example/dialogflow/DetectIntentWithTextToSpeechResponse.java b/dialogflow/cloud-client/src/main/java/com/example/dialogflow/DetectIntentWithTextToSpeechResponse.java
index c6acfd84922..da053d1017d 100644
--- a/dialogflow/cloud-client/src/main/java/com/example/dialogflow/DetectIntentWithTextToSpeechResponse.java
+++ b/dialogflow/cloud-client/src/main/java/com/example/dialogflow/DetectIntentWithTextToSpeechResponse.java
@@ -26,30 +26,31 @@
import com.google.cloud.dialogflow.v2beta1.SessionsClient;
import com.google.cloud.dialogflow.v2beta1.TextInput;
import com.google.cloud.dialogflow.v2beta1.TextInput.Builder;
+import com.google.common.collect.Maps;
import java.util.List;
-import java.util.UUID;
-import net.sourceforge.argparse4j.ArgumentParsers;
-import net.sourceforge.argparse4j.inf.ArgumentParser;
-import net.sourceforge.argparse4j.inf.ArgumentParserException;
-import net.sourceforge.argparse4j.inf.Namespace;
+import java.util.Map;
public class DetectIntentWithTextToSpeechResponse {
-
// [START dialogflow_detect_intent_with_texttospeech_response]
+
/**
* Returns the result of detect intent with texts as inputs.
*
* Using the same `session_id` between requests allows continuation of the conversation.
*
- * @param projectId Project/Agent Id.
- * @param texts The text intents to be detected based on what a user says.
- * @param sessionId Identifier of the DetectIntent session.
+ * @param projectId Project/Agent Id.
+ * @param texts The text intents to be detected based on what a user says.
+ * @param sessionId Identifier of the DetectIntent session.
* @param languageCode Language code of the query.
+ * @return The QueryResult for each input text.
*/
- public static void detectIntentWithTexttoSpeech(
- String projectId, List texts, String sessionId, String languageCode)
- throws Exception {
+ public static Map detectIntentWithTexttoSpeech(
+ String projectId,
+ List texts,
+ String sessionId,
+ String languageCode) throws Exception {
+ 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)
@@ -81,8 +82,6 @@ public static void detectIntentWithTexttoSpeech(
.build();
// Performs the detect intent request
- // DetectIntentResponse response = sessionsClient.detectIntent(session,
- // queryInput,outputAudioConfig);
DetectIntentResponse response = sessionsClient.detectIntent(dr);
// Display the query result
@@ -94,48 +93,11 @@ public static void detectIntentWithTexttoSpeech(
"Detected Intent: %s (confidence: %f)\n",
queryResult.getIntent().getDisplayName(), queryResult.getIntentDetectionConfidence());
System.out.format("Fulfillment Text: '%s'\n", queryResult.getFulfillmentText());
+
+ queryResults.put(text, queryResult);
}
}
+ return queryResults;
}
-
// [END dialogflow_detect_intent_with_texttospeech_response]
-
-
- public static void main(String[] args) throws Exception {
- ArgumentParser parser =
- ArgumentParsers.newFor("DetectIntentWithTextToSpeechResponse")
- .build()
- .defaultHelp(true)
- .description("Returns the result of detect intent with text as input"
- + "Base.\n"
- + "mvn exec:java -DDetectIntentWithTTSResponses -Dexec.args=\"--projectId "
- + "PROJECT_ID --sessionId SESSION_ID 'hello' 'book a meeting room' 'Mountain View' "
- + "'tomorrow' '10 am' '2 hours' '10 people' 'A' 'yes'\"\n");
-
- parser.addArgument("--projectId").help("Project/Agent Id").required(true);
-
- parser.addArgument("--sessionId")
- .help("Identifier of the DetectIntent session (Default: UUID.)")
- .setDefault(UUID.randomUUID().toString());
-
- parser.addArgument("--languageCode")
- .help("Language Code of the query (Default: en-US")
- .setDefault("en-US");
-
- parser.addArgument("texts")
- .nargs("+")
- .help("Text: 'Where can I find pricing information?'")
- .required(true);
-
- try {
- Namespace namespace = parser.parseArgs(args);
-
- detectIntentWithTexttoSpeech(namespace.get("projectId"), namespace.get("texts"),
- namespace.get("sessionId"), namespace.get("languageCode"));
- } catch (ArgumentParserException e) {
- parser.handleError(e);
- }
- }
-
-
}
diff --git a/dialogflow/cloud-client/src/main/java/com/example/dialogflow/DocumentManagement.java b/dialogflow/cloud-client/src/main/java/com/example/dialogflow/DocumentManagement.java
index 49ba5d8a650..bfdecb8899e 100644
--- a/dialogflow/cloud-client/src/main/java/com/example/dialogflow/DocumentManagement.java
+++ b/dialogflow/cloud-client/src/main/java/com/example/dialogflow/DocumentManagement.java
@@ -20,28 +20,22 @@
import com.google.cloud.dialogflow.v2beta1.CreateDocumentRequest;
import com.google.cloud.dialogflow.v2beta1.Document;
import com.google.cloud.dialogflow.v2beta1.Document.KnowledgeType;
-import com.google.cloud.dialogflow.v2beta1.DocumentName;
import com.google.cloud.dialogflow.v2beta1.DocumentsClient;
-import com.google.cloud.dialogflow.v2beta1.KnowledgeBaseName;
import com.google.cloud.dialogflow.v2beta1.KnowledgeOperationMetadata;
-import net.sourceforge.argparse4j.ArgumentParsers;
-import net.sourceforge.argparse4j.inf.ArgumentParser;
-import net.sourceforge.argparse4j.inf.ArgumentParserException;
-import net.sourceforge.argparse4j.inf.Namespace;
-import net.sourceforge.argparse4j.inf.Subparser;
-import net.sourceforge.argparse4j.inf.Subparsers;
+import com.google.common.collect.Lists;
-public class DocumentManagement {
+import java.util.List;
+public class DocumentManagement {
// [START dialogflow_list_document]
+
/**
- * @param projectId Project/Agent id.
- * @param knowledgeBaseId Knowledge Base id.
+ * @param knowledgeBaseName Knowledge Base id.
*/
- public static void listDocuments(String projectId, String knowledgeBaseId) throws Exception {
+ public static List listDocuments(String knowledgeBaseName) throws Exception {
+ List documents = Lists.newArrayList();
// Instantiates a client
try (DocumentsClient documentsClient = DocumentsClient.create()) {
- KnowledgeBaseName knowledgeBaseName = KnowledgeBaseName.of(projectId, knowledgeBaseId);
for (Document document : documentsClient.listDocuments(knowledgeBaseName).iterateAll()) {
System.out.format(" - Display Name: %s\n", document.getDisplayName());
System.out.format(" - Knowledge ID: %s\n", document.getName());
@@ -51,23 +45,26 @@ public static void listDocuments(String projectId, String knowledgeBaseId) throw
System.out.format(" - %s \n", knowledgeTypeId.getValueDescriptor());
}
System.out.format(" - Source: %s \n", document.getContentUri());
+
+ documents.add(document);
}
}
+ return documents;
}
// [END dialogflow_list_document]
// [START dialogflow_create_document]
+
/**
- * @param projectId Project/Agent id.
- * @param knowledgeBaseId Knowledge Base id.
- * @param displayName display name of the Document.
- * @param mimeType MIME type of the Document. e.g. text/csv, text/html
- * @param knowledgeType Knowledge Type of the Document. e.g. FAQ, EXTRACTIVE_QA
- * @param contentUri Uri of the Document. e.g. gs://path/mydoc.csv, http://mypage.com/faq.html
+ * @param knowledgeBaseName Knowledge Base id.
+ * @param displayName display name of the Document.
+ * @param mimeType MIME type of the Document. e.g. text/csv, text/html
+ * @param knowledgeType Knowledge Type of the Document. e.g. FAQ, EXTRACTIVE_QA
+ * @param contentUri Uri of the Document. e.g. gs://path/mydoc.csv, http://mypage.com/faq.html
+ * @return The created document.
*/
- public static void createDocument(
- String projectId,
- String knowledgeBaseId,
+ public static Document createDocument(
+ String knowledgeBaseName,
String displayName,
String mimeType,
String knowledgeType,
@@ -82,38 +79,37 @@ public static void createDocument(
.setMimeType(mimeType)
.addKnowledgeTypes(KnowledgeType.valueOf(knowledgeType))
.build();
- KnowledgeBaseName parent = KnowledgeBaseName.of(projectId, knowledgeBaseId);
CreateDocumentRequest createDocumentRequest =
CreateDocumentRequest.newBuilder()
.setDocument(document)
- .setParent(parent.toString())
+ .setParent(knowledgeBaseName)
.build();
OperationFuture response =
documentsClient.createDocumentAsync(createDocumentRequest);
+ Document createdDocument = response.get();
System.out.format("Created Document:\n");
- System.out.format(" - Display Name: %s\n", response.get().getDisplayName());
- System.out.format(" - Knowledge ID: %s\n", response.get().getName());
- System.out.format(" - MIME Type: %s\n", response.get().getMimeType());
+ System.out.format(" - Display Name: %s\n", createdDocument.getDisplayName());
+ System.out.format(" - Knowledge ID: %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());
+ return createdDocument;
}
}
// [END dialogflow_create_document]
// [START dialogflow_get_document]
+
/**
- * @param projectId Project/Agent id.
- * @param knowledgeBaseId Knowledge Base id.
- * @param documentId Document Id.
+ * @param documentName Document Id.
+ * @return The requested document.
*/
- public static void getDocument(String projectId, String knowledgeBaseId, String documentId)
- throws Exception {
+ public static Document getDocument(String documentName) throws Exception {
// Instantiates a client
try (DocumentsClient documentsClient = DocumentsClient.create()) {
- DocumentName documentName = DocumentName.of(projectId, knowledgeBaseId, documentId);
Document response = documentsClient.getDocument(documentName);
System.out.format("Got Document: \n");
System.out.format(" - Display Name: %s\n", response.getDisplayName());
@@ -124,97 +120,22 @@ public static void getDocument(String projectId, String knowledgeBaseId, String
System.out.format(" - %s \n", knowledgeTypeId.getValueDescriptor());
}
System.out.format(" - Source: %s \n", response.getContentUri());
+
+ return response;
}
}
// [END dialogflow_get_document]
// [START dialogflow_delete_document]
+
/**
- * @param projectId Project/Agent id.
- * @param knowledgeBaseId Knowledge Base id.
- * @param documentId Document Id.
+ * @param documentName Document Id.
*/
- public static void deleteDocument(String projectId, String knowledgeBaseId, String documentId)
- throws Exception {
+ public static void deleteDocument(String documentName) throws Exception {
// Instantiates a client
try (DocumentsClient documentsClient = DocumentsClient.create()) {
- DocumentName documentName = DocumentName.of(projectId, knowledgeBaseId, documentId);
documentsClient.deleteDocumentAsync(documentName).getInitialFuture().get();
System.out.format("The document has been deleted.");
}
}
-
- public static void main(String[] args) throws Exception {
- ArgumentParser parser =
- ArgumentParsers.newFor("DocumentManagement")
- .build()
- .defaultHelp(true)
- .description("Create / List / Delete a Document.");
-
- Subparsers subparsers = parser.addSubparsers().dest("command").title("Commands");
-
- Subparser listParser = subparsers.addParser("list")
- .help("mvn exec:java -DDocumentManagement -Dexec.args='list --projectId PROJECT_ID "
- + "--knowledgeBaseId KNOWLEDGE_BASE_ID'");
- listParser.addArgument("--projectId").help("Project/Agent Id").required(true);
- listParser.addArgument("--knowledgeBaseId")
- .help("The id of the Knowledge Base to list the Documents").required(true);
-
- Subparser createParser = subparsers.addParser("create")
- .help("mvn exec:java -DDocumentManagement -Dexec.args='create --projectId PROJECT_ID "
- + "--knowledgeBaseId KNOWLEDGE_BASE_ID --displayName DISPLAY_NAME "
- + "--mimeType text/html --knowledgeType FAQ "
- + "--contentUri https://cloud.google.com/storage/docs/faq'");
- createParser.addArgument("--projectId").help("Project/Agent Id").required(true);
- createParser.addArgument("--knowledgeBaseId")
- .help("The ID of the Knowledge Base to list the Documents").required(true);
- createParser.addArgument("--displayName")
- .help("The display name of the Document").required(true);
- createParser.addArgument("--mimeType")
- .help("The mime-type of the Document, e.g. text/csv, text/html, text/plain, text/pdf etc.")
- .required(true);
- createParser.addArgument("--knowledgeType")
- .help("The knowledge-type of the Document, e.g. FAQ, EXTRACTIVE_QA.").required(true);
- createParser.addArgument("--contentUri")
- .help("The uri of the Document, e.g. gs://path/mydoc.csv, http://mypage.com/faq.html")
- .required(true);
-
- Subparser getParser = subparsers.addParser("get")
- .help("mvn exec:java -DDocumentManagement -Dexec.args='get --projectId PROJECT_ID "
- + "--knowledgeBaseId KNOWLEDGE_BASE_ID --documentId DOCUMENT_ID'");
- getParser.addArgument("--projectId").help("Project/Agent Id").required(true);
- getParser.addArgument("--knowledgeBaseId")
- .help("The ID of the Knowledge Base to list the Documents").required(true);
- getParser.addArgument("--documentId")
- .help("The ID of the Document you want to delete").required(true);
-
- Subparser deleteParser = subparsers.addParser("delete")
- .help("mvn exec:java -DDocumentManagement -Dexec.args='delete --projectId PROJECT_ID "
- + "--knowledgeBaseId KNOWLEDGE_BASE_ID --documentId DOCUMENT_ID'");
- deleteParser.addArgument("--projectId").help("Project/Agent Id").required(true);
- deleteParser.addArgument("--knowledgeBaseId")
- .help("The ID of the Knowledge Base to list the Documents").required(true);
- deleteParser.addArgument("--documentId")
- .help("The ID of the Document you want to delete").required(true);
-
- try {
- Namespace namespace = parser.parseArgs(args);
-
- if (namespace.get("command").equals("list")) {
- listDocuments(namespace.get("projectId"), namespace.get("knowledgeBaseId"));
- } else if (namespace.get("command").equals("create")) {
- createDocument(namespace.get("projectId"), namespace.get("knowledgeBaseId"),
- namespace.get("displayName"), namespace.get("mimeType"), namespace.get("knowledgeType"),
- namespace.get("contentUri"));
- } else if (namespace.get("command").equals("get")) {
- getDocument(namespace.get("projectId"), namespace.get("knowledgeBaseId"),
- namespace.get("documentId"));
- } else if (namespace.get("command").equals("delete")) {
- deleteDocument(namespace.get("projectId"), namespace.get("knowledgeBaseId"),
- namespace.get("documentId"));
- }
- } catch (ArgumentParserException e) {
- parser.handleError(e);
- }
- }
}
diff --git a/dialogflow/cloud-client/src/main/java/com/example/dialogflow/EntityManagement.java b/dialogflow/cloud-client/src/main/java/com/example/dialogflow/EntityManagement.java
index 63a48914e73..0d982693e0d 100644
--- a/dialogflow/cloud-client/src/main/java/com/example/dialogflow/EntityManagement.java
+++ b/dialogflow/cloud-client/src/main/java/com/example/dialogflow/EntityManagement.java
@@ -17,35 +17,30 @@
package com.example.dialogflow;
// Imports the Google Cloud client library
+
import com.google.cloud.dialogflow.v2.EntityType;
import com.google.cloud.dialogflow.v2.EntityType.Entity;
import com.google.cloud.dialogflow.v2.EntityTypeName;
import com.google.cloud.dialogflow.v2.EntityTypesClient;
import com.google.protobuf.Empty;
-import java.util.ArrayList;
-import java.util.Arrays;
+import java.util.Collections;
import java.util.List;
-import net.sourceforge.argparse4j.ArgumentParsers;
-import net.sourceforge.argparse4j.inf.ArgumentParser;
-import net.sourceforge.argparse4j.inf.ArgumentParserException;
-import net.sourceforge.argparse4j.inf.Namespace;
-import net.sourceforge.argparse4j.inf.Subparser;
-import net.sourceforge.argparse4j.inf.Subparsers;
-
/**
* DialogFlow API Entity sample.
*/
public class EntityManagement {
-
// [START dialogflow_list_entities]
+
/**
* List entities
- * @param projectId Project/agent id.
+ *
+ * @param projectId Project/agent id.
* @param entityTypeId The id of the entity_type.
+ * @return List of found entities.
*/
- public static void listEntities(String projectId, String entityTypeId) throws Exception {
+ public static List listEntities(String projectId, String entityTypeId) throws Exception {
// Instantiates a client
try (EntityTypesClient entityTypesClient = EntityTypesClient.create()) {
// Set the entity type name using the projectID (my-project-id) and entityTypeId (KIND_LIST)
@@ -53,23 +48,30 @@ public static void listEntities(String projectId, String entityTypeId) throws Ex
// Performs the get entity type request
EntityType entityType = entityTypesClient.getEntityType(name);
- for (Entity entity : entityType.getEntitiesList()) {
+ List entities = entityType.getEntitiesList();
+ for (Entity entity : entities) {
System.out.format("Entity value: %s\n", entity.getValue());
System.out.format("Entity synonyms: %s\n", entity.getSynonymsList().toString());
}
+ return entities;
}
}
// [END dialogflow_list_entities]
// [START dialogflow_create_entity]
+
/**
* Create an entity of the given entity type
- * @param projectId Project/agent id.
+ *
+ * @param projectId Project/agent id.
* @param entityTypeId The id of the entity_type.
- * @param entityValue The entity value to be added.
- * @param synonyms The synonyms that will map to the provided entity value.
+ * @param entityValue The entity value to be added.
+ * @param synonyms The synonyms that will map to the provided entity value.
*/
- public static void createEntity(String projectId, String entityTypeId, String entityValue,
+ public static void createEntity(
+ String projectId,
+ String entityTypeId,
+ String entityValue,
List synonyms) throws Exception {
// Note: synonyms must be exactly [entityValue] if the
// entityTypeId's kind is KIND_LIST
@@ -90,20 +92,20 @@ public static void createEntity(String projectId, String entityTypeId, String en
// Performs the create entity type request
Empty response = entityTypesClient.batchCreateEntitiesAsync(name,
- Arrays.asList(entity)).get();
+ Collections.singletonList(entity)).get();
System.out.println("Entity created: " + response);
}
-
-
}
// [END dialogflow_create_entity]
// [START dialogflow_delete_entity]
+
/**
* Delete entity with the given entity type and entity value
- * @param projectId Project/agent id.
+ *
+ * @param projectId Project/agent id.
* @param entityTypeId The id of the entity_type.
- * @param entityValue The value of the entity to delete.
+ * @param entityValue The value of the entity to delete.
*/
public static void deleteEntity(String projectId, String entityTypeId, String entityValue)
throws Exception {
@@ -113,67 +115,9 @@ public static void deleteEntity(String projectId, String entityTypeId, String en
EntityTypeName name = EntityTypeName.of(projectId, entityTypeId);
// Performs the delete entity type request
- entityTypesClient.batchDeleteEntitiesAsync(name, Arrays.asList(entityValue))
+ entityTypesClient.batchDeleteEntitiesAsync(name, Collections.singletonList(entityValue))
.getInitialFuture().get();
}
}
// [END dialogflow_delete_entity]
-
- public static void main(String[] args) throws Exception {
- ArgumentParser parser =
- ArgumentParsers.newFor("EntityManagement")
- .build()
- .defaultHelp(true)
- .description("Create / List / Delete a Entity.");
-
- Subparsers subparsers = parser.addSubparsers().dest("command").title("Commands");
-
- Subparser listParser = subparsers.addParser("list")
- .help("mvn exec:java -DEntityManagement -Dexec.args='list --projectId PROJECT_ID "
- + "--entityTypeId ENTITY_TYPE_ID'");
- listParser.addArgument("--projectId").help("Project/Agent Id").required(true);
- listParser.addArgument("--entityTypeId")
- .help("The id of the entityType to which to add an entity.").required(true);
-
- Subparser createParser = subparsers.addParser("create")
- .help("mvn exec:java -DEntityManagement -Dexec.args='create ENTITY_VALUE "
- + "--projectId PROJECT_ID --entityTypeId ENTITY_TYPE_ID "
- + "--synonyms basement cellar'");
- createParser.addArgument("entityValue")
- .help("The entity value to be added.").required(true);
- createParser.addArgument("--projectId").help("Project/Agent Id").required(true);
- createParser.addArgument("--entityTypeId")
- .help("The id of the entityType to which to add an entity.").required(true);
- createParser.addArgument("--synonyms").nargs("+")
- .help("The synonyms that will map to the provided entity value");
-
- Subparser deleteParser = subparsers.addParser("delete")
- .help("mvn exec:java -DEntityManagement -Dexec.args='delete ENTITY_VALUE "
- + "--projectId PROJECT_ID --entityTypeId ENTITY_TYPE_ID'");
- deleteParser.addArgument("entityValue")
- .help("The entity value to be added.").required(true);
- deleteParser.addArgument("--projectId").help("Project/Agent Id").required(true);
- deleteParser.addArgument("--entityTypeId")
- .help("The id of the entityType to delete.").required(true);
-
- try {
- Namespace namespace = parser.parseArgs(args);
-
- if (namespace.get("command").equals("list")) {
- listEntities(namespace.get("projectId"), namespace.get("entityTypeId"));
- } else if (namespace.get("command").equals("create")) {
- ArrayList synonyms = new ArrayList<>();
- if (namespace.get("synonyms") == null) {
- synonyms = namespace.get("synonyms");
- }
- createEntity(namespace.get("projectId"), namespace.get("entityTypeId"),
- namespace.get("entityValue"), synonyms);
- } else if (namespace.get("command").equals("delete")) {
- deleteEntity(namespace.get("projectId"), namespace.get("entityTypeId"),
- namespace.get("entityValue"));
- }
- } catch (ArgumentParserException e) {
- parser.handleError(e);
- }
- }
}
diff --git a/dialogflow/cloud-client/src/main/java/com/example/dialogflow/EntityTypeManagement.java b/dialogflow/cloud-client/src/main/java/com/example/dialogflow/EntityTypeManagement.java
index 3eb4466e534..04740c40b42 100644
--- a/dialogflow/cloud-client/src/main/java/com/example/dialogflow/EntityTypeManagement.java
+++ b/dialogflow/cloud-client/src/main/java/com/example/dialogflow/EntityTypeManagement.java
@@ -16,35 +16,32 @@
package com.example.dialogflow;
-
// Imports the Google Cloud client library
+
import com.google.cloud.dialogflow.v2.EntityType;
import com.google.cloud.dialogflow.v2.EntityType.Kind;
import com.google.cloud.dialogflow.v2.EntityTypeName;
import com.google.cloud.dialogflow.v2.EntityTypesClient;
import com.google.cloud.dialogflow.v2.ProjectAgentName;
+import com.google.common.collect.Lists;
import java.util.ArrayList;
import java.util.List;
-import net.sourceforge.argparse4j.ArgumentParsers;
-import net.sourceforge.argparse4j.inf.ArgumentParser;
-import net.sourceforge.argparse4j.inf.ArgumentParserException;
-import net.sourceforge.argparse4j.inf.Namespace;
-import net.sourceforge.argparse4j.inf.Subparser;
-import net.sourceforge.argparse4j.inf.Subparsers;
-
/**
* DialogFlow API EntityType sample.
*/
public class EntityTypeManagement {
-
// [START dialogflow_list_entity_types]
+
/**
* List entity types
+ *
* @param projectId Project/agent id.
+ * @return The EntityTypes found.
*/
- public static void listEntityTypes(String projectId) throws Exception {
+ public static List listEntityTypes(String projectId) throws Exception {
+ List entityTypes = Lists.newArrayList();
// Instantiates a client
try (EntityTypesClient entityTypesClient = EntityTypesClient.create()) {
// Set the project agent name using the projectID (my-project-id)
@@ -55,19 +52,25 @@ public static void listEntityTypes(String projectId) throws Exception {
System.out.format("Entity type name %s\n", entityType.getName());
System.out.format("Entity type display name: %s\n", entityType.getDisplayName());
System.out.format("Number of entities: %d\n", entityType.getEntitiesCount());
+
+ entityTypes.add(entityType);
}
}
+ return entityTypes;
}
// [END dialogflow_list_entity_types]
// [START dialogflow_create_entity_type]
+
/**
* Create an entity type with the given display name
+ *
* @param displayName The display name of the entity.
- * @param projectId Project/agent id.
- * @param kind The kind of entity. KIND_MAP (default) or KIND_LIST.
+ * @param projectId Project/agent id.
+ * @param kind The kind of entity. KIND_MAP (default) or KIND_LIST.
+ * @return The created EntityType.
*/
- public static void createEntityType(String displayName, String projectId, String kind)
+ public static EntityType createEntityType(String displayName, String projectId, String kind)
throws Exception {
// Instantiates a client
try (EntityTypesClient entityTypesClient = EntityTypesClient.create()) {
@@ -83,15 +86,18 @@ public static void createEntityType(String displayName, String projectId, String
// Performs the create entity type request
EntityType response = entityTypesClient.createEntityType(parent, entityType);
System.out.println("Entity type created: " + response);
+ return response;
}
}
// [END dialogflow_create_entity_type]
// [START dialogflow_delete_entity_type]
+
/**
* Delete entity type with the given entity type name
+ *
* @param entityTypeId The id of the entity_type.
- * @param projectId Project/agent id.
+ * @param projectId Project/agent id.
*/
public static void deleteEntityType(String entityTypeId, String projectId) throws Exception {
// Instantiates a client
@@ -124,52 +130,4 @@ public static List getEntityTypeIds(String displayName, String projectId
}
return entityTypesIds;
}
-
-
- public static void main(String[] args) throws Exception {
- ArgumentParser parser =
- ArgumentParsers.newFor("EntityTypeManagement")
- .build()
- .defaultHelp(true)
- .description("Create / List / Delete a Entity Type.");
-
- Subparsers subparsers = parser.addSubparsers().dest("command").title("Commands");
-
- Subparser listParser = subparsers.addParser("list")
- .help("mvn exec:java -DEntityTypeManagement -Dexec.args='list --projectId PROJECT_ID'");
- listParser.addArgument("--projectId").help("Project/Agent Id").required(true);
-
- Subparser createParser = subparsers.addParser("create")
- .help("mvn exec:java -DEntityTypeManagement -Dexec.args='create DISPLAY_NAME "
- + "--projectId PROJECT_ID --entityTypeId ENTITY_TYPE_ID "
- + "--synonyms basement cellar'");
- createParser.addArgument("displayName")
- .help("The display name of the entity.").required(true);
- createParser.addArgument("--projectId").help("Project/Agent Id").required(true);
- createParser.addArgument("--kind")
- .help("The kind of entity. KIND_MAP (default) or KIND_LIST.").setDefault("KIND_MAP");
-
- Subparser deleteParser = subparsers.addParser("delete")
- .help("mvn exec:java -DEntityTypeManagement -Dexec.args='delete ENTITY_TYPE_ID "
- + "--projectId PROJECT_ID'");
- deleteParser.addArgument("entityTypeId")
- .help("The id of the entityType to delete.").required(true);
- deleteParser.addArgument("--projectId").help("Project/Agent Id").required(true);
-
-
- try {
- Namespace namespace = parser.parseArgs(args);
-
- if (namespace.get("command").equals("list")) {
- listEntityTypes(namespace.get("projectId"));
- } else if (namespace.get("command").equals("create")) {
- createEntityType(namespace.get("displayName"), namespace.get("projectId"),
- namespace.get("kind"));
- } else if (namespace.get("command").equals("delete")) {
- deleteEntityType(namespace.get("entityTypeId"), namespace.get("projectId"));
- }
- } catch (ArgumentParserException e) {
- parser.handleError(e);
- }
- }
}
diff --git a/dialogflow/cloud-client/src/main/java/com/example/dialogflow/IntentManagement.java b/dialogflow/cloud-client/src/main/java/com/example/dialogflow/IntentManagement.java
index c2147cbaf52..0e1bbc8e8ee 100644
--- a/dialogflow/cloud-client/src/main/java/com/example/dialogflow/IntentManagement.java
+++ b/dialogflow/cloud-client/src/main/java/com/example/dialogflow/IntentManagement.java
@@ -16,8 +16,8 @@
package com.example.dialogflow;
-
// Imports the Google Cloud client library
+
import com.google.cloud.dialogflow.v2.Context;
import com.google.cloud.dialogflow.v2.Intent;
import com.google.cloud.dialogflow.v2.Intent.Message;
@@ -27,28 +27,25 @@
import com.google.cloud.dialogflow.v2.IntentName;
import com.google.cloud.dialogflow.v2.IntentsClient;
import com.google.cloud.dialogflow.v2.ProjectAgentName;
+import com.google.common.collect.Lists;
import java.util.ArrayList;
import java.util.List;
-import net.sourceforge.argparse4j.ArgumentParsers;
-import net.sourceforge.argparse4j.inf.ArgumentParser;
-import net.sourceforge.argparse4j.inf.ArgumentParserException;
-import net.sourceforge.argparse4j.inf.Namespace;
-import net.sourceforge.argparse4j.inf.Subparser;
-import net.sourceforge.argparse4j.inf.Subparsers;
-
/**
* DialogFlow API Intent sample.
*/
public class IntentManagement {
-
// [START dialogflow_list_intents]
+
/**
* List intents
+ *
* @param projectId Project/Agent Id.
+ * @return Intents found.
*/
- public static void listIntents(String projectId) throws Exception {
+ public static List listIntents(String projectId) throws Exception {
+ List intents = Lists.newArrayList();
// Instantiates a client
try (IntentsClient intentsClient = IntentsClient.create()) {
// Set the project agent name using the projectID (my-project-id)
@@ -67,27 +64,34 @@ public static void listIntents(String projectId) throws Exception {
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 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.
+ * @param messageTexts Message texts for the agent's response when the intent is detected.
+ * @return The created Intent.
*/
- public static void createIntent(String displayName, String projectId,
- List trainingPhrasesParts, List messageTexts)
- throws Exception {
+ public static Intent createIntent(
+ String displayName,
+ String projectId,
+ List trainingPhrasesParts,
+ List messageTexts) throws Exception {
// Instantiates a client
try (IntentsClient intentsClient = IntentsClient.create()) {
// Set the project agent name using the projectID (my-project-id)
@@ -98,7 +102,7 @@ public static void createIntent(String displayName, String projectId,
for (String trainingPhrase : trainingPhrasesParts) {
trainingPhrases.add(
TrainingPhrase.newBuilder().addParts(
- Part.newBuilder().setText(trainingPhrase).build())
+ Part.newBuilder().setText(trainingPhrase).build())
.build());
}
@@ -119,14 +123,18 @@ public static void createIntent(String displayName, String projectId,
// 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 intentId The id of the intent.
* @param projectId Project/Agent Id.
*/
public static void deleteIntent(String intentId, String projectId) throws Exception {
@@ -158,63 +166,4 @@ public static List getIntentIds(String displayName, String projectId) th
return intentIds;
}
-
- public static void main(String[] args) throws Exception {
-
-
- ArgumentParser parser =
- ArgumentParsers.newFor("IntentManagement")
- .build()
- .defaultHelp(true)
- .description("Create / List / Delete a Intent.");
-
- Subparsers subparsers = parser.addSubparsers().dest("command").title("Commands");
-
- Subparser listParser = subparsers.addParser("list")
- .help("mvn exec:java -DIntentManagement -Dexec.args='list --projectId PROJECT_ID'");
- listParser.addArgument("--projectId").help("Project/Agent Id").required(true);
-
- Subparser createParser = subparsers.addParser("create")
- .help("mvn exec:java -DIntentManagement -Dexec.args='create DISPLAY_NAME "
- + "--projectId PROJECT_ID --trainingPhrasesParts \"cancel\" \"cancellation\" "
- + "--messageTexts \"Are you sure you want to cancel?\" \"Cancelled.\"'");
- createParser.addArgument("displayName")
- .help("The display name of the intent.").required(true);
- createParser.addArgument("--projectId").help("Project/Agent Id").required(true);
- createParser.addArgument("--trainingPhrasesParts")
- .help("Training phrases.").nargs("+");
- createParser.addArgument("--messageTexts").nargs("+")
- .help("Message texts for the agent's response when the intent is detected.");
-
- Subparser deleteParser = subparsers.addParser("delete")
- .help("mvn exec:java -DIntentManagement -Dexec.args='delete INTENT_ID "
- + "--projectId PROJECT_ID'");
- deleteParser.addArgument("intentId")
- .help("The ID of the intent.").required(true);
- deleteParser.addArgument("--projectId").help("Project/Agent Id").required(true);
-
- try {
- Namespace namespace = parser.parseArgs(args);
-
- if (namespace.get("command").equals("list")) {
- listIntents(namespace.get("projectId"));
- } else if (namespace.get("command").equals("create")) {
- ArrayList trainingPhrasesParts = new ArrayList<>();
- ArrayList messageTexts = new ArrayList<>();
- if (namespace.get("trainingPhrasesParts") != null) {
- trainingPhrasesParts = namespace.get("trainingPhrasesParts");
- }
- if (namespace.get("messageTexts") != null) {
- messageTexts = namespace.get("messageTexts");
- }
-
- createIntent(namespace.get("displayName"), namespace.get("projectId"), trainingPhrasesParts,
- messageTexts);
- } else if (namespace.get("command").equals("delete")) {
- deleteIntent(namespace.get("intentId"), namespace.get("projectId"));
- }
- } catch (ArgumentParserException e) {
- parser.handleError(e);
- }
- }
}
diff --git a/dialogflow/cloud-client/src/main/java/com/example/dialogflow/KnowledgeBaseManagement.java b/dialogflow/cloud-client/src/main/java/com/example/dialogflow/KnowledgeBaseManagement.java
index d160e50c789..1fee645e10e 100644
--- a/dialogflow/cloud-client/src/main/java/com/example/dialogflow/KnowledgeBaseManagement.java
+++ b/dialogflow/cloud-client/src/main/java/com/example/dialogflow/KnowledgeBaseManagement.java
@@ -17,25 +17,23 @@
package com.example.dialogflow;
import com.google.cloud.dialogflow.v2beta1.KnowledgeBase;
-import com.google.cloud.dialogflow.v2beta1.KnowledgeBaseName;
import com.google.cloud.dialogflow.v2beta1.KnowledgeBasesClient;
import com.google.cloud.dialogflow.v2beta1.ProjectName;
-import net.sourceforge.argparse4j.ArgumentParsers;
-import net.sourceforge.argparse4j.inf.ArgumentParser;
-import net.sourceforge.argparse4j.inf.ArgumentParserException;
-import net.sourceforge.argparse4j.inf.Namespace;
-import net.sourceforge.argparse4j.inf.Subparser;
-import net.sourceforge.argparse4j.inf.Subparsers;
+import com.google.common.collect.Lists;
-public class KnowledgeBaseManagement {
+import java.util.List;
+public class KnowledgeBaseManagement {
// [START dialogflow_list_knowledge_base]
+
/**
* List Knowledge bases
*
* @param projectId Project/agent id.
+ * @return The KnowledgeBases found in projectId.
*/
- public static void listKnowledgeBases(String projectId) throws Exception {
+ public static List listKnowledgeBases(String projectId) throws Exception {
+ List knowledgeBases = Lists.newArrayList();
// Instantiates a client
try (KnowledgeBasesClient knowledgeBasesClient = KnowledgeBasesClient.create()) {
// Set the entity type name using the projectID (my-project-id) and entityTypeId (KIND_LIST)
@@ -44,28 +42,34 @@ public static void listKnowledgeBases(String projectId) throws Exception {
knowledgeBasesClient.listKnowledgeBases(projectName).iterateAll()) {
System.out.format(" - Display Name: %s\n", knowledgeBase.getDisplayName());
System.out.format(" - Knowledge ID: %s\n", knowledgeBase.getName());
+ knowledgeBases.add(knowledgeBase);
}
}
+ return knowledgeBases;
}
// [END dialogflow_list_knowledge_base]
// [START dialogflow_create_knowledge_base]
+
/**
* Create a Knowledge base
*
- * @param projectId Project/agent id.
+ * @param projectId Project/agent id.
* @param displayName Name of the knowledge base.
+ * @return The created KnowledgeBase.
*/
- public static void createKnowledgeBase(String projectId, String displayName) throws Exception {
+ public static KnowledgeBase createKnowledgeBase(String projectId, String displayName)
+ throws Exception {
// Instantiates a client
try (KnowledgeBasesClient knowledgeBasesClient = KnowledgeBasesClient.create()) {
-
KnowledgeBase knowledgeBase = KnowledgeBase.newBuilder().setDisplayName(displayName).build();
ProjectName projectName = ProjectName.of(projectId);
KnowledgeBase response = knowledgeBasesClient.createKnowledgeBase(projectName, knowledgeBase);
System.out.format("Knowledgebase created:\n");
System.out.format("Display Name: %s \n", response.getDisplayName());
System.out.format("Knowledge ID: %s \n", response.getName());
+
+ return response;
}
}
// [END dialogflow_create_knowledge_base]
@@ -73,87 +77,32 @@ public static void createKnowledgeBase(String projectId, String displayName) thr
// [START dialogflow_get_knowledge_base]
/**
- * @param knowledgeBaseId Knowledge base id.
- * @param projectId Project/agent id.
+ * @param knowledgeBaseName Knowledge base id.
+ * @return The retrieved KnowledgeBase.
*/
- public static void getKnowledgeBase(String projectId, String knowledgeBaseId) throws Exception {
-
+ public static KnowledgeBase getKnowledgeBase(String knowledgeBaseName) throws Exception {
// Instantiates a client
try (KnowledgeBasesClient knowledgeBasesClient = KnowledgeBasesClient.create()) {
- KnowledgeBaseName knowledgeBaseName = KnowledgeBaseName.of(projectId, knowledgeBaseId);
KnowledgeBase response = knowledgeBasesClient.getKnowledgeBase(knowledgeBaseName);
System.out.format("Got Knowledge Base:\n");
System.out.format(" - Display Name: %s\n", response.getDisplayName());
System.out.format(" - Knowledge ID: %s\n", response.getName());
+ return response;
}
}
// [END dialogflow_get_knowledge_base]
+
// [START dialogflow_delete_knowledge_base]
/**
- * @param knowledgeBaseId Knowledge base id.
- * @param projectId Project/agent id.
+ * @param knowledgeBaseName Knowledge base id.
*/
- public static void deleteKnowledgeBase(String projectId, String knowledgeBaseId)
- throws Exception {
+ public static void deleteKnowledgeBase(String knowledgeBaseName) throws Exception {
// Instantiates a client
try (KnowledgeBasesClient knowledgeBasesClient = KnowledgeBasesClient.create()) {
- KnowledgeBaseName knowledgeBaseName = KnowledgeBaseName.of(projectId, knowledgeBaseId);
knowledgeBasesClient.deleteKnowledgeBase(knowledgeBaseName);
System.out.format("KnowledgeBase has been deleted.\n");
}
}
// [END dialogflow_delete_knowledge_base]
-
-
- public static void main(String[] args) throws Exception {
- ArgumentParser parser =
- ArgumentParsers.newFor("KnowledgeBaseManagement")
- .build()
- .defaultHelp(true)
- .description("Create / List / Delete a Knowledge Base.");
-
- Subparsers subparsers = parser.addSubparsers().dest("command").title("Commands");
-
- Subparser listParser = subparsers.addParser("list")
- .help("mvn exec:java -DKnowledgeManagement -Dexec.args='list --projectId PROJECT_ID'");
- listParser.addArgument("--projectId").help("Project/Agent Id").required(true);
-
- Subparser createParser = subparsers.addParser("create")
- .help("mvn exec:java -DKnowledgeManagement -Dexec.args='create DISPLAY_NAME "
- + "--projectId PROJECT_ID'");
- createParser.addArgument("displayName")
- .help("The display name of the Document").required(true);
- createParser.addArgument("--projectId").help("Project/Agent Id").required(true);
-
- Subparser getParser = subparsers.addParser("get")
- .help("mvn exec:java -DKnowledgeManagement -Dexec.args='get KNOWLEDGE_BASE_ID "
- + "--projectId PROJECT_ID'");
- getParser.addArgument("knowledgeBaseId")
- .help("The ID of the Knowledge Base to list the Documents").required(true);
- getParser.addArgument("--projectId").help("Project/Agent Id").required(true);
-
- Subparser deleteParser = subparsers.addParser("delete")
- .help("mvn exec:java -DKnowledgeManagement -Dexec.args='delete KNOWLEDGE_BASE_ID "
- + "--projectId PROJECT_ID'");
- deleteParser.addArgument("--projectId").help("Project/Agent Id").required(true);
- deleteParser.addArgument("--knowledgeBaseId")
- .help("The ID of the Knowledge Base to list the Documents").required(true);
-
- try {
- Namespace namespace = parser.parseArgs(args);
-
- if (namespace.get("command").equals("list")) {
- listKnowledgeBases(namespace.get("projectId"));
- } else if (namespace.get("command").equals("create")) {
- createKnowledgeBase(namespace.get("projectId"), namespace.get("displayName"));
- } else if (namespace.get("command").equals("get")) {
- getKnowledgeBase(namespace.get("projectId"), namespace.get("knowledgeBaseId"));
- } else if (namespace.get("command").equals("delete")) {
- deleteKnowledgeBase(namespace.get("projectId"), namespace.get("knowledgeBaseId"));
- }
- } catch (ArgumentParserException e) {
- parser.handleError(e);
- }
- }
}
diff --git a/dialogflow/cloud-client/src/main/java/com/example/dialogflow/SessionEntityTypeManagement.java b/dialogflow/cloud-client/src/main/java/com/example/dialogflow/SessionEntityTypeManagement.java
index da52376e326..aeb28f9f21f 100644
--- a/dialogflow/cloud-client/src/main/java/com/example/dialogflow/SessionEntityTypeManagement.java
+++ b/dialogflow/cloud-client/src/main/java/com/example/dialogflow/SessionEntityTypeManagement.java
@@ -17,34 +17,34 @@
package com.example.dialogflow;
// Imports the Google Cloud client library
+
import com.google.cloud.dialogflow.v2.EntityType.Entity;
import com.google.cloud.dialogflow.v2.SessionEntityType;
import com.google.cloud.dialogflow.v2.SessionEntityType.EntityOverrideMode;
import com.google.cloud.dialogflow.v2.SessionEntityTypeName;
import com.google.cloud.dialogflow.v2.SessionEntityTypesClient;
import com.google.cloud.dialogflow.v2.SessionName;
+import com.google.common.collect.Lists;
import java.util.ArrayList;
import java.util.List;
-import net.sourceforge.argparse4j.ArgumentParsers;
-import net.sourceforge.argparse4j.inf.ArgumentParser;
-import net.sourceforge.argparse4j.inf.ArgumentParserException;
-import net.sourceforge.argparse4j.inf.Namespace;
-import net.sourceforge.argparse4j.inf.Subparser;
-import net.sourceforge.argparse4j.inf.Subparsers;
/**
* DialogFlow API SessionEntityType sample.
*/
public class SessionEntityTypeManagement {
-
// [START dialogflow_list_session_entity_types]
+
/**
* List session entity types
+ *
* @param projectId Project/Agent Id.
* @param sessionId Identifier of the DetectIntent session.
+ * @return SessionEntityTypes found.
*/
- public static void listSessionEntityTypes(String projectId, String sessionId) throws Exception {
+ public static List listSessionEntityTypes(String projectId, String sessionId)
+ throws Exception {
+ List sessionEntityTypes = Lists.newArrayList();
// Instantiates a client
try (SessionEntityTypesClient sessionEntityTypesClient = SessionEntityTypesClient.create()) {
// Set the session name using the sessionId (UUID) and projectID (my-project-id)
@@ -56,30 +56,39 @@ public static void listSessionEntityTypes(String projectId, String sessionId) th
sessionEntityTypesClient.listSessionEntityTypes(session).iterateAll()) {
System.out.format("\tSessionEntityType name: %s\n", sessionEntityType.getName());
System.out.format("\tNumber of entities: %d\n", sessionEntityType.getEntitiesCount());
+
+ sessionEntityTypes.add(sessionEntityType);
}
}
+ return sessionEntityTypes;
}
// [END dialogflow_list_session_entity_types]
// [START dialogflow_create_session_entity_type]
+
/**
* Create an entity type with the given display name
- * @param projectId Project/Agent Id.
- * @param sessionId Identifier of the DetectIntent session.
- * @param entityValues The entity values of the session entity type.
+ *
+ * @param projectId Project/Agent Id.
+ * @param sessionId Identifier of the DetectIntent session.
+ * @param entityValues The entity values of the session entity type.
* @param entityTypeDisplayName DISPLAY NAME of the entity type to be overridden in the session.
- * @param entityOverrideMode ENTITY_OVERRIDE_MODE_OVERRIDE (default) or
- * ENTITY_OVERRIDE_MODE_SUPPLEMENT
+ * @param entityOverrideMode ENTITY_OVERRIDE_MODE_OVERRIDE (default) or
+ * ENTITY_OVERRIDE_MODE_SUPPLEMENT
+ * @return Created SessionEntityType.
*/
- public static void createSessionEntityType(String projectId, String sessionId,
- List entityValues, String entityTypeDisplayName,int entityOverrideMode)
- throws Exception {
+ public static SessionEntityType createSessionEntityType(
+ String projectId,
+ String sessionId,
+ List entityValues,
+ String entityTypeDisplayName,
+ int entityOverrideMode) throws Exception {
// Instantiates a client
try (SessionEntityTypesClient sessionEntityTypesClient = SessionEntityTypesClient.create()) {
// Set the session name using the sessionId (UUID) and projectID (my-project-id)
SessionName session = SessionName.of(projectId, sessionId);
- SessionEntityTypeName name = SessionEntityTypeName.of(projectId, sessionId,
- entityTypeDisplayName);
+ SessionEntityTypeName name = SessionEntityTypeName.of(
+ projectId, sessionId, entityTypeDisplayName);
List entities = new ArrayList<>();
for (String entityValue : entityValues) {
@@ -100,20 +109,25 @@ public static void createSessionEntityType(String projectId, String sessionId,
// Performs the create session entity type request
SessionEntityType response = sessionEntityTypesClient.createSessionEntityType(session,
sessionEntityType);
-
System.out.format("SessionEntityType created: %s\n", response);
+
+ return response;
}
}
// [END dialogflow_create_session_entity_type]
// [START dialogflow_delete_session_entity_type]
+
/**
* Delete entity type with the given entity type name
- * @param projectId Project/Agent Id.
- * @param sessionId Identifier of the DetectIntent session.
+ *
+ * @param projectId Project/Agent Id.
+ * @param sessionId Identifier of the DetectIntent session.
* @param entityTypeDisplayName DISPLAY NAME of the entity type to be overridden in the session.
*/
- public static void deleteSessionEntityType(String projectId, String sessionId,
+ public static void deleteSessionEntityType(
+ String projectId,
+ String sessionId,
String entityTypeDisplayName) throws Exception {
// Instantiates a client
try (SessionEntityTypesClient sessionEntityTypesClient = SessionEntityTypesClient.create()) {
@@ -125,70 +139,4 @@ public static void deleteSessionEntityType(String projectId, String sessionId,
}
}
// [END dialogflow_delete_session_entity_type]
-
- public static void main(String[] args) throws Exception {
- ArgumentParser parser =
- ArgumentParsers.newFor("SessionEntityTypeManagement")
- .build()
- .defaultHelp(true)
- .description("Create / List / Delete a SessionEntityType.");
-
- Subparsers subparsers = parser.addSubparsers().dest("command").title("Commands");
-
- Subparser listParser = subparsers.addParser("list")
- .help("mvn exec:java -DSessionEntityTypeManagement -Dexec.args='list "
- + "--projectId PROJECT_ID --sessionId SESSION_ID '");
- listParser.addArgument("--projectId").help("Project/Agent Id").required(true);
- listParser.addArgument("--sessionId")
- .help("Identifier of the DetectIntent session").required(true);
-
- Subparser createParser = subparsers.addParser("create")
- .help("mvn exec:java -DSessionEntityTypeManagement -Dexec.args='create "
- + "--projectId PROJECT_ID --sessionId SESSION_ID "
- + "--entityTypeDisplayName ENTITY_TYPE_DISPLAY_NAME "
- + "--entityOverrideMode ENTITY_OVERRIDE_MODE_OVERRIDE "
- + "--entityValues C D E F'");
- createParser.addArgument("--projectId").help("Project/Agent Id").required(true);
- createParser.addArgument("--sessionId")
- .help("Identifier of the DetectIntent session").required(true);
- createParser.addArgument("--entityTypeDisplayName")
- .help("The DISPLAY NAME of the entity type to be overridden in the session.t")
- .required(true);
- createParser.addArgument("--entityOverrideMode")
- .help("ENTITY_OVERRIDE_MODE_OVERRIDE (default) or ENTITY_OVERRIDE_MODE_SUPPLEMENT")
- .setDefault(1);
- createParser.addArgument("--entityValues").nargs("+")
- .help("The entity values of the session entity type.");
-
- Subparser deleteParser = subparsers.addParser("delete")
- .help("mvn exec:java -DSessionEntityTypeManagement -Dexec.args='delete "
- + "--sessionId SESSION_ID --projectId PROJECT_ID --contextId CONTEXT_ID'");
- deleteParser.addArgument("--projectId").help("Project/Agent Id").required(true);
- deleteParser.addArgument("--sessionId")
- .help("Identifier of the DetectIntent session").required(true);
- deleteParser.addArgument("--entityTypeDisplayName")
- .help("The DISPLAY NAME of the entity type to be overridden in the session.t")
- .required(true);
-
- try {
- Namespace namespace = parser.parseArgs(args);
-
- if (namespace.get("command").equals("list")) {
- listSessionEntityTypes(namespace.get("projectId"), namespace.get("sessionId"));
- } else if (namespace.get("command").equals("create")) {
- ArrayList entityValues = new ArrayList<>();
- if (namespace.get("entityValues") != null) {
- entityValues = namespace.get("entityValues");
- }
- createSessionEntityType(namespace.get("projectId"), namespace.get("sessionId"),
- entityValues, namespace.get("entityTypeDisplayName"),
- namespace.get("entityOverrideMode"));
- } else if (namespace.get("command").equals("delete")) {
- deleteSessionEntityType(namespace.get("projectId"), namespace.get("sessionId"),
- namespace.get("entityTypeDisplayName"));
- }
- } catch (ArgumentParserException e) {
- parser.handleError(e);
- }
- }
}
diff --git a/dialogflow/cloud-client/src/test/java/com/example/dialogflow/ContextManagementIT.java b/dialogflow/cloud-client/src/test/java/com/example/dialogflow/ContextManagementIT.java
index fcd16806692..10eb147e8a6 100644
--- a/dialogflow/cloud-client/src/test/java/com/example/dialogflow/ContextManagementIT.java
+++ b/dialogflow/cloud-client/src/test/java/com/example/dialogflow/ContextManagementIT.java
@@ -17,10 +17,17 @@
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.cloud.dialogflow.v2.Context;
+import com.google.cloud.dialogflow.v2.ContextName;
+import com.google.cloud.dialogflow.v2.ContextsClient;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
-import java.util.Arrays;
+import java.util.List;
+
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
@@ -33,49 +40,46 @@
@RunWith(JUnit4.class)
@SuppressWarnings("checkstyle:abbreviationaswordinname")
public class ContextManagementIT {
-
- private ByteArrayOutputStream bout;
- private PrintStream out;
-
- private DetectIntentTexts detectIntentTexts;
- private ContextManagement contextManagement;
private static String PROJECT_ID = System.getenv().get("GOOGLE_CLOUD_PROJECT");
private static String SESSION_ID = "fake_session_for_testing";
private static String CONTEXT_ID = "fake_context_for_testing";
@Before
public void setUp() {
- bout = new ByteArrayOutputStream();
- out = new PrintStream(bout);
- System.setOut(out);
- detectIntentTexts = new DetectIntentTexts();
- contextManagement = new ContextManagement();
- PROJECT_ID = System.getenv().get("GOOGLE_CLOUD_PROJECT");
+ System.setOut(new PrintStream(new ByteArrayOutputStream()));
}
@After
- public void tearDown() {
+ public void tearDown() throws Exception {
+ try (ContextsClient contextsClient = ContextsClient.create()) {
+ // If the Context still exists, delete it.
+ try {
+ ContextName contextName = ContextName.of(PROJECT_ID, SESSION_ID, CONTEXT_ID);
+ Context existing = contextsClient.getContext(contextName);
+ contextsClient.deleteContext(existing.getName());
+ } catch (Exception e) {
+ // Context doesn't exist, nothing to do.
+ }
+ }
System.setOut(null);
}
@Test
public void testCreateDeleteContext() throws Exception {
- // Calling detect intent to create a session
- detectIntentTexts.detectIntentTexts(PROJECT_ID, Arrays.asList("hi"), SESSION_ID, "en-US");
-
// Create the context
- contextManagement.createContext(CONTEXT_ID, SESSION_ID, PROJECT_ID, 1);
- contextManagement.listContexts(SESSION_ID, PROJECT_ID);
+ Context context = ContextManagement.createContext(CONTEXT_ID, SESSION_ID, PROJECT_ID, 1);
+ assertThat(context.getName()).contains(CONTEXT_ID);
+ assertEquals(1, context.getLifespanCount());
- String got = bout.toString();
- assertThat(got).contains(CONTEXT_ID);
+ List contexts = ContextManagement.listContexts(SESSION_ID, PROJECT_ID);
+ assertTrue(contexts.size() > 0);
+ assertTrue(contexts.stream().anyMatch(c -> c.getName().contains(SESSION_ID)
+ && c.getName().contains(CONTEXT_ID)));
// Delete the context
- bout.reset();
- contextManagement.deleteContext(CONTEXT_ID, SESSION_ID, PROJECT_ID);
- contextManagement.listContexts(SESSION_ID, PROJECT_ID);
-
- got = bout.toString();
- assertThat(got).doesNotContain(CONTEXT_ID);
+ ContextManagement.deleteContext(CONTEXT_ID, SESSION_ID, PROJECT_ID);
+ int numContexts = contexts.size();
+ contexts = ContextManagement.listContexts(SESSION_ID, PROJECT_ID);
+ assertEquals(numContexts - 1, contexts.size());
}
}
diff --git a/dialogflow/cloud-client/src/test/java/com/example/dialogflow/DetectIntentAudioIT.java b/dialogflow/cloud-client/src/test/java/com/example/dialogflow/DetectIntentAudioIT.java
deleted file mode 100644
index bc458d6e9ae..00000000000
--- a/dialogflow/cloud-client/src/test/java/com/example/dialogflow/DetectIntentAudioIT.java
+++ /dev/null
@@ -1,72 +0,0 @@
-/*
- * 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.PrintStream;
-import java.util.Arrays;
-import java.util.List;
-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 DetectIntentAudio}.
- */
-@RunWith(JUnit4.class)
-@SuppressWarnings("checkstyle:abbreviationaswordinname")
-public class DetectIntentAudioIT {
-
- private ByteArrayOutputStream bout;
- private PrintStream out;
- private DetectIntentAudio detectIntentAudio;
- private static String PROJECT_ID = System.getenv().get("GOOGLE_CLOUD_PROJECT");
- private static String SESSION_ID = "fake_session_for_testing";
- private static String LANGUAGE_CODE = "en-US";
- private static List AUDIOS = Arrays.asList(
- "resources/book_a_room.wav",
- "resources/mountain_view.wav",
- "resources/today.wav");
-
- @Before
- public void setUp() {
- bout = new ByteArrayOutputStream();
- out = new PrintStream(bout);
- System.setOut(out);
- detectIntentAudio = new DetectIntentAudio();
- }
-
- @After
- public void tearDown() {
- System.setOut(null);
- }
-
- @Test
- public void testDetectIntent() throws Exception {
- for (String audioFilePath : AUDIOS) {
- detectIntentAudio.detectIntentAudio(PROJECT_ID, audioFilePath, SESSION_ID, LANGUAGE_CODE);
- }
-
- String got = bout.toString();
- assertThat(got).contains("Fulfillment Text: 'What time will the meeting start?'");
- }
-
-}
diff --git a/dialogflow/cloud-client/src/test/java/com/example/dialogflow/DetectIntentStreamIT.java b/dialogflow/cloud-client/src/test/java/com/example/dialogflow/DetectIntentStreamIT.java
index 88f3c7d613d..a1d6b8c080a 100644
--- a/dialogflow/cloud-client/src/test/java/com/example/dialogflow/DetectIntentStreamIT.java
+++ b/dialogflow/cloud-client/src/test/java/com/example/dialogflow/DetectIntentStreamIT.java
@@ -16,10 +16,14 @@
package com.example.dialogflow;
-import static com.google.common.truth.Truth.assertThat;
+import static org.junit.Assert.assertTrue;
+
+import com.google.cloud.dialogflow.v2.StreamingDetectIntentResponse;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
+import java.util.List;
+
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
@@ -33,35 +37,32 @@
@SuppressWarnings("checkstyle:abbreviationaswordinname")
public class DetectIntentStreamIT {
- private ByteArrayOutputStream bout;
- private PrintStream out;
private static String audioFilePath = "resources/book_a_room.wav";
- private DetectIntentStream detectIntentStream;
private static String PROJECT_ID = System.getenv().get("GOOGLE_CLOUD_PROJECT");
private static String SESSION_ID = "fake_session_for_testing";
private static String LANGUAGE_CODE = "en-US";
@Before
public void setUp() {
- bout = new ByteArrayOutputStream();
- out = new PrintStream(bout);
- System.setOut(out);
- detectIntentStream = new DetectIntentStream();
+ System.setOut(new PrintStream(new ByteArrayOutputStream()));
}
-
@After
public void tearDown() {
System.setOut(null);
}
-
@Test
public void testStreamingDetectIntentCallable() throws Throwable {
- detectIntentStream.detectIntentStream(PROJECT_ID, audioFilePath, SESSION_ID, LANGUAGE_CODE);
-
- String got = bout.toString();
- assertThat(got).contains("Intermediate transcript: 'book'");
- assertThat(got).contains("Detected Intent: room.reservation");
+ List response = DetectIntentStream.detectIntentStream(
+ PROJECT_ID, audioFilePath, SESSION_ID, LANGUAGE_CODE);
+ assertTrue(response.size() > 0);
+ assertTrue(response.stream().anyMatch(i -> i
+ .getQueryResult()
+ .getIntent()
+ .getDisplayName().equals("room.reservation")));
+ assertTrue(response.stream().anyMatch(i -> i
+ .getRecognitionResult()
+ .getTranscript().contains("book")));
}
}
diff --git a/dialogflow/cloud-client/src/test/java/com/example/dialogflow/DetectIntentTextsIT.java b/dialogflow/cloud-client/src/test/java/com/example/dialogflow/DetectIntentTextsIT.java
deleted file mode 100644
index 88213ae275b..00000000000
--- a/dialogflow/cloud-client/src/test/java/com/example/dialogflow/DetectIntentTextsIT.java
+++ /dev/null
@@ -1,68 +0,0 @@
-/*
- * 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.PrintStream;
-import java.util.Arrays;
-import java.util.List;
-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 DetectIntentTexts}.
- */
-@RunWith(JUnit4.class)
-@SuppressWarnings("checkstyle:abbreviationaswordinname")
-public class DetectIntentTextsIT {
-
- private ByteArrayOutputStream bout;
- private DetectIntentTexts detectIntentTexts;
- private PrintStream out;
- private static String PROJECT_ID = System.getenv().get("GOOGLE_CLOUD_PROJECT");
- private static String SESSION_ID = "fake_session_for_testing";
- 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() {
- bout = new ByteArrayOutputStream();
- out = new PrintStream(bout);
- System.setOut(out);
- detectIntentTexts = new DetectIntentTexts();
- }
-
- @After
- public void tearDown() {
- System.setOut(null);
- }
-
- @Test
- public void testDetectIntent() throws Exception {
- detectIntentTexts.detectIntentTexts(PROJECT_ID, TEXTS, SESSION_ID, LANGUAGE_CODE);
-
- String got = bout.toString();
- assertThat(got).contains("Fulfillment Text: 'All set!'");
- }
-
-}
diff --git a/dialogflow/cloud-client/src/test/java/com/example/dialogflow/DetectIntentWithAudioAndModelSelectionIT.java b/dialogflow/cloud-client/src/test/java/com/example/dialogflow/DetectIntentWithAudioAndModelSelectionIT.java
new file mode 100644
index 00000000000..53822d64f18
--- /dev/null
+++ b/dialogflow/cloud-client/src/test/java/com/example/dialogflow/DetectIntentWithAudioAndModelSelectionIT.java
@@ -0,0 +1,111 @@
+/*
+ * 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.cloud.dialogflow.v2beta1.QueryResult;
+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 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 DetectIntentWithModelSelection}.
+ */
+@RunWith(JUnit4.class)
+@SuppressWarnings("checkstyle:abbreviationaswordinname")
+public class DetectIntentWithAudioAndModelSelectionIT {
+ protected static String PROJECT_ID = System.getenv().get("GOOGLE_CLOUD_PROJECT");
+ protected static String SESSION_ID = "fake_session_for_testing";
+ 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);
+ }
+
+ @Test
+ public void testDetectIntentWithModelSelection() throws Exception {
+ List askedQuestions = Lists.newArrayList();
+ QueryResult result = DetectIntentWithModelSelection.detectIntentWithModelSelection(
+ 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 = DetectIntentWithModelSelection.detectIntentWithModelSelection(
+ 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/cloud-client/src/test/java/com/example/dialogflow/DetectIntentWithModelSelectionIT.java b/dialogflow/cloud-client/src/test/java/com/example/dialogflow/DetectIntentWithModelSelectionIT.java
deleted file mode 100644
index 399f4342a9c..00000000000
--- a/dialogflow/cloud-client/src/test/java/com/example/dialogflow/DetectIntentWithModelSelectionIT.java
+++ /dev/null
@@ -1,69 +0,0 @@
-/*
- * 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.PrintStream;
-import java.util.Arrays;
-import java.util.List;
-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 DetectIntentWithModelSelection}. */
-@RunWith(JUnit4.class)
-@SuppressWarnings("checkstyle:abbreviationaswordinname")
-public class DetectIntentWithModelSelectionIT {
-
- private static String PROJECT_ID = System.getenv().get("GOOGLE_CLOUD_PROJECT");
- private static String SESSION_ID = "fake_session_for_testing";
- private static String LANGUAGE_CODE = "en-US";
- private static List AUDIOS =
- Arrays.asList(
- "resources/book_a_room.wav", "resources/mountain_view.wav", "resources/today.wav");
- private ByteArrayOutputStream bout;
- private PrintStream out;
- private DetectIntentWithModelSelection detectIntentWithModelSelection;
-
- @Before
- public void setUp() {
- bout = new ByteArrayOutputStream();
- out = new PrintStream(bout);
- System.setOut(out);
- detectIntentWithModelSelection = new DetectIntentWithModelSelection();
- }
-
- @After
- public void tearDown() {
- System.setOut(null);
- }
-
- @Test
- public void testDetectIntent() throws Exception {
- for (String audioFilePath : AUDIOS) {
- detectIntentWithModelSelection.detectIntentWithModelSelection(
- PROJECT_ID, SESSION_ID, audioFilePath, LANGUAGE_CODE);
- }
-
- String got = bout.toString();
- assertThat(got).contains("Fulfillment Text: 'What time will the meeting start?'");
- }
-}
diff --git a/dialogflow/cloud-client/src/test/java/com/example/dialogflow/DetectIntentWithSentimentAnalysisIT.java b/dialogflow/cloud-client/src/test/java/com/example/dialogflow/DetectIntentWithSentimentAnalysisIT.java
deleted file mode 100644
index c442fcf74bb..00000000000
--- a/dialogflow/cloud-client/src/test/java/com/example/dialogflow/DetectIntentWithSentimentAnalysisIT.java
+++ /dev/null
@@ -1,69 +0,0 @@
-/*
- * 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.PrintStream;
-import java.util.Arrays;
-import java.util.List;
-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 DetectIntentWithSentimentAnalysisIT {
-
- private ByteArrayOutputStream bout;
- private DetectIntentWithSentimentAnalysis detectIntentWithSentimentAnalysis;
- private PrintStream out;
- private static String PROJECT_ID = System.getenv().get("GOOGLE_CLOUD_PROJECT");
- private static String SESSION_ID = "fake_session_for_testing";
- 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() {
- bout = new ByteArrayOutputStream();
- out = new PrintStream(bout);
- System.setOut(out);
- detectIntentWithSentimentAnalysis = new DetectIntentWithSentimentAnalysis();
- }
-
- @After
- public void tearDown() {
- System.setOut(null);
- }
-
- @Test
- public void testDetectIntent() throws Exception {
- detectIntentWithSentimentAnalysis.detectIntentSentimentAnalysis(PROJECT_ID, TEXTS, SESSION_ID,
- LANGUAGE_CODE);
-
- String got = bout.toString();
- assertThat(got).contains("Sentiment Score:");
- }
-
-}
\ No newline at end of file
diff --git a/dialogflow/cloud-client/src/test/java/com/example/dialogflow/DetectIntentWithSentimentAndTextToSpeechIT.java b/dialogflow/cloud-client/src/test/java/com/example/dialogflow/DetectIntentWithSentimentAndTextToSpeechIT.java
new file mode 100644
index 00000000000..a427f95aa50
--- /dev/null
+++ b/dialogflow/cloud-client/src/test/java/com/example/dialogflow/DetectIntentWithSentimentAndTextToSpeechIT.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 org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
+import com.google.cloud.dialogflow.v2beta1.QueryResult;
+
+import java.io.ByteArrayOutputStream;
+import java.io.PrintStream;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Map;
+
+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 SESSION_ID = "fake_session_for_testing";
+ 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 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());
+ }
+}
\ No newline at end of file
diff --git a/dialogflow/cloud-client/src/test/java/com/example/dialogflow/DetectIntentWithTextToSpeechResponseIT.java b/dialogflow/cloud-client/src/test/java/com/example/dialogflow/DetectIntentWithTextToSpeechResponseIT.java
deleted file mode 100644
index d28e2f21a64..00000000000
--- a/dialogflow/cloud-client/src/test/java/com/example/dialogflow/DetectIntentWithTextToSpeechResponseIT.java
+++ /dev/null
@@ -1,75 +0,0 @@
-/*
- * 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.PrintStream;
-import java.util.Arrays;
-import java.util.List;
-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 DetectIntentWithTextToSpeechResponse}. */
-@RunWith(JUnit4.class)
-@SuppressWarnings("checkstyle:abbreviationaswordinname")
-public class DetectIntentWithTextToSpeechResponseIT {
-
- private static String PROJECT_ID = System.getenv().get("GOOGLE_CLOUD_PROJECT");
- private static String SESSION_ID = "fake_session_for_testing";
- 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");
- private ByteArrayOutputStream bout;
- private DetectIntentWithTextToSpeechResponse detectIntentWithTextToSpeechResponse;
- private PrintStream out;
-
- @Before
- public void setUp() {
- bout = new ByteArrayOutputStream();
- out = new PrintStream(bout);
- System.setOut(out);
- detectIntentWithTextToSpeechResponse = new DetectIntentWithTextToSpeechResponse();
- }
-
- @After
- public void tearDown() {
- System.setOut(null);
- }
-
- @Test
- public void testDetectIntent() throws Exception {
- detectIntentWithTextToSpeechResponse.detectIntentWithTexttoSpeech(
- PROJECT_ID, TEXTS, SESSION_ID, LANGUAGE_CODE);
-
- String got = bout.toString();
- assertThat(got).contains("Fulfillment Text: 'All set!'");
- }
-}
diff --git a/dialogflow/cloud-client/src/test/java/com/example/dialogflow/CreateDeleteEntityIT.java b/dialogflow/cloud-client/src/test/java/com/example/dialogflow/EntityManagementIT.java
similarity index 52%
rename from dialogflow/cloud-client/src/test/java/com/example/dialogflow/CreateDeleteEntityIT.java
rename to dialogflow/cloud-client/src/test/java/com/example/dialogflow/EntityManagementIT.java
index 23ab85991d4..532f929602e 100644
--- a/dialogflow/cloud-client/src/test/java/com/example/dialogflow/CreateDeleteEntityIT.java
+++ b/dialogflow/cloud-client/src/test/java/com/example/dialogflow/EntityManagementIT.java
@@ -17,11 +17,18 @@
package com.example.dialogflow;
import static com.google.common.truth.Truth.assertThat;
+import static org.junit.Assert.assertEquals;
+
+import com.google.cloud.dialogflow.v2.EntityType;
+import com.google.cloud.dialogflow.v2.EntityType.Entity;
+import com.google.protobuf.ProtocolStringList;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.util.Arrays;
+import java.util.Collections;
import java.util.List;
+
import org.junit.After;
import org.junit.Before;
import org.junit.FixMethodOrder;
@@ -30,37 +37,25 @@
import org.junit.runners.JUnit4;
import org.junit.runners.MethodSorters;
-
/**
* Integration (system) tests for {@link EntityManagement} and {@link EntityTypeManagement}.
*/
@RunWith(JUnit4.class)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
@SuppressWarnings("checkstyle:abbreviationaswordinname")
-public class CreateDeleteEntityIT {
+public class EntityManagementIT {
+ private static String PROJECT_ID = System.getenv().get("GOOGLE_CLOUD_PROJECT");
private static String ENTITY_TYPE_DISPLAY_NAME = "fake_entity_type_for_testing";
private static String ENTITY_VALUE_1 = "fake_entity_for_testing_1";
private static String ENTITY_VALUE_2 = "fake_entity_for_testing_2";
private static List SYNONYMS = Arrays.asList("fake_synonym_for_testing_1",
"fake_synonym_for_testing_2");
- private ByteArrayOutputStream bout;
- private PrintStream out;
-
- private EntityManagement entityManagement;
- private EntityTypeManagement entityTypeManagement;
- private static String PROJECT_ID = System.getenv().get("GOOGLE_CLOUD_PROJECT");
-
@Before
public void setUp() {
- bout = new ByteArrayOutputStream();
- out = new PrintStream(bout);
- System.setOut(out);
- entityManagement = new EntityManagement();
- entityTypeManagement = new EntityTypeManagement();
+ System.setOut(new PrintStream(new ByteArrayOutputStream()));
}
-
@After
public void tearDown() {
System.setOut(null);
@@ -68,66 +63,67 @@ public void tearDown() {
@Test
public void testCreateEntityType() throws Exception {
- List entityTypeIds = entityTypeManagement.getEntityTypeIds(ENTITY_TYPE_DISPLAY_NAME,
- PROJECT_ID);
+ List entityTypeIds = EntityTypeManagement.getEntityTypeIds(
+ ENTITY_TYPE_DISPLAY_NAME, PROJECT_ID);
assertThat(entityTypeIds.size()).isEqualTo(0);
- entityTypeManagement.createEntityType(ENTITY_TYPE_DISPLAY_NAME, PROJECT_ID, "KIND_MAP");
-
- String got = bout.toString();
- assertThat(got).contains(String.format("display_name: \"%s\"", ENTITY_TYPE_DISPLAY_NAME));
+ EntityType entityType = EntityTypeManagement.createEntityType(
+ ENTITY_TYPE_DISPLAY_NAME, PROJECT_ID, "KIND_MAP");
+ assertEquals(ENTITY_TYPE_DISPLAY_NAME, entityType.getDisplayName());
- entityTypeIds = entityTypeManagement.getEntityTypeIds(ENTITY_TYPE_DISPLAY_NAME,
- PROJECT_ID);
+ entityTypeIds = EntityTypeManagement.getEntityTypeIds(
+ ENTITY_TYPE_DISPLAY_NAME, PROJECT_ID);
assertThat(entityTypeIds.size()).isEqualTo(1);
}
@Test
public void testCreateEntityWithCreatedEntityType() throws Exception {
- List entityTypeIds = entityTypeManagement.getEntityTypeIds(ENTITY_TYPE_DISPLAY_NAME,
+ List entityTypeIds = EntityTypeManagement.getEntityTypeIds(ENTITY_TYPE_DISPLAY_NAME,
PROJECT_ID);
- entityManagement.createEntity(PROJECT_ID, entityTypeIds.get(0), ENTITY_VALUE_1,
- Arrays.asList(""));
- entityManagement.createEntity(PROJECT_ID, entityTypeIds.get(0), ENTITY_VALUE_2, SYNONYMS);
-
- entityManagement.listEntities(PROJECT_ID, entityTypeIds.get(0));
+ EntityManagement.createEntity(
+ PROJECT_ID, entityTypeIds.get(0), ENTITY_VALUE_1, Collections.singletonList(""));
+ EntityManagement.createEntity(
+ PROJECT_ID, entityTypeIds.get(0), ENTITY_VALUE_2, SYNONYMS);
- String got = bout.toString();
- assertThat(got).contains(String.format("Entity value: %s", ENTITY_VALUE_1));
- assertThat(got).contains(String.format("Entity value: %s", ENTITY_VALUE_2));
+ List entities = EntityManagement.listEntities(PROJECT_ID, entityTypeIds.get(0));
+ assertEquals(2, entities.size());
+ int entityOneInd = entities.get(0).getValue().equals(ENTITY_VALUE_1) ? 0 : 1;
+ int entityTwoInd = entityOneInd == 0 ? 1 : 0;
+ assertEquals(ENTITY_VALUE_1, entities.get(entityOneInd).getValue());
+ assertEquals(ENTITY_VALUE_2, entities.get(entityTwoInd).getValue());
+ ProtocolStringList synonyms = entities.get(entityTwoInd).getSynonymsList();
+ assertEquals(2, synonyms.size());
for (String synonym : SYNONYMS) {
- assertThat(got).contains(synonym);
+ assertThat(synonyms).contains(synonym);
}
}
@Test
public void testDeleteEntity() throws Exception {
- List entityTypeIds = entityTypeManagement.getEntityTypeIds(ENTITY_TYPE_DISPLAY_NAME,
- PROJECT_ID);
-
- entityManagement.deleteEntity(PROJECT_ID, entityTypeIds.get(0), ENTITY_VALUE_1);
- entityManagement.deleteEntity(PROJECT_ID, entityTypeIds.get(0), ENTITY_VALUE_2);
+ List entityTypeIds = EntityTypeManagement.getEntityTypeIds(
+ ENTITY_TYPE_DISPLAY_NAME, PROJECT_ID);
- entityManagement.listEntities(PROJECT_ID, entityTypeIds.get(0));
+ EntityManagement.deleteEntity(PROJECT_ID, entityTypeIds.get(0), ENTITY_VALUE_1);
+ EntityManagement.deleteEntity(PROJECT_ID, entityTypeIds.get(0), ENTITY_VALUE_2);
- String got = bout.toString();
- assertThat(got).isEqualTo("");
+ List entities = EntityManagement.listEntities(PROJECT_ID, entityTypeIds.get(0));
+ assertEquals(0, entities.size());
}
@Test
public void testDeleteEntityType() throws Exception {
- List entityTypeIds = entityTypeManagement.getEntityTypeIds(ENTITY_TYPE_DISPLAY_NAME,
- PROJECT_ID);
+ List entityTypeIds = EntityTypeManagement.getEntityTypeIds(
+ ENTITY_TYPE_DISPLAY_NAME, PROJECT_ID);
for (String entityTypeId : entityTypeIds) {
- entityTypeManagement.deleteEntityType(entityTypeId, PROJECT_ID);
+ EntityTypeManagement.deleteEntityType(entityTypeId, PROJECT_ID);
}
- entityTypeIds = entityTypeManagement.getEntityTypeIds(ENTITY_TYPE_DISPLAY_NAME, PROJECT_ID);
+ entityTypeIds = EntityTypeManagement.getEntityTypeIds(ENTITY_TYPE_DISPLAY_NAME, PROJECT_ID);
assertThat(entityTypeIds.size()).isEqualTo(0);
}
}
diff --git a/dialogflow/cloud-client/src/test/java/com/example/dialogflow/IntentManagementIT.java b/dialogflow/cloud-client/src/test/java/com/example/dialogflow/IntentManagementIT.java
index 251984a00c8..5dc9d6c6bbc 100644
--- a/dialogflow/cloud-client/src/test/java/com/example/dialogflow/IntentManagementIT.java
+++ b/dialogflow/cloud-client/src/test/java/com/example/dialogflow/IntentManagementIT.java
@@ -17,11 +17,19 @@
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.Intent;
+import com.google.cloud.dialogflow.v2.IntentsClient;
+import com.google.cloud.dialogflow.v2.ProjectAgentName;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.util.Arrays;
import java.util.List;
+
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
@@ -41,59 +49,53 @@ public class IntentManagementIT {
private static List TRAINING_PHRASE_PARTS = Arrays.asList(
"fake_training_phrase_part_1",
"fake_training_phrase_part_2");
- private ByteArrayOutputStream bout;
- private PrintStream out;
private static String PROJECT_ID = System.getenv().get("GOOGLE_CLOUD_PROJECT");
- private IntentManagement intentManagement;
@Before
public void setUp() {
- bout = new ByteArrayOutputStream();
- out = new PrintStream(bout);
- System.setOut(out);
- intentManagement = new IntentManagement();
+ System.setOut(new PrintStream(new ByteArrayOutputStream()));
}
-
@After
- public void tearDown() {
+ public void tearDown() throws Exception {
+ try (IntentsClient intentsClient = IntentsClient.create()) {
+ // Set the project agent name using the projectID (my-project-id)
+ ProjectAgentName parent = ProjectAgentName.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
- intentManagement.createIntent(INTENT_DISPLAY_NAME, PROJECT_ID, TRAINING_PHRASE_PARTS,
- MESSAGE_TEXTS);
-
- List intentIds = intentManagement.getIntentIds(INTENT_DISPLAY_NAME, PROJECT_ID);
+ 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);
- intentManagement.listIntents(PROJECT_ID);
-
- String got = bout.toString();
- assertThat(got).contains(INTENT_DISPLAY_NAME);
+ List intents = IntentManagement.listIntents(PROJECT_ID);
+ assertTrue(intents.size() > 0);
+ assertThat(intents).contains(intent);
for (String messageText : MESSAGE_TEXTS) {
- assertThat(got).contains(messageText);
+ assertTrue(intent.getMessagesList()
+ .stream().anyMatch(message -> message.getText().toString().contains(messageText)));
}
- // Delete the intent
- bout.reset();
- intentIds = intentManagement.getIntentIds(INTENT_DISPLAY_NAME, PROJECT_ID);
-
for (String intentId : intentIds) {
- intentManagement.deleteIntent(intentId, PROJECT_ID);
+ IntentManagement.deleteIntent(intentId, PROJECT_ID);
}
- intentManagement.listIntents(PROJECT_ID);
-
- got = bout.toString();
- assertThat(got).doesNotContain(INTENT_DISPLAY_NAME);
-
- intentIds = intentManagement.getIntentIds(INTENT_DISPLAY_NAME, PROJECT_ID);
-
- assertThat(intentIds.size()).isEqualTo(0);
+ int numIntents = intents.size();
+ intents = IntentManagement.listIntents(PROJECT_ID);
+ assertEquals(numIntents - 1, intents.size());
}
-
}
diff --git a/dialogflow/cloud-client/src/test/java/com/example/dialogflow/KnowledgeBaseManagementIT.java b/dialogflow/cloud-client/src/test/java/com/example/dialogflow/KnowledgeBaseManagementIT.java
index 18609814666..e3e8f19fc14 100644
--- a/dialogflow/cloud-client/src/test/java/com/example/dialogflow/KnowledgeBaseManagementIT.java
+++ b/dialogflow/cloud-client/src/test/java/com/example/dialogflow/KnowledgeBaseManagementIT.java
@@ -17,11 +17,23 @@
package com.example.dialogflow;
import static com.google.common.truth.Truth.assertThat;
+import static org.junit.Assert.assertEquals;
+
+import com.google.cloud.dialogflow.v2beta1.DeleteDocumentRequest;
+import com.google.cloud.dialogflow.v2beta1.Document;
+import com.google.cloud.dialogflow.v2beta1.DocumentsClient;
+import com.google.cloud.dialogflow.v2beta1.KnowledgeAnswers;
+import com.google.cloud.dialogflow.v2beta1.KnowledgeAnswers.Answer;
+import com.google.cloud.dialogflow.v2beta1.KnowledgeBase;
+import com.google.cloud.dialogflow.v2beta1.KnowledgeBasesClient;
+import com.google.cloud.dialogflow.v2beta1.ProjectName;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
-import java.util.Arrays;
+import java.util.Collections;
import java.util.List;
+import java.util.Map;
+
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
@@ -35,100 +47,127 @@
@SuppressWarnings("checkstyle:abbreviationaswordinname")
public class KnowledgeBaseManagementIT {
- private ByteArrayOutputStream bout;
- private DetectIntentKnowledge detectIntentKnowledge;
- private KnowledgeBaseManagement knowledgeBaseManagement;
- private DocumentManagement documentManagement;
- private PrintStream out;
private static String PROJECT_ID = System.getenv().get("GOOGLE_CLOUD_PROJECT");
private static String SESSION_ID = "fake_session_for_testing";
private static String LANGUAGE_CODE = "en-US";
private static String KNOWLEDGE_BASE_NAME = "fake_knowledge_base_name";
private static String DOCUMENT_BASE_NAME = "fake_document_name";
- private String knowledgeBaseId = "";
- private String documentId = "";
- private static List TEXTS = Arrays.asList("Where is my data stored?");
+ private static List TEXTS = Collections.singletonList("Is my data redundant?");
@Before
public void setUp() {
- bout = new ByteArrayOutputStream();
- out = new PrintStream(bout);
- System.setOut(out);
- detectIntentKnowledge = new DetectIntentKnowledge();
- knowledgeBaseManagement = new KnowledgeBaseManagement();
- documentManagement = new DocumentManagement();
+ System.setOut(new PrintStream(new ByteArrayOutputStream()));
}
+ // If any knowledge base/documents remain after test complete, delete them.
@After
- public void tearDown() {
+ public void tearDown() throws Exception {
+ try (KnowledgeBasesClient knowledgeBasesClient = KnowledgeBasesClient.create()) {
+ try (DocumentsClient documentsClient = DocumentsClient.create()) {
+ ProjectName projectName = ProjectName.of(PROJECT_ID);
+ for (KnowledgeBase knowledgeBase :
+ knowledgeBasesClient.listKnowledgeBases(projectName).iterateAll()) {
+ // Delete any documents in the knowledge base.
+ for (Document document : documentsClient.listDocuments(
+ knowledgeBase.getName()).iterateAll()) {
+ documentsClient.deleteDocumentCallable().call(
+ DeleteDocumentRequest.newBuilder().setName(document.getName()).build());
+ }
+ knowledgeBasesClient.deleteKnowledgeBase(knowledgeBase.getName());
+ }
+ }
+ }
System.setOut(null);
}
@Test
public void testKnowledgeBase() throws Exception {
// Check the knowledge base does not yet exist
- knowledgeBaseManagement.listKnowledgeBases(PROJECT_ID);
- String got = bout.toString();
- assertThat(got).doesNotContain("Display Name: " + KNOWLEDGE_BASE_NAME);
+ List knowledgeBases = KnowledgeBaseManagement.listKnowledgeBases(PROJECT_ID);
+ assertEquals(0, knowledgeBases.size());
// Create a Knowledge Base
- knowledgeBaseManagement.createKnowledgeBase(PROJECT_ID,KNOWLEDGE_BASE_NAME);
- got = bout.toString();
- assertThat(got).contains("Display Name: " + KNOWLEDGE_BASE_NAME);
+ KnowledgeBase knowledgeBase =
+ KnowledgeBaseManagement.createKnowledgeBase(PROJECT_ID, KNOWLEDGE_BASE_NAME);
+ assertEquals(knowledgeBase.getDisplayName(), KNOWLEDGE_BASE_NAME);
+
+ // Get KnowledgeBase
+ knowledgeBase = KnowledgeBaseManagement.getKnowledgeBase(knowledgeBase.getName());
+ assertEquals(knowledgeBase.getDisplayName(), KNOWLEDGE_BASE_NAME);
// List Knowledge Bases
- knowledgeBaseManagement.listKnowledgeBases(PROJECT_ID);
- got = bout.toString();
- assertThat(got).contains("Display Name: " + KNOWLEDGE_BASE_NAME);
- knowledgeBaseId = got.split("/knowledgeBases/")[2].trim();
+ knowledgeBases = KnowledgeBaseManagement.listKnowledgeBases(PROJECT_ID);
+ assertEquals(1, knowledgeBases.size());
+ assertEquals(KNOWLEDGE_BASE_NAME, knowledgeBases.get(0).getDisplayName());
- // Get knowledge base
- knowledgeBaseManagement.getKnowledgeBase(PROJECT_ID,knowledgeBaseId);
- got = bout.toString();
- assertThat(got).contains("Display Name: " + KNOWLEDGE_BASE_NAME);
+ // Delete the Knowledge Base
+ KnowledgeBaseManagement.deleteKnowledgeBase(knowledgeBase.getName());
- // Create a Document
- documentManagement.createDocument(PROJECT_ID,knowledgeBaseId,DOCUMENT_BASE_NAME,"text/html","FAQ","https://cloud.google.com/storage/docs/faq");
- got = bout.toString();
- assertThat(got).contains("Display Name: " + DOCUMENT_BASE_NAME);
+ // List Knowledge Bases (ensure delete success)
+ knowledgeBases = KnowledgeBaseManagement.listKnowledgeBases(PROJECT_ID);
+ assertEquals(0, knowledgeBases.size());
+ }
- // List the Document
- documentManagement.listDocuments(PROJECT_ID,knowledgeBaseId);
- got = bout.toString();
- assertThat(got).contains("Display Name: " + DOCUMENT_BASE_NAME);
- documentId = got.split("documents/")[1].split("- MIME Type")[0].trim();
+ @Test
+ public void testDocumentManagement() throws Exception {
+ // Create a Knowledge Base
+ KnowledgeBase knowledgeBase =
+ KnowledgeBaseManagement.createKnowledgeBase(PROJECT_ID, KNOWLEDGE_BASE_NAME);
+ String knowledgeBaseName = knowledgeBase.getName();
- // Get the Document
- documentManagement.getDocument(PROJECT_ID,knowledgeBaseId,documentId);
- got = bout.toString();
- assertThat(got).contains("Display Name: " + DOCUMENT_BASE_NAME);
+ // Create a Document
+ Document document = DocumentManagement.createDocument(
+ knowledgeBaseName,
+ DOCUMENT_BASE_NAME,
+ "text/html",
+ "FAQ",
+ "https://cloud.google.com/storage/docs/faq");
+ assertEquals(DOCUMENT_BASE_NAME, document.getDisplayName());
+
+ // List the Documents
+ List documents = DocumentManagement.listDocuments(knowledgeBaseName);
+ assertEquals(1, documents.size());
+ assertEquals(DOCUMENT_BASE_NAME, documents.get(0).getDisplayName());
- // Detect Intent with Knowledge Base
- detectIntentKnowledge.detectIntentKnowledge(PROJECT_ID, knowledgeBaseId,SESSION_ID,
- LANGUAGE_CODE, TEXTS);
- got = bout.toString();
- assertThat(got).contains("Knowledge results");
+ // Get the Document
+ document = DocumentManagement.getDocument(document.getName());
+ assertEquals(DOCUMENT_BASE_NAME, document.getDisplayName());
// Delete the Document
- bout.reset();
- documentManagement.deleteDocument(PROJECT_ID,knowledgeBaseId,documentId);
- got = bout.toString();
- assertThat(got).contains("The document has been deleted.");
+ DocumentManagement.deleteDocument(document.getName());
// List the Document
- documentManagement.listDocuments(PROJECT_ID,knowledgeBaseId);
- got = bout.toString();
- assertThat(got).doesNotContain("Display Name: " + DOCUMENT_BASE_NAME);
-
- // Delete the Knowledge Base
- knowledgeBaseManagement.deleteKnowledgeBase(PROJECT_ID,knowledgeBaseId);
-
- // List Knowledge Bases
- knowledgeBaseManagement.listKnowledgeBases(PROJECT_ID);
- got = bout.toString();
- assertThat(got).doesNotContain("Display Name: " + KNOWLEDGE_BASE_NAME);
-
+ documents = DocumentManagement.listDocuments(knowledgeBaseName);
+ assertEquals(0, documents.size());
}
-}
\ No newline at end of file
+ @Test
+ public void testDetectIntentKnowledge() throws Exception {
+ // Create a Knowledge Base
+ KnowledgeBase knowledgeBase =
+ KnowledgeBaseManagement.createKnowledgeBase(PROJECT_ID, KNOWLEDGE_BASE_NAME);
+ String knowledgeBaseName = knowledgeBase.getName();
+
+ // Create a Document - one needs to exist in order for detectIntentKnowledge to provide answers.
+ Document document = DocumentManagement.createDocument(
+ knowledgeBaseName,
+ DOCUMENT_BASE_NAME,
+ "text/html",
+ "FAQ",
+ "https://cloud.google.com/storage/docs/faq");
+ assertEquals(DOCUMENT_BASE_NAME, document.getDisplayName());
+
+ Map allAnswers = DetectIntentKnowledge
+ .detectIntentKnowledge(PROJECT_ID, knowledgeBaseName, SESSION_ID, LANGUAGE_CODE, TEXTS);
+ assertEquals(1, allAnswers.size());
+ KnowledgeAnswers knowledgeAnswers = allAnswers.get(TEXTS.get(0));
+ for (String text : TEXTS) {
+ assertEquals(1, knowledgeAnswers.getAnswersCount());
+ Answer answer = knowledgeAnswers.getAnswers(0);
+ assertEquals(text, answer.getFaqQuestion());
+ assertEquals(document.getName(), answer.getSource());
+ assertThat(answer.getAnswer()).contains("Cloud Storage");
+ }
+ }
+}
diff --git a/dialogflow/cloud-client/src/test/java/com/example/dialogflow/SessionEntityTypeManagementIT.java b/dialogflow/cloud-client/src/test/java/com/example/dialogflow/SessionEntityTypeManagementIT.java
index a4f9edf480f..6e7cdcf5b8f 100644
--- a/dialogflow/cloud-client/src/test/java/com/example/dialogflow/SessionEntityTypeManagementIT.java
+++ b/dialogflow/cloud-client/src/test/java/com/example/dialogflow/SessionEntityTypeManagementIT.java
@@ -17,11 +17,20 @@
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.cloud.dialogflow.v2.EntityType;
+import com.google.cloud.dialogflow.v2.EntityType.Kind;
+import com.google.cloud.dialogflow.v2.SessionEntityType;
+import com.google.cloud.dialogflow.v2.SessionEntityTypesClient;
+import com.google.cloud.dialogflow.v2.SessionName;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.util.Arrays;
import java.util.List;
+
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
@@ -39,63 +48,62 @@ public class SessionEntityTypeManagementIT {
private static List ENTITY_VALUES = Arrays.asList("fake_entity_value_1",
"fake_entity_value_2");
private static String PROJECT_ID = System.getenv().get("GOOGLE_CLOUD_PROJECT");
- private ByteArrayOutputStream bout;
- private PrintStream out;
-
- private SessionEntityTypeManagement sessionEntityTypeManagement;
- private EntityTypeManagement entityTypeManagement;
@Before
public void setUp() {
- bout = new ByteArrayOutputStream();
- out = new PrintStream(bout);
- System.setOut(out);
- sessionEntityTypeManagement = new SessionEntityTypeManagement();
- entityTypeManagement = new EntityTypeManagement();
+ System.setOut(new PrintStream(new ByteArrayOutputStream()));
}
-
@After
- public void tearDown() {
+ public void tearDown() throws Exception {
+ try (SessionEntityTypesClient sessionEntityTypesClient = SessionEntityTypesClient.create()) {
+ SessionName session = SessionName.of(PROJECT_ID, SESSION_ID);
+
+ // Performs the list session entity types request
+ for (SessionEntityType sessionEntityType :
+ sessionEntityTypesClient.listSessionEntityTypes(session).iterateAll()) {
+ if (sessionEntityType.getName().equals(ENTITY_TYPE_DISPLAY_NAME)) {
+ sessionEntityTypesClient.deleteSessionEntityType(sessionEntityType.getName());
+ }
+ }
+ }
System.setOut(null);
}
-
@Test
public void testCreateDeleteSessionEntityType() throws Exception {
// Create session entity type
- entityTypeManagement.createEntityType(ENTITY_TYPE_DISPLAY_NAME, PROJECT_ID, "KIND_MAP");
+ EntityType entityType = EntityTypeManagement
+ .createEntityType(ENTITY_TYPE_DISPLAY_NAME, PROJECT_ID, "KIND_MAP");
+ assertEquals(Kind.valueOf("KIND_MAP"), entityType.getKind());
- sessionEntityTypeManagement.createSessionEntityType(PROJECT_ID, SESSION_ID, ENTITY_VALUES,
- ENTITY_TYPE_DISPLAY_NAME, 1);
+ SessionEntityTypeManagement.createSessionEntityType(
+ PROJECT_ID, SESSION_ID, ENTITY_VALUES, ENTITY_TYPE_DISPLAY_NAME, 1);
- sessionEntityTypeManagement.listSessionEntityTypes(PROJECT_ID, SESSION_ID);
+ List sessionEntityTypes = SessionEntityTypeManagement
+ .listSessionEntityTypes(PROJECT_ID, SESSION_ID);
+ assertEquals(1, sessionEntityTypes.size());
+ SessionEntityType sessionEntityType = sessionEntityTypes.get(0);
+ assertThat(sessionEntityType.getName()).contains(SESSION_ID);
+ assertThat(sessionEntityType.getName()).contains(ENTITY_TYPE_DISPLAY_NAME);
- String got = bout.toString();
- assertThat(got).contains(SESSION_ID);
- assertThat(got).contains(ENTITY_TYPE_DISPLAY_NAME);
for (String entityValue : ENTITY_VALUES) {
- assertThat(got).contains(entityValue);
+ assertTrue(sessionEntityType
+ .getEntitiesList().stream().anyMatch(e -> e.getValue().equals(entityValue)));
}
// Delete session entity type
- bout.reset();
- sessionEntityTypeManagement.deleteSessionEntityType(PROJECT_ID, SESSION_ID,
- ENTITY_TYPE_DISPLAY_NAME);
-
- sessionEntityTypeManagement.listSessionEntityTypes(PROJECT_ID, SESSION_ID);
+ SessionEntityTypeManagement.deleteSessionEntityType(
+ PROJECT_ID, SESSION_ID, ENTITY_TYPE_DISPLAY_NAME);
- got = bout.toString();
- assertThat(got).doesNotContain(ENTITY_TYPE_DISPLAY_NAME);
- for (String entityValue : ENTITY_VALUES) {
- assertThat(got).doesNotContain(entityValue);
- }
+ sessionEntityTypes = SessionEntityTypeManagement.listSessionEntityTypes(PROJECT_ID, SESSION_ID);
+ assertEquals(0, sessionEntityTypes.size());
- List entityTypesIds = entityTypeManagement.getEntityTypeIds(ENTITY_TYPE_DISPLAY_NAME,
- PROJECT_ID);
+ List entityTypesIds = EntityTypeManagement.getEntityTypeIds(
+ ENTITY_TYPE_DISPLAY_NAME, PROJECT_ID);
for (String entityTypeId : entityTypesIds) {
- entityTypeManagement.deleteEntityType(entityTypeId, PROJECT_ID);
+ EntityTypeManagement.deleteEntityType(entityTypeId, PROJECT_ID);
}
}
}