diff --git a/dialogflow/cloud-client/pom.xml b/dialogflow/cloud-client/pom.xml index 7f95c9725e8..256522101ef 100644 --- a/dialogflow/cloud-client/pom.xml +++ b/dialogflow/cloud-client/pom.xml @@ -39,7 +39,7 @@ com.google.cloud google-cloud-dialogflow - 1.0.0 + 2.1.0 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 f996f1ef7e0..38f319a9885 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 @@ -16,8 +16,9 @@ package com.example.dialogflow; -// Imports the Google Cloud client library +// [START dialogflow_detect_intent_audio] +import com.google.api.gax.rpc.ApiException; import com.google.cloud.dialogflow.v2.AudioEncoding; import com.google.cloud.dialogflow.v2.DetectIntentRequest; import com.google.cloud.dialogflow.v2.DetectIntentResponse; @@ -27,33 +28,16 @@ import com.google.cloud.dialogflow.v2.SessionName; import com.google.cloud.dialogflow.v2.SessionsClient; import com.google.protobuf.ByteString; +import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; - -/** - * 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 audioFilePath Path to the audio file. - * @param sessionId Identifier of the DetectIntent session. - * @param languageCode Language code of the query. - * @return QueryResult for the request. - */ + // DialogFlow API Detect Intent sample with audio files. public static QueryResult detectIntentAudio( - String projectId, - String audioFilePath, - String sessionId, - String languageCode) - throws Exception { + String projectId, String audioFilePath, String sessionId, String languageCode) + throws IOException, ApiException { // Instantiates a client try (SessionsClient sessionsClient = SessionsClient.create()) { // Set the session name using the sessionId (UUID) and projectID (my-project-id) @@ -66,11 +50,13 @@ public static QueryResult detectIntentAudio( int sampleRateHertz = 16000; // Instructs the speech recognizer how to process the audio content. - InputAudioConfig inputAudioConfig = InputAudioConfig.newBuilder() - .setAudioEncoding(audioEncoding) // audioEncoding = AudioEncoding.AUDIO_ENCODING_LINEAR_16 - .setLanguageCode(languageCode) // languageCode = "en-US" - .setSampleRateHertz(sampleRateHertz) // sampleRateHertz = 16000 - .build(); + InputAudioConfig inputAudioConfig = + InputAudioConfig.newBuilder() + .setAudioEncoding( + audioEncoding) // audioEncoding = AudioEncoding.AUDIO_ENCODING_LINEAR_16 + .setLanguageCode(languageCode) // languageCode = "en-US" + .setSampleRateHertz(sampleRateHertz) // sampleRateHertz = 16000 + .build(); // Build the query with the InputAudioConfig QueryInput queryInput = QueryInput.newBuilder().setAudioConfig(inputAudioConfig).build(); @@ -79,11 +65,12 @@ public static QueryResult detectIntentAudio( byte[] inputAudio = Files.readAllBytes(Paths.get(audioFilePath)); // Build the DetectIntentRequest - DetectIntentRequest request = DetectIntentRequest.newBuilder() - .setSession(session.toString()) - .setQueryInput(queryInput) - .setInputAudio(ByteString.copyFrom(inputAudio)) - .build(); + DetectIntentRequest request = + DetectIntentRequest.newBuilder() + .setSession(session.toString()) + .setQueryInput(queryInput) + .setInputAudio(ByteString.copyFrom(inputAudio)) + .build(); // Performs the detect intent request DetectIntentResponse response = sessionsClient.detectIntent(request); @@ -92,12 +79,13 @@ public static QueryResult detectIntentAudio( QueryResult queryResult = response.getQueryResult(); System.out.println("===================="); System.out.format("Query Text: '%s'\n", queryResult.getQueryText()); - System.out.format("Detected Intent: %s (confidence: %f)\n", + System.out.format( + "Detected Intent: %s (confidence: %f)\n", queryResult.getIntent().getDisplayName(), queryResult.getIntentDetectionConfidence()); System.out.format("Fulfillment Text: '%s'\n", queryResult.getFulfillmentText()); return queryResult; } } - // [END dialogflow_detect_intent_audio] } +// [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 96a04fa6e26..4fc3243ef57 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,8 +16,9 @@ package com.example.dialogflow; -// Imports the Google Cloud client library +// [START dialogflow_detect_intent_knowledge] +import com.google.api.gax.rpc.ApiException; import com.google.cloud.dialogflow.v2beta1.DetectIntentRequest; import com.google.cloud.dialogflow.v2beta1.DetectIntentResponse; import com.google.cloud.dialogflow.v2beta1.KnowledgeAnswers; @@ -29,33 +30,20 @@ import com.google.cloud.dialogflow.v2beta1.SessionsClient; import com.google.cloud.dialogflow.v2beta1.TextInput; import com.google.common.collect.Maps; +import java.io.IOException; import java.util.List; import java.util.Map; -/** - * 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 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. - */ + // DialogFlow API Detect Intent sample with querying knowledge connector. public static Map detectIntentKnowledge( String projectId, String knowledgeBaseName, String sessionId, String languageCode, - List texts) throws Exception { + List texts) + throws IOException, ApiException { // Instantiates a client Map allKnowledgeAnswers = Maps.newHashMap(); try (SessionsClient sessionsClient = SessionsClient.create()) { @@ -72,9 +60,7 @@ public static Map detectIntentKnowledge( QueryInput queryInput = QueryInput.newBuilder().setText(textInput).build(); QueryParameters queryParameters = - QueryParameters.newBuilder() - .addKnowledgeBaseNames(knowledgeBaseName) - .build(); + QueryParameters.newBuilder().addKnowledgeBaseNames(knowledgeBaseName).build(); DetectIntentRequest detectIntentRequest = DetectIntentRequest.newBuilder() @@ -107,5 +93,5 @@ public static Map detectIntentKnowledge( } return allKnowledgeAnswers; } - // [END dialogflow_detect_intent_knowledge] } +// [END dialogflow_detect_intent_knowledge] 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 94a7d4df8d8..ffeffcd4dce 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 @@ -17,7 +17,8 @@ package com.example.dialogflow; // [START dialogflow_detect_intent_streaming] -// Imports the Google Cloud client library + +import com.google.api.gax.rpc.ApiException; import com.google.api.gax.rpc.BidiStream; import com.google.cloud.dialogflow.v2.AudioEncoding; import com.google.cloud.dialogflow.v2.InputAudioConfig; @@ -31,12 +32,11 @@ import java.io.FileInputStream; import java.io.IOException; -/** - * DialogFlow API Detect Intent sample with audio files processes as an audio stream. - */ class DetectIntentStream { - static void detectIntentStream(String projectId, String audioFilePath, String sessionId) { + // DialogFlow API Detect Intent sample with audio files processes as an audio stream. + static void detectIntentStream(String projectId, String audioFilePath, String sessionId) + throws IOException, ApiException { // String projectId = "YOUR_PROJECT_ID"; // String audioFilePath = "path_to_your_audio_file"; // Using the same `sessionId` between requests allows continuation of the conversation. @@ -50,11 +50,12 @@ static void detectIntentStream(String projectId, String audioFilePath, String se // Instructs the speech recognizer how to process the audio content. // Note: hard coding audioEncoding and sampleRateHertz for simplicity. // Audio encoding of the audio content sent in the query request. - InputAudioConfig inputAudioConfig = InputAudioConfig.newBuilder() - .setAudioEncoding(AudioEncoding.AUDIO_ENCODING_LINEAR_16) - .setLanguageCode("en-US") // languageCode = "en-US" - .setSampleRateHertz(16000) // sampleRateHertz = 16000 - .build(); + InputAudioConfig inputAudioConfig = + InputAudioConfig.newBuilder() + .setAudioEncoding(AudioEncoding.AUDIO_ENCODING_LINEAR_16) + .setLanguageCode("en-US") // languageCode = "en-US" + .setSampleRateHertz(16000) // sampleRateHertz = 16000 + .build(); // Build the query with the InputAudioConfig QueryInput queryInput = QueryInput.newBuilder().setAudioConfig(inputAudioConfig).build(); @@ -64,10 +65,11 @@ static void detectIntentStream(String projectId, String audioFilePath, String se sessionsClient.streamingDetectIntentCallable().call(); // The first request must **only** contain the audio configuration: - bidiStream.send(StreamingDetectIntentRequest.newBuilder() - .setSession(session.toString()) - .setQueryInput(queryInput) - .build()); + bidiStream.send( + StreamingDetectIntentRequest.newBuilder() + .setSession(session.toString()) + .setQueryInput(queryInput) + .build()); try (FileInputStream audioStream = new FileInputStream(audioFilePath)) { // Subsequent requests must **only** contain the audio data. @@ -91,13 +93,11 @@ static void detectIntentStream(String projectId, String audioFilePath, String se System.out.println("===================="); System.out.format("Intent Display Name: %s\n", queryResult.getIntent().getDisplayName()); System.out.format("Query Text: '%s'\n", queryResult.getQueryText()); - System.out.format("Detected Intent: %s (confidence: %f)\n", + System.out.format( + "Detected Intent: %s (confidence: %f)\n", queryResult.getIntent().getDisplayName(), queryResult.getIntentDetectionConfidence()); System.out.format("Fulfillment Text: '%s'\n", queryResult.getFulfillmentText()); - } - } catch (IOException e) { - e.printStackTrace(); } } } 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 83e6a813910..89d21562313 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 @@ -16,8 +16,9 @@ package com.example.dialogflow; -// Imports the Google Cloud client library +// [START dialogflow_detect_intent_text] +import com.google.api.gax.rpc.ApiException; import com.google.cloud.dialogflow.v2.DetectIntentResponse; import com.google.cloud.dialogflow.v2.QueryInput; import com.google.cloud.dialogflow.v2.QueryResult; @@ -25,31 +26,16 @@ import com.google.cloud.dialogflow.v2.SessionsClient; import com.google.cloud.dialogflow.v2.TextInput; import com.google.common.collect.Maps; +import java.io.IOException; import java.util.List; import java.util.Map; -/** - * 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 languageCode Language code of the query. - * @return The QueryResult for each input text. - */ + // DialogFlow API Detect Intent sample with text inputs. public static Map detectIntentTexts( - String projectId, - List texts, - String sessionId, - String languageCode) throws Exception { + String projectId, List texts, String sessionId, String languageCode) + throws IOException, ApiException { Map queryResults = Maps.newHashMap(); // Instantiates a client try (SessionsClient sessionsClient = SessionsClient.create()) { @@ -74,7 +60,8 @@ public static Map detectIntentTexts( System.out.println("===================="); System.out.format("Query Text: '%s'\n", queryResult.getQueryText()); - System.out.format("Detected Intent: %s (confidence: %f)\n", + System.out.format( + "Detected Intent: %s (confidence: %f)\n", queryResult.getIntent().getDisplayName(), queryResult.getIntentDetectionConfidence()); System.out.format("Fulfillment Text: '%s'\n", queryResult.getFulfillmentText()); @@ -83,5 +70,5 @@ public static Map detectIntentTexts( } return queryResults; } - // [END dialogflow_detect_intent_text] } +// [END dialogflow_detect_intent_text] 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 4f3dce487ac..136590c9346 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 @@ -16,6 +16,9 @@ package com.example.dialogflow; +// [START dialogflow_detect_intent_with_sentiment_analysis] + +import com.google.api.gax.rpc.ApiException; import com.google.cloud.dialogflow.v2.DetectIntentRequest; import com.google.cloud.dialogflow.v2.DetectIntentResponse; import com.google.cloud.dialogflow.v2.QueryInput; @@ -26,28 +29,15 @@ import com.google.cloud.dialogflow.v2.SessionsClient; import com.google.cloud.dialogflow.v2.TextInput; import com.google.common.collect.Maps; +import java.io.IOException; import java.util.List; import java.util.Map; public class DetectIntentWithSentimentAnalysis { - // [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 languageCode Language code of the query. - * @return The QueryResult for each text in query. - */ - public static Map detectIntentSentimentAnalysis( - String projectId, - List texts, - String sessionId, - String languageCode) throws Exception { + public static Map detectIntentSentimentAnalysis( + String projectId, List texts, String sessionId, String languageCode) + throws IOException, ApiException { Map queryResults = Maps.newHashMap(); // Instantiates a client try (SessionsClient sessionsClient = SessionsClient.create()) { @@ -100,5 +90,5 @@ public static Map detectIntentSentimentAnalysis( } return queryResults; } - // [END dialogflow_detect_intent_with_sentiment_analysis] } +// [END dialogflow_detect_intent_with_sentiment_analysis] 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 933adf88558..3a40384c28d 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 @@ -16,6 +16,9 @@ package com.example.dialogflow; +// [START dialogflow_detect_intent_with_texttospeech_response] + +import com.google.api.gax.rpc.ApiException; import com.google.cloud.dialogflow.v2.DetectIntentRequest; import com.google.cloud.dialogflow.v2.DetectIntentResponse; import com.google.cloud.dialogflow.v2.OutputAudioConfig; @@ -26,28 +29,15 @@ import com.google.cloud.dialogflow.v2.SessionsClient; import com.google.cloud.dialogflow.v2.TextInput; import com.google.common.collect.Maps; +import java.io.IOException; import java.util.List; import java.util.Map; public class DetectIntentWithTextToSpeechResponse { - // [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 languageCode Language code of the query. - * @return The QueryResult for each input text. - */ public static Map detectIntentWithTexttoSpeech( - String projectId, - List texts, - String sessionId, - String languageCode) throws Exception { + String projectId, List texts, String sessionId, String languageCode) + throws IOException, ApiException { Map queryResults = Maps.newHashMap(); // Instantiates a client try (SessionsClient sessionsClient = SessionsClient.create()) { @@ -98,5 +88,5 @@ public static Map detectIntentWithTexttoSpeech( } return queryResults; } - // [END dialogflow_detect_intent_with_texttospeech_response] } +// [END dialogflow_detect_intent_with_texttospeech_response] 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 8666e86cb0f..a78e7ae058b 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 @@ -16,32 +16,29 @@ package com.example.dialogflow; +// [START dialogflow_create_document] + import com.google.api.gax.longrunning.OperationFuture; +import com.google.api.gax.rpc.ApiException; import com.google.cloud.dialogflow.v2beta1.CreateDocumentRequest; import com.google.cloud.dialogflow.v2beta1.Document; import com.google.cloud.dialogflow.v2beta1.Document.KnowledgeType; import com.google.cloud.dialogflow.v2beta1.DocumentsClient; import com.google.cloud.dialogflow.v2beta1.KnowledgeOperationMetadata; +import java.io.IOException; +import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; public class DocumentManagement { - // [START dialogflow_create_document] - /** - * @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 Document createDocument( String knowledgeBaseName, String displayName, String mimeType, String knowledgeType, String contentUri) - throws Exception { + throws IOException, ApiException, InterruptedException, ExecutionException, TimeoutException { // Instantiates a client try (DocumentsClient documentsClient = DocumentsClient.create()) { Document document = @@ -71,5 +68,5 @@ public static Document createDocument( return createdDocument; } } - // [END dialogflow_create_document] } +// [END dialogflow_create_document] 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 e7a19579ee8..a9ed0f51880 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 @@ -18,6 +18,8 @@ // Imports the Google Cloud client library +import com.google.api.gax.rpc.ApiException; +import com.google.cloud.dialogflow.v2.AgentName; import com.google.cloud.dialogflow.v2.Context; import com.google.cloud.dialogflow.v2.Intent; import com.google.cloud.dialogflow.v2.Intent.Message; @@ -26,14 +28,12 @@ import com.google.cloud.dialogflow.v2.Intent.TrainingPhrase.Part; import com.google.cloud.dialogflow.v2.IntentName; import com.google.cloud.dialogflow.v2.IntentsClient; -import com.google.cloud.dialogflow.v2.ProjectAgentName; import com.google.common.collect.Lists; +import java.io.IOException; import java.util.ArrayList; import java.util.List; -/** - * DialogFlow API Intent sample. - */ +/** DialogFlow API Intent sample. */ public class IntentManagement { // [START dialogflow_list_intents] @@ -43,12 +43,12 @@ public class IntentManagement { * @param projectId Project/Agent Id. * @return Intents found. */ - public static List listIntents(String projectId) throws Exception { + public static List listIntents(String projectId) throws ApiException, IOException { List intents = Lists.newArrayList(); // Instantiates a client try (IntentsClient intentsClient = IntentsClient.create()) { // Set the project agent name using the projectID (my-project-id) - ProjectAgentName parent = ProjectAgentName.of(projectId); + AgentName parent = AgentName.of(projectId); // Performs the list intents request for (Intent intent : intentsClient.listIntents(parent).iterateAll()) { @@ -80,44 +80,43 @@ public static List listIntents(String projectId) throws Exception { /** * 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 Intent createIntent( String displayName, String projectId, List trainingPhrasesParts, - List messageTexts) throws Exception { + List messageTexts) + throws ApiException, IOException { // Instantiates a client try (IntentsClient intentsClient = IntentsClient.create()) { // Set the project agent name using the projectID (my-project-id) - ProjectAgentName parent = ProjectAgentName.of(projectId); + AgentName parent = AgentName.of(projectId); // Build the trainingPhrases from the trainingPhrasesParts List trainingPhrases = new ArrayList<>(); for (String trainingPhrase : trainingPhrasesParts) { trainingPhrases.add( - TrainingPhrase.newBuilder().addParts( - Part.newBuilder().setText(trainingPhrase).build()) + TrainingPhrase.newBuilder() + .addParts(Part.newBuilder().setText(trainingPhrase).build()) .build()); } // Build the message texts for the agent's response - Message message = Message.newBuilder() - .setText( - Text.newBuilder() - .addAllText(messageTexts).build() - ).build(); + Message message = + Message.newBuilder().setText(Text.newBuilder().addAllText(messageTexts).build()).build(); // Build the intent - Intent intent = Intent.newBuilder() - .setDisplayName(displayName) - .addMessages(message) - .addAllTrainingPhrases(trainingPhrases) - .build(); + Intent intent = + Intent.newBuilder() + .setDisplayName(displayName) + .addMessages(message) + .addAllTrainingPhrases(trainingPhrases) + .build(); // Performs the create intent request Intent response = intentsClient.createIntent(parent, intent); @@ -133,10 +132,11 @@ public static Intent createIntent( /** * 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 { + public static void deleteIntent(String intentId, String projectId) + throws ApiException, IOException { // Instantiates a client try (IntentsClient intentsClient = IntentsClient.create()) { IntentName name = IntentName.of(projectId, intentId); @@ -146,15 +146,14 @@ public static void deleteIntent(String intentId, String projectId) throws Except } // [END dialogflow_delete_intent] - /** - * Helper method for testing to get intentIds from displayName. - */ - public static List getIntentIds(String displayName, String projectId) throws Exception { + /** Helper method for testing to get intentIds from displayName. */ + public static List getIntentIds(String displayName, String projectId) + throws ApiException, IOException { List intentIds = new ArrayList<>(); // Instantiates a client try (IntentsClient intentsClient = IntentsClient.create()) { - ProjectAgentName parent = ProjectAgentName.of(projectId); + AgentName parent = AgentName.of(projectId); for (Intent intent : intentsClient.listIntents(parent).iterateAll()) { if (intent.getDisplayName().equals(displayName)) { String[] splitName = intent.getName().split("/"); 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 506ae1982f4..c64b2609681 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 @@ -16,23 +16,19 @@ package com.example.dialogflow; +// [START dialogflow_create_knowledge_base] + +import com.google.api.gax.rpc.ApiException; import com.google.cloud.dialogflow.v2beta1.KnowledgeBase; import com.google.cloud.dialogflow.v2beta1.KnowledgeBasesClient; import com.google.cloud.dialogflow.v2beta1.ProjectName; - +import java.io.IOException; public class KnowledgeBaseManagement { - // [START dialogflow_create_knowledge_base] - /** - * Create a Knowledge base - * - * @param projectId Project/agent id. - * @param displayName Name of the knowledge base. - * @return The created KnowledgeBase. - */ + // Create a Knowledge base public static KnowledgeBase createKnowledgeBase(String projectId, String displayName) - throws Exception { + throws ApiException, IOException { // Instantiates a client try (KnowledgeBasesClient knowledgeBasesClient = KnowledgeBasesClient.create()) { KnowledgeBase knowledgeBase = KnowledgeBase.newBuilder().setDisplayName(displayName).build(); @@ -45,6 +41,5 @@ public static KnowledgeBase createKnowledgeBase(String projectId, String display return response; } } - // [END dialogflow_create_knowledge_base] - } +// [END dialogflow_create_knowledge_base] diff --git a/dialogflow/cloud-client/src/test/java/com/example/dialogflow/CreateDocumentTest.java b/dialogflow/cloud-client/src/test/java/com/example/dialogflow/CreateDocumentTest.java index e75405a0b6f..8aaa3830053 100644 --- a/dialogflow/cloud-client/src/test/java/com/example/dialogflow/CreateDocumentTest.java +++ b/dialogflow/cloud-client/src/test/java/com/example/dialogflow/CreateDocumentTest.java @@ -46,9 +46,7 @@ public class CreateDocumentTest { private String knowledgeBaseName; private static void requireEnvVar(String varName) { - assertNotNull( - "Environment variable '%s' is required to perform these tests.".format(varName), - String.format(varName)); + assertNotNull(String.format(varName), String.format(varName)); } @BeforeClass diff --git a/dialogflow/cloud-client/src/test/java/com/example/dialogflow/CreateKnowledgeBaseTest.java b/dialogflow/cloud-client/src/test/java/com/example/dialogflow/CreateKnowledgeBaseTest.java index 5581868f1a7..7f5a6395877 100644 --- a/dialogflow/cloud-client/src/test/java/com/example/dialogflow/CreateKnowledgeBaseTest.java +++ b/dialogflow/cloud-client/src/test/java/com/example/dialogflow/CreateKnowledgeBaseTest.java @@ -44,9 +44,7 @@ public class CreateKnowledgeBaseTest { private String knowledgeBaseName; private static void requireEnvVar(String varName) { - assertNotNull( - "Environment variable '%s' is required to perform these tests.".format(varName), - String.format(varName)); + assertNotNull(String.format(varName), String.format(varName)); } @BeforeClass diff --git a/dialogflow/cloud-client/src/test/java/com/example/dialogflow/DetectIntentKnowledgeTest.java b/dialogflow/cloud-client/src/test/java/com/example/dialogflow/DetectIntentKnowledgeTest.java index fb940c31383..0f1aa54d880 100644 --- a/dialogflow/cloud-client/src/test/java/com/example/dialogflow/DetectIntentKnowledgeTest.java +++ b/dialogflow/cloud-client/src/test/java/com/example/dialogflow/DetectIntentKnowledgeTest.java @@ -35,7 +35,6 @@ import org.junit.runner.RunWith; import org.junit.runners.JUnit4; - @RunWith(JUnit4.class) @SuppressWarnings("checkstyle:abbreviationaswordinname") public class DetectIntentKnowledgeTest { @@ -46,10 +45,14 @@ public class DetectIntentKnowledgeTest { private static String SESSION_ID = UUID.randomUUID().toString(); private static String LANGUAGE_CODE = "en-US"; - private static List TEXTS = ImmutableList - .of("How do I sign up?", "Is my data redundant?", "Where can I find pricing information?", - "Where is my data stored?", "What are my support options?", - "How can I maximize the availability of my data?"); + private static List TEXTS = + ImmutableList.of( + "How do I sign up?", + "Is my data redundant?", + "Where can I find pricing information?", + "Where is my data stored?", + "What are my support options?", + "How can I maximize the availability of my data?"); @Before public void setUp() { @@ -63,16 +66,21 @@ public void tearDown() { @Test public void testDetectIntentKnowledge() throws Exception { - KnowledgeBaseName knowledgeBaseName = KnowledgeBaseName.newBuilder() - .setProject(PROJECT_ID).setKnowledgeBase(TEST_KNOWLEDGE_BASE_ID).build(); + KnowledgeBaseName knowledgeBaseName = + KnowledgeBaseName.newBuilder() + .setProject(PROJECT_ID) + .setKnowledgeBase(TEST_KNOWLEDGE_BASE_ID) + .build(); - DocumentName documentName = DocumentName.newBuilder() + DocumentName documentName = + DocumentName.newBuilder() .setProject(PROJECT_ID) .setKnowledgeBase(TEST_KNOWLEDGE_BASE_ID) .setDocument(TEST_DOCUMENT_ID) .build(); - Map allAnswers = DetectIntentKnowledge.detectIntentKnowledge( + Map allAnswers = + DetectIntentKnowledge.detectIntentKnowledge( PROJECT_ID, knowledgeBaseName.toString(), SESSION_ID, LANGUAGE_CODE, TEXTS); assertEquals(TEXTS.size(), allAnswers.size()); int answersFound = 0; @@ -81,7 +89,7 @@ public void testDetectIntentKnowledge() throws Exception { if (knowledgeAnswers.getAnswersCount() > 0) { Answer answer = knowledgeAnswers.getAnswers(0); if (text.equals(answer.getFaqQuestion()) - && documentName.toString().equals(answer.getSource())) { + && documentName.toString().equals(answer.getSource())) { answersFound++; } } 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 cc1063f9703..a29f03be3a8 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 @@ -19,6 +19,7 @@ import static com.google.common.truth.Truth.assertThat; import java.io.ByteArrayOutputStream; +import java.io.IOException; import java.io.PrintStream; import java.util.UUID; import org.junit.After; @@ -27,18 +28,15 @@ import org.junit.runner.RunWith; import org.junit.runners.JUnit4; -/** - * Integration (system) tests for {@link DetectIntentStream}. - */ +/** Integration (system) tests for {@link DetectIntentStream}. */ @RunWith(JUnit4.class) @SuppressWarnings("checkstyle:abbreviationaswordinname") public class DetectIntentStreamIT { - private ByteArrayOutputStream bout; - private static String audioFilePath = "resources/book_a_room.wav"; private static String PROJECT_ID = System.getenv().get("GOOGLE_CLOUD_PROJECT"); private static String SESSION_ID = UUID.randomUUID().toString(); + private ByteArrayOutputStream bout; @Before public void setUp() { @@ -53,9 +51,8 @@ public void tearDown() { } @Test - public void testStreamingDetectIntentCallable() { - DetectIntentStream.detectIntentStream( - PROJECT_ID, audioFilePath, SESSION_ID); + public void testStreamingDetectIntentCallable() throws IOException { + DetectIntentStream.detectIntentStream(PROJECT_ID, audioFilePath, SESSION_ID); String output = bout.toString(); diff --git a/dialogflow/cloud-client/src/test/java/com/example/dialogflow/DetectIntentWithAudioTest.java b/dialogflow/cloud-client/src/test/java/com/example/dialogflow/DetectIntentWithAudioTest.java index 20d1ca187cd..51649607304 100644 --- a/dialogflow/cloud-client/src/test/java/com/example/dialogflow/DetectIntentWithAudioTest.java +++ b/dialogflow/cloud-client/src/test/java/com/example/dialogflow/DetectIntentWithAudioTest.java @@ -40,19 +40,25 @@ public class DetectIntentWithAudioTest { protected static String PROJECT_ID = System.getenv().get("GOOGLE_CLOUD_PROJECT"); protected static String SESSION_ID = UUID.randomUUID().toString(); protected static String LANGUAGE_CODE = "en-US"; - protected static List QUESTIONS = ImmutableList.of( - "What date?", - "What time will the meeting start?", - "How long will it last?", - "Thanks. How many people are attending?", - "I can help with that. Where would you like to reserve a room?"); - protected static Map ANSWERS = ImmutableMap.of( - "I can help with that. Where would you like to reserve a room?", - "resources/mountain_view.wav", - "What date?", "resources/today.wav", - "What time will the meeting start?", "resources/230pm.wav", - "How long will it last?", "resources/half_an_hour.wav", - "Thanks. How many people are attending?", "resources/two_people.wav"); + 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() { @@ -67,8 +73,9 @@ public void tearDown() { @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); + 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) @@ -76,8 +83,9 @@ public void testDetectIntentAudio() throws Exception { 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); + result = + DetectIntentAudio.detectIntentAudio( + PROJECT_ID, ANSWERS.get(fulfillmentText), SESSION_ID, LANGUAGE_CODE); fulfillmentText = result.getFulfillmentText(); } assertTrue(result.getAllRequiredParamsPresent()); 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 index 1f7c9ddd55d..0e902d6c497 100644 --- a/dialogflow/cloud-client/src/test/java/com/example/dialogflow/DetectIntentWithSentimentAndTextToSpeechIT.java +++ b/dialogflow/cloud-client/src/test/java/com/example/dialogflow/DetectIntentWithSentimentAndTextToSpeechIT.java @@ -32,9 +32,7 @@ import org.junit.runner.RunWith; import org.junit.runners.JUnit4; -/** - * Integration (system) tests for {@link DetectIntentWithSentimentAnalysis}. - */ +/** Integration (system) tests for {@link DetectIntentWithSentimentAnalysis}. */ @RunWith(JUnit4.class) @SuppressWarnings("checkstyle:abbreviationaswordinname") public class DetectIntentWithSentimentAndTextToSpeechIT { @@ -42,16 +40,17 @@ public class DetectIntentWithSentimentAndTextToSpeechIT { private static String PROJECT_ID = System.getenv().get("GOOGLE_CLOUD_PROJECT"); private static String SESSION_ID = UUID.randomUUID().toString(); private static String LANGUAGE_CODE = "en-US"; - private static List TEXTS = Arrays.asList( - "hello", - "book a meeting room", - "Mountain View", - "tomorrow", - "10 am", - "2 hours", - "10 people", - "A", - "yes"); + 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() { @@ -65,7 +64,7 @@ public void tearDown() { @Test public void testDetectIntentTexts() throws Exception { - Map queryResults = + 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)); @@ -75,14 +74,16 @@ public void testDetectIntentTexts() throws Exception { @Test public void testDetectIntentWithSentimentAnalysis() throws Exception { - assertResults(DetectIntentWithSentimentAnalysis - .detectIntentSentimentAnalysis(PROJECT_ID, TEXTS, SESSION_ID, LANGUAGE_CODE)); + 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)); + assertResults( + DetectIntentWithTextToSpeechResponse.detectIntentWithTexttoSpeech( + PROJECT_ID, TEXTS, SESSION_ID, LANGUAGE_CODE)); } private void assertResults(Map queryResults) { 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 1826f3d45ef..09bdf8299dc 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 @@ -21,9 +21,9 @@ import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; +import com.google.cloud.dialogflow.v2.AgentName; import com.google.cloud.dialogflow.v2.Intent; import com.google.cloud.dialogflow.v2.IntentsClient; -import com.google.cloud.dialogflow.v2.ProjectAgentName; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import java.util.Arrays; @@ -35,19 +35,15 @@ import org.junit.runner.RunWith; import org.junit.runners.JUnit4; -/** - * Integration (system) tests for {@link IntentManagement}. - */ +/** Integration (system) tests for {@link IntentManagement}. */ @RunWith(JUnit4.class) @SuppressWarnings("checkstyle:abbreviationaswordinname") public class IntentManagementIT { private static String INTENT_DISPLAY_NAME = UUID.randomUUID().toString(); - private static List MESSAGE_TEXTS = Arrays.asList( - "fake_message_text_for_testing_1", - "fake_message_text_for_testing_2"); - private static List TRAINING_PHRASE_PARTS = Arrays.asList( - "fake_training_phrase_part_1", - "fake_training_phrase_part_2"); + private static List MESSAGE_TEXTS = + Arrays.asList("fake_message_text_for_testing_1", "fake_message_text_for_testing_2"); + private static List TRAINING_PHRASE_PARTS = + Arrays.asList("fake_training_phrase_part_1", "fake_training_phrase_part_2"); private static String PROJECT_ID = System.getenv().get("GOOGLE_CLOUD_PROJECT"); @Before @@ -59,7 +55,7 @@ public void setUp() { 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); + AgentName parent = AgentName.of(PROJECT_ID); // Performs the list intents request for (Intent intent : intentsClient.listIntents(parent).iterateAll()) { @@ -74,8 +70,9 @@ public void tearDown() throws Exception { @Test public void testCreateIntent() throws Exception { // Create the intent - Intent intent = IntentManagement.createIntent( - INTENT_DISPLAY_NAME, PROJECT_ID, TRAINING_PHRASE_PARTS, MESSAGE_TEXTS); + Intent intent = + IntentManagement.createIntent( + INTENT_DISPLAY_NAME, PROJECT_ID, TRAINING_PHRASE_PARTS, MESSAGE_TEXTS); assertNotNull(intent); List intentIds = IntentManagement.getIntentIds(intent.getDisplayName(), PROJECT_ID); @@ -85,8 +82,9 @@ public void testCreateIntent() throws Exception { assertTrue(intents.size() > 0); assertThat(intents).contains(intent); for (String messageText : MESSAGE_TEXTS) { - assertTrue(intent.getMessagesList() - .stream().anyMatch(message -> message.getText().toString().contains(messageText))); + assertTrue( + intent.getMessagesList().stream() + .anyMatch(message -> message.getText().toString().contains(messageText))); } for (String intentId : intentIds) {