diff --git a/dialogflow-cx/pom.xml b/dialogflow-cx/pom.xml new file mode 100644 index 00000000000..ab51bbfb446 --- /dev/null +++ b/dialogflow-cx/pom.xml @@ -0,0 +1,68 @@ + + + 4.0.0 + com.example.dialogflow-cx + dialogflow-cx-snippets + jar + Google Dialogflow CX Snippets + https://github.com/GoogleCloudPlatform/java-docs-samples/tree/main/dialogflow-cx + + + + com.google.cloud.samples + shared-configuration + 1.2.0 + + + + 11 + 11 + UTF-8 + + + + + + com.google.cloud + google-cloud-dialogflow-cx + 0.14.7 + + + com.google.code.gson + gson + 2.9.1 + + + com.google.cloud.functions + functions-framework-api + 1.0.4 + + + junit + junit + 4.13.2 + test + + + com.google.cloud.functions + function-maven-plugin + 0.10.1 + test + + + org.mockito + mockito-core + 4.8.0 + test + + + com.google.truth + truth + 1.1.3 + test + + + diff --git a/dialogflow-cx/resources/book_a_room.wav b/dialogflow-cx/resources/book_a_room.wav new file mode 100644 index 00000000000..9124e927946 Binary files /dev/null and b/dialogflow-cx/resources/book_a_room.wav differ diff --git a/dialogflow-cx/src/main/java/dialogflow/cx/ConfigureWebhookToSetFormParametersAsOptionalOrRequired.java b/dialogflow-cx/src/main/java/dialogflow/cx/ConfigureWebhookToSetFormParametersAsOptionalOrRequired.java new file mode 100644 index 00000000000..b94c55242ba --- /dev/null +++ b/dialogflow-cx/src/main/java/dialogflow/cx/ConfigureWebhookToSetFormParametersAsOptionalOrRequired.java @@ -0,0 +1,81 @@ +/* + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package dialogflow.cx; + +// The following snippet is used in https://cloud.google.com/dialogflow/cx/docs/concept/webhook + +// [START dialogflow_cx_v3_configure_webhooks_to_set_form_parameter_as_optional_or_required] + +// TODO: Change class name to Example +// TODO: Uncomment the line below before running cloud function +// package com.example; + +import com.google.cloud.functions.HttpFunction; +import com.google.cloud.functions.HttpRequest; +import com.google.cloud.functions.HttpResponse; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonArray; +import com.google.gson.JsonObject; +import java.io.BufferedWriter; + +public class ConfigureWebhookToSetFormParametersAsOptionalOrRequired implements HttpFunction { + @Override + public void service(HttpRequest request, HttpResponse response) throws Exception { + JsonObject parameterObject = new JsonObject(); + parameterObject.addProperty("display_name", "order_number"); + parameterObject.addProperty("required", "true"); + parameterObject.addProperty("state", "VALID"); + + JsonArray parameterInfoList = new JsonArray(); + parameterInfoList.add(parameterObject); + + JsonObject parameterInfoObject = new JsonObject(); + parameterInfoObject.add("parameter_info", parameterInfoList); + + JsonObject formInfo = new JsonObject(); + formInfo.add("form_info", parameterInfoObject); + + // Constructs the webhook response object + JsonObject webhookResponse = new JsonObject(); + webhookResponse.add("page_info", formInfo); + + Gson gson = new GsonBuilder().setPrettyPrinting().create(); + String jsonResponseObject = gson.toJson(webhookResponse); + + /* { + * "page_info": { + * "form_info": { + * "parameter_info": [ + * { + * "display_name": "order_number", + * "required": "true", + * "state": "VALID" + * } + * ] + * } + * } + * } + */ + + BufferedWriter writer = response.getWriter(); + + // Sends the responseObject + writer.write(jsonResponseObject.toString()); + } +} +// [END dialogflow_cx_v3_configure_webhooks_to_set_form_parameter_as_optional_or_required] diff --git a/dialogflow-cx/src/main/java/dialogflow/cx/CreateAgent.java b/dialogflow-cx/src/main/java/dialogflow/cx/CreateAgent.java new file mode 100644 index 00000000000..657abed0ee4 --- /dev/null +++ b/dialogflow-cx/src/main/java/dialogflow/cx/CreateAgent.java @@ -0,0 +1,65 @@ +/* + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package dialogflow.cx; + +// [START dialogflow_cx_create_agent] + +import com.google.cloud.dialogflow.cx.v3.Agent; +import com.google.cloud.dialogflow.cx.v3.Agent.Builder; +import com.google.cloud.dialogflow.cx.v3.AgentsClient; +import com.google.cloud.dialogflow.cx.v3.AgentsSettings; +import java.io.IOException; + +public class CreateAgent { + + public static void main(String[] args) throws IOException { + // TODO(developer): Replace these variables before running the sample. + String projectId = "my-project-id"; + String displayName = "my-display-name"; + + createAgent(projectId, displayName); + } + + public static Agent createAgent(String parent, String displayName) throws IOException { + + String apiEndpoint = "global-dialogflow.googleapis.com:443"; + + AgentsSettings agentsSettings = AgentsSettings.newBuilder().setEndpoint(apiEndpoint).build(); + // Note: close() needs to be called on the AgentsClient object to clean up resources + // such as threads. In the example below, try-with-resources is used, + // which automatically calls close(). + try (AgentsClient client = AgentsClient.create(agentsSettings)) { + // Set the details of the Agent to create + Builder build = Agent.newBuilder(); + + build.setDefaultLanguageCode("en"); + build.setDisplayName(displayName); + // Correct format for timezone is location/city + // For example America/Los_Angeles, Europe/Madrid, Asia/Tokyo + build.setTimeZone("America/Los_Angeles"); + + Agent agent = build.build(); + String parentPath = String.format("projects/%s/locations/%s", parent, "global"); + + // Calls the create agent api and returns the created Agent + Agent response = client.createAgent(parentPath, agent); + System.out.println(response); + return response; + } + } +} +// [END dialogflow_cx_create_agent] diff --git a/dialogflow-cx/src/main/java/dialogflow/cx/CreateFlow.java b/dialogflow-cx/src/main/java/dialogflow/cx/CreateFlow.java new file mode 100644 index 00000000000..1719f152639 --- /dev/null +++ b/dialogflow-cx/src/main/java/dialogflow/cx/CreateFlow.java @@ -0,0 +1,93 @@ +/* + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package dialogflow.cx; + +// [START dialogflow_cx_create_flow] + +import com.google.api.gax.rpc.ApiException; +import com.google.cloud.dialogflow.cx.v3beta1.AgentName; +import com.google.cloud.dialogflow.cx.v3beta1.EventHandler; +import com.google.cloud.dialogflow.cx.v3beta1.Flow; +import com.google.cloud.dialogflow.cx.v3beta1.FlowsClient; +import com.google.cloud.dialogflow.cx.v3beta1.FlowsSettings; +import com.google.cloud.dialogflow.cx.v3beta1.Fulfillment; +import com.google.cloud.dialogflow.cx.v3beta1.ResponseMessage; +import com.google.cloud.dialogflow.cx.v3beta1.ResponseMessage.Text; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +public class CreateFlow { + + // Create a flow in the specified agent. + public static Flow createFlow( + String displayName, + String projectId, + String locationId, + String agentId, + Map eventsToFulfillmentMessages) + throws IOException, ApiException { + FlowsSettings.Builder flowsSettingsBuilder = FlowsSettings.newBuilder(); + if (locationId.equals("global")) { + flowsSettingsBuilder.setEndpoint("dialogflow.googleapis.com:443"); + } else { + flowsSettingsBuilder.setEndpoint(locationId + "-dialogflow.googleapis.com:443"); + } + FlowsSettings flowsSettings = flowsSettingsBuilder.build(); + + // Instantiates a client. + // Note: close() needs to be called on the FlowsClient object to clean up resources + // such as threads. In the example below, try-with-resources is used, + // which automatically calls close(). + try (FlowsClient flowsClient = FlowsClient.create(flowsSettings)) { + // Set the project agent name using the projectID (my-project-id), locationID (global), and + // agentID (UUID). + AgentName parent = AgentName.of(projectId, locationId, agentId); + + // Build the EventHandlers for the flow using the mapping from events to fulfillment messages. + List eventHandlers = new ArrayList<>(); + for (Map.Entry item : eventsToFulfillmentMessages.entrySet()) { + eventHandlers.add( + EventHandler.newBuilder() + .setEvent(item.getKey()) // Event (sys.no-match-default) + .setTriggerFulfillment( + Fulfillment.newBuilder() + // Text ("Sorry, could you say that again?") + .addMessages( + ResponseMessage.newBuilder() + .setText(Text.newBuilder().addText(item.getValue()).build()) + .build()) + .build()) + .build()); + } + + // Build the flow. + Flow flow = + Flow.newBuilder().setDisplayName(displayName).addAllEventHandlers(eventHandlers).build(); + + // Performs the create flow request. + Flow response = flowsClient.createFlow(parent, flow); + + // TODO : Uncomment if you want to print response + // System.out.format("Flow created: %s\n", response.toString()); + flowsClient.shutdown(); + return response; + } + } +} +// [END dialogflow_cx_create_flow] diff --git a/dialogflow-cx/src/main/java/dialogflow/cx/CreateIntent.java b/dialogflow-cx/src/main/java/dialogflow/cx/CreateIntent.java new file mode 100644 index 00000000000..3469c184853 --- /dev/null +++ b/dialogflow-cx/src/main/java/dialogflow/cx/CreateIntent.java @@ -0,0 +1,86 @@ +/* + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package dialogflow.cx; + +// [START dialogflow_cx_create_intent] + +import com.google.api.gax.rpc.ApiException; +import com.google.cloud.dialogflow.cx.v3beta1.AgentName; +import com.google.cloud.dialogflow.cx.v3beta1.Intent; +import com.google.cloud.dialogflow.cx.v3beta1.Intent.TrainingPhrase; +import com.google.cloud.dialogflow.cx.v3beta1.Intent.TrainingPhrase.Part; +import com.google.cloud.dialogflow.cx.v3beta1.IntentsClient; +import com.google.cloud.dialogflow.cx.v3beta1.IntentsSettings; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +public class CreateIntent { + + // Create an intent of the given intent type. + public static Intent createIntent( + String displayName, + String projectId, + String locationId, + String agentId, + List trainingPhrasesParts) + throws IOException, ApiException { + IntentsSettings.Builder intentsSettingsBuilder = IntentsSettings.newBuilder(); + if (locationId.equals("global")) { + intentsSettingsBuilder.setEndpoint("dialogflow.googleapis.com:443"); + } else { + intentsSettingsBuilder.setEndpoint(locationId + "-dialogflow.googleapis.com:443"); + } + IntentsSettings intentsSettings = intentsSettingsBuilder.build(); + + // Instantiates a client + // Note: close() needs to be called on the IntentsClient object to clean up resources + // such as threads. In the example below, try-with-resources is used, + // which automatically calls close(). + try (IntentsClient intentsClient = IntentsClient.create(intentsSettings)) { + // Set the project agent name using the projectID (my-project-id), locationID (global), and + // agentID (UUID). + AgentName parent = AgentName.of(projectId, locationId, agentId); + + // Build the trainingPhrases from the trainingPhrasesParts. + List trainingPhrases = new ArrayList<>(); + for (String trainingPhrase : trainingPhrasesParts) { + trainingPhrases.add( + TrainingPhrase.newBuilder() + .addParts(Part.newBuilder().setText(trainingPhrase).build()) + .setRepeatCount(1) + .build()); + } + + // Build the intent. + Intent intent = + Intent.newBuilder() + .setDisplayName(displayName) + .addAllTrainingPhrases(trainingPhrases) + .build(); + + // Performs the create intent request. + Intent response = intentsClient.createIntent(parent, intent); + + // TODO : Uncomment if you want to print response + // System.out.format("Intent created: %s\n", response); + + return response; + } + } +} +// [END dialogflow_cx_create_intent] diff --git a/dialogflow-cx/src/main/java/dialogflow/cx/CreatePage.java b/dialogflow-cx/src/main/java/dialogflow/cx/CreatePage.java new file mode 100644 index 00000000000..b45bc46f81f --- /dev/null +++ b/dialogflow-cx/src/main/java/dialogflow/cx/CreatePage.java @@ -0,0 +1,116 @@ +/* + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package dialogflow.cx; + +// [START dialogflow_cx_create_page] + +import com.google.api.gax.rpc.ApiException; +import com.google.cloud.dialogflow.cx.v3beta1.FlowName; +import com.google.cloud.dialogflow.cx.v3beta1.Form; +import com.google.cloud.dialogflow.cx.v3beta1.Form.Parameter; +import com.google.cloud.dialogflow.cx.v3beta1.Form.Parameter.FillBehavior; +import com.google.cloud.dialogflow.cx.v3beta1.Fulfillment; +import com.google.cloud.dialogflow.cx.v3beta1.Page; +import com.google.cloud.dialogflow.cx.v3beta1.PagesClient; +import com.google.cloud.dialogflow.cx.v3beta1.PagesSettings; +import com.google.cloud.dialogflow.cx.v3beta1.ResponseMessage; +import com.google.cloud.dialogflow.cx.v3beta1.ResponseMessage.Text; +import java.io.IOException; +import java.util.List; + +public class CreatePage { + + // Create a page in the specified agent. + public static Page createPage( + String displayName, + String projectId, + String locationId, + String agentId, + String flowId, + List entryTexts) + throws IOException, ApiException { + PagesSettings.Builder pagesSettingsBuilder = PagesSettings.newBuilder(); + if (locationId.equals("global")) { + pagesSettingsBuilder.setEndpoint("dialogflow.googleapis.com:443"); + } else { + pagesSettingsBuilder.setEndpoint(locationId + "-dialogflow.googleapis.com:443"); + } + PagesSettings pagesSettings = pagesSettingsBuilder.build(); + + // Instantiates a client + // Note: close() needs to be called on the PagesClient object to clean up resources + // such as threads. In the example below, try-with-resources is used, + // which automatically calls close(). + try (PagesClient pagesClient = PagesClient.create(pagesSettings)) { + // Set the flow name using the projectID (my-project-id), locationID (global), agentID (UUID) + // and flowID (UUID). + FlowName parent = FlowName.of(projectId, locationId, agentId, flowId); + + // Build the entry fulfillment based on entry texts. + Fulfillment.Builder entryFulfillmentBuilder = Fulfillment.newBuilder(); + for (String entryText : entryTexts) { + entryFulfillmentBuilder.addMessages( + ResponseMessage.newBuilder() + // Text ("Hi") + .setText(Text.newBuilder().addText(entryText).build()) + .build()); + } + Fulfillment entryFulfillment = entryFulfillmentBuilder.build(); + + // Build the form for the new page. + // Note: hard coding parameters for simplicity. + FillBehavior fillBehavior = + FillBehavior.newBuilder() + .setInitialPromptFulfillment( + Fulfillment.newBuilder() + .addMessages( + ResponseMessage.newBuilder() + .setText(Text.newBuilder().addText("What would you like?").build()) + .build()) + .build()) + .build(); + Form form = + Form.newBuilder() + .addParameters( + Parameter.newBuilder() + .setDisplayName("param") + .setRequired(true) + .setEntityType("projects/-/locations/-/agents/-/entityTypes/sys.any") + .setFillBehavior(fillBehavior) + .build()) + .build(); + + // Build the page. + Page page = + Page.newBuilder() + .setDisplayName(displayName) + .setEntryFulfillment(entryFulfillment) + .setForm(form) + .build(); + + // Performs the create page request. + Page response = pagesClient.createPage(parent, page); + + // TODO : Uncomment if you want to print response + // System.out.format("Page created: %s\n", response.toString()); + + pagesClient.shutdown(); + return response; + } + } +} +// [END dialogflow_cx_create_page] diff --git a/dialogflow-cx/src/main/java/dialogflow/cx/CreateSimplePage.java b/dialogflow-cx/src/main/java/dialogflow/cx/CreateSimplePage.java new file mode 100644 index 00000000000..26b10e85422 --- /dev/null +++ b/dialogflow-cx/src/main/java/dialogflow/cx/CreateSimplePage.java @@ -0,0 +1,72 @@ +/* + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package dialogflow.cx; + +// [START dialogflow_cx_create_page] +import com.google.cloud.dialogflow.cx.v3.CreatePageRequest; +import com.google.cloud.dialogflow.cx.v3.Page; +import com.google.cloud.dialogflow.cx.v3.PagesClient; +import java.io.IOException; + +public class CreateSimplePage { + + public static void main(String[] args) throws IOException { + // TODO(developer): Replace these variables before running the sample. + String projectId = "my-project-id"; + String agentId = "my-agent-id"; + String flowId = "my-flow-id"; + String location = "my-location"; + String displayName = "my-display-name"; + + createPage(projectId, agentId, flowId, location, displayName); + } + + // DialogFlow API Create Page Sample. + // Creates a page from the provided parameters + public static Page createPage( + String projectId, String agentId, String flowId, String location, String displayName) + throws IOException { + Page response; + CreatePageRequest.Builder createRequestBuilder = CreatePageRequest.newBuilder(); + Page.Builder pageBuilder = Page.newBuilder(); + + pageBuilder.setDisplayName(displayName); + + createRequestBuilder + .setParent( + "projects/" + + projectId + + "/locations/" + + location + + "/agents/" + + agentId + + "/flows/" + + flowId) + .setPage(pageBuilder); + + // Make API request to create page + // Note: close() needs to be called on the PagesClient object to clean up resources + // such as threads. In the example below, try-with-resources is used, + // which automatically calls close(). + try (PagesClient client = PagesClient.create()) { + response = client.createPage(createRequestBuilder.build()); + System.out.println("Successfully created page!"); + return response; + } + } + // [END dialogflow_cx_create_page] +} diff --git a/dialogflow-cx/src/main/java/dialogflow/cx/DeletePage.java b/dialogflow-cx/src/main/java/dialogflow/cx/DeletePage.java new file mode 100644 index 00000000000..8403a690a99 --- /dev/null +++ b/dialogflow-cx/src/main/java/dialogflow/cx/DeletePage.java @@ -0,0 +1,68 @@ +/* + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package dialogflow.cx; + +// [START dialogflow_cx_delete_page] +import com.google.cloud.dialogflow.cx.v3.DeletePageRequest; +import com.google.cloud.dialogflow.cx.v3.DeletePageRequest.Builder; +import com.google.cloud.dialogflow.cx.v3.PagesClient; +import java.io.IOException; + +public class DeletePage { + + public static void main(String[] args) throws IOException { + // TODO(developer): Replace these variables before running the sample. + String projectId = "my-project-id"; + String agentId = "my-agent-id"; + String flowId = "my-flow-id"; + String pageId = "my-page-id"; + String location = "my-location"; + + deletePage(projectId, agentId, flowId, pageId, location); + } + + // DialogFlow API Delete Page Sample. + // Deletes a page from the provided parameters + public static void deletePage( + String projectId, String agentId, String flowId, String pageId, String location) + throws IOException { + + // Note: close() needs to be called on the PagesClient object to clean up resources + // such as threads. In the example below, try-with-resources is used, + // which automatically calls close(). + try (PagesClient client = PagesClient.create()) { + Builder deleteRequestBuilder = DeletePageRequest.newBuilder(); + + deleteRequestBuilder.setName( + "projects/" + + projectId + + "/locations/" + + location + + "/agents/" + + agentId + + "/flows/" + + flowId + + "/pages/" + + pageId); + + // Make API request to delete page + client.deletePage(deleteRequestBuilder.build()); + System.out.println("Successfully deleted page!"); + } + } + // [END dialogflow_cx_delete_page] +} diff --git a/dialogflow-cx/src/main/java/dialogflow/cx/DetectIntent.java b/dialogflow-cx/src/main/java/dialogflow/cx/DetectIntent.java new file mode 100644 index 00000000000..3109a4fc5a8 --- /dev/null +++ b/dialogflow-cx/src/main/java/dialogflow/cx/DetectIntent.java @@ -0,0 +1,105 @@ +/* + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package dialogflow.cx; + +// [START dialogflow_cx_detect_intent_text] + +import com.google.api.gax.rpc.ApiException; +import com.google.cloud.dialogflow.cx.v3beta1.DetectIntentRequest; +import com.google.cloud.dialogflow.cx.v3beta1.DetectIntentResponse; +import com.google.cloud.dialogflow.cx.v3beta1.QueryInput; +import com.google.cloud.dialogflow.cx.v3beta1.QueryResult; +import com.google.cloud.dialogflow.cx.v3beta1.SessionName; +import com.google.cloud.dialogflow.cx.v3beta1.SessionsClient; +import com.google.cloud.dialogflow.cx.v3beta1.SessionsSettings; +import com.google.cloud.dialogflow.cx.v3beta1.TextInput; +import com.google.common.collect.Maps; +import java.io.IOException; +import java.util.List; +import java.util.Map; + +public class DetectIntent { + + // DialogFlow API Detect Intent sample with text inputs. + public static Map detectIntent( + String projectId, + String locationId, + String agentId, + String sessionId, + List texts, + String languageCode) + throws IOException, ApiException { + SessionsSettings.Builder sessionsSettingsBuilder = SessionsSettings.newBuilder(); + if (locationId.equals("global")) { + sessionsSettingsBuilder.setEndpoint("dialogflow.googleapis.com:443"); + } else { + sessionsSettingsBuilder.setEndpoint(locationId + "-dialogflow.googleapis.com:443"); + } + SessionsSettings sessionsSettings = sessionsSettingsBuilder.build(); + + Map queryResults = Maps.newHashMap(); + // Instantiates a client. + + // Note: close() needs to be called on the SessionsClient object to clean up resources + // such as threads. In the example below, try-with-resources is used, + // which automatically calls close(). + try (SessionsClient sessionsClient = SessionsClient.create(sessionsSettings)) { + // Set the session name using the projectID (my-project-id), locationID (global), agentID + // (UUID), and sessionId (UUID). + SessionName session = + SessionName.ofProjectLocationAgentSessionName(projectId, locationId, agentId, sessionId); + + // TODO : Uncomment if you want to print session path + // System.out.println("Session Path: " + session.toString()); + + // Detect intents for each text input. + for (String text : texts) { + // Set the text (hello) for the query. + TextInput.Builder textInput = TextInput.newBuilder().setText(text); + + // Build the query with the TextInput and language code (en-US). + QueryInput queryInput = + QueryInput.newBuilder().setText(textInput).setLanguageCode(languageCode).build(); + + // Build the DetectIntentRequest with the SessionName and QueryInput. + DetectIntentRequest request = + DetectIntentRequest.newBuilder() + .setSession(session.toString()) + .setQueryInput(queryInput) + .build(); + + // Performs the detect intent request. + DetectIntentResponse response = sessionsClient.detectIntent(request); + + // Display the query result. + QueryResult queryResult = response.getQueryResult(); + + // TODO : Uncomment if you want to print queryResult + // System.out.println("===================="); + // System.out.format("Query Text: '%s'\n", queryResult.getText()); + // System.out.format( + // "Detected Intent: %s (confidence: %f)\n", + // queryResult.getIntent().getDisplayName(), + // queryResult.getIntentDetectionConfidence()); + + queryResults.put(text, queryResult); + } + } + return queryResults; + } +} +// [END dialogflow_cx_detect_intent_text] diff --git a/dialogflow-cx/src/main/java/dialogflow/cx/DetectIntentAudioInput.java b/dialogflow-cx/src/main/java/dialogflow/cx/DetectIntentAudioInput.java new file mode 100644 index 00000000000..36a6a17c727 --- /dev/null +++ b/dialogflow-cx/src/main/java/dialogflow/cx/DetectIntentAudioInput.java @@ -0,0 +1,132 @@ +/* + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package dialogflow.cx; + +// [START dialogflow_cx_v3_detect_intent_audio_input] + +import com.google.api.gax.rpc.ApiException; +import com.google.cloud.dialogflow.cx.v3.AudioEncoding; +import com.google.cloud.dialogflow.cx.v3.AudioInput; +import com.google.cloud.dialogflow.cx.v3.DetectIntentRequest; +import com.google.cloud.dialogflow.cx.v3.DetectIntentResponse; +import com.google.cloud.dialogflow.cx.v3.InputAudioConfig; +import com.google.cloud.dialogflow.cx.v3.QueryInput; +import com.google.cloud.dialogflow.cx.v3.QueryResult; +import com.google.cloud.dialogflow.cx.v3.SessionName; +import com.google.cloud.dialogflow.cx.v3.SessionsClient; +import com.google.cloud.dialogflow.cx.v3.SessionsSettings; +import com.google.protobuf.ByteString; +import java.io.FileInputStream; +import java.io.IOException; + +public class DetectIntentAudioInput { + + // DialogFlow API Detect Intent sample with Audio input. + public static void main(String[] args) throws IOException, ApiException { + /** TODO (developer): replace these values with your own values */ + String projectId = "my-project-id"; + String locationId = "global"; + String agentId = "my-agent-id"; + String audioFileName = "resources/book_a_room.wav"; + int sampleRateHertz = 16000; + /* + * A session ID is a string of at most 36 bytes in size. + * Your system is responsible for generating unique session IDs. + * They can be random numbers, hashed end-user identifiers, + * or any other values that are convenient for you to generate. + */ + String sessionId = "my-UUID"; + String languageCode = "en"; + + detectIntent( + projectId, locationId, agentId, audioFileName, sampleRateHertz, sessionId, languageCode); + } + + public static void detectIntent( + String projectId, + String locationId, + String agentId, + String audioFileName, + int sampleRateHertz, + String sessionId, + String languageCode) + throws IOException, ApiException { + + SessionsSettings.Builder sessionsSettingsBuilder = SessionsSettings.newBuilder(); + if (locationId.equals("global")) { + sessionsSettingsBuilder.setEndpoint("dialogflow.googleapis.com:443"); + } else { + sessionsSettingsBuilder.setEndpoint(locationId + "-dialogflow.googleapis.com:443"); + } + SessionsSettings sessionsSettings = sessionsSettingsBuilder.build(); + + // Instantiates a client by setting the session name. + // Format:`projects//locations//agents//sessions/` + + // Note: close() needs to be called on the SessionsClient object to clean up resources + // such as threads. In the example below, try-with-resources is used, + // which automatically calls close(). + try (SessionsClient sessionsClient = SessionsClient.create(sessionsSettings)) { + SessionName session = + SessionName.ofProjectLocationAgentSessionName(projectId, locationId, agentId, sessionId); + + // TODO : Uncomment if you want to print session path + // System.out.println("Session Path: " + session.toString()); + InputAudioConfig inputAudioConfig = + InputAudioConfig.newBuilder() + .setAudioEncoding(AudioEncoding.AUDIO_ENCODING_LINEAR_16) + .setSampleRateHertz(sampleRateHertz) + .build(); + + try (FileInputStream audioStream = new FileInputStream(audioFileName)) { + // Subsequent requests must **only** contain the audio data. + // Following messages: audio chunks. We just read the file in fixed-size chunks. In reality + // you would split the user input by time. + byte[] buffer = new byte[4096]; + int bytes = audioStream.read(buffer); + AudioInput audioInput = + AudioInput.newBuilder() + .setAudio(ByteString.copyFrom(buffer, 0, bytes)) + .setConfig(inputAudioConfig) + .build(); + QueryInput queryInput = + QueryInput.newBuilder() + .setAudio(audioInput) + .setLanguageCode("en-US") // languageCode = "en-US" + .build(); + + DetectIntentRequest request = + DetectIntentRequest.newBuilder() + .setSession(session.toString()) + .setQueryInput(queryInput) + .build(); + + // Performs the detect intent request. + DetectIntentResponse response = sessionsClient.detectIntent(request); + + // Display the query result. + QueryResult queryResult = response.getQueryResult(); + + System.out.println("===================="); + System.out.format( + "Detected Intent: %s (confidence: %f)\n", + queryResult.getTranscript(), queryResult.getIntentDetectionConfidence()); + } + } + } +} +// [END dialogflow_cx_v3_detect_intent_audio_input] diff --git a/dialogflow-cx/src/main/java/dialogflow/cx/DetectIntentDisableWebhook.java b/dialogflow-cx/src/main/java/dialogflow/cx/DetectIntentDisableWebhook.java new file mode 100644 index 00000000000..ee97aabdab9 --- /dev/null +++ b/dialogflow-cx/src/main/java/dialogflow/cx/DetectIntentDisableWebhook.java @@ -0,0 +1,124 @@ +/* + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package dialogflow.cx; + +// [START dialogflow_cx_v3_detect_intent_disable_webhook] + +import com.google.api.gax.rpc.ApiException; +import com.google.cloud.dialogflow.cx.v3.DetectIntentRequest; +import com.google.cloud.dialogflow.cx.v3.DetectIntentResponse; +import com.google.cloud.dialogflow.cx.v3.QueryInput; +import com.google.cloud.dialogflow.cx.v3.QueryParameters; +import com.google.cloud.dialogflow.cx.v3.QueryResult; +import com.google.cloud.dialogflow.cx.v3.SessionName; +import com.google.cloud.dialogflow.cx.v3.SessionsClient; +import com.google.cloud.dialogflow.cx.v3.SessionsSettings; +import com.google.cloud.dialogflow.cx.v3.TextInput; +import com.google.common.collect.Maps; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +public class DetectIntentDisableWebhook { + + public static void main(String[] args) throws IOException, ApiException { + String projectId = "my-project-id"; + String locationId = "global"; + String agentId = "my-agent-id"; + String sessionId = "my-UUID"; + List texts = new ArrayList<>(List.of("my-list", "of-texts")); + String languageCode = "en"; + + detectIntent(projectId, locationId, agentId, sessionId, texts, languageCode); + } + + // DialogFlow API Detect Intent sample with webhook disabled. + public static Map detectIntent( + String projectId, + String locationId, + String agentId, + String sessionId, + List texts, + String languageCode) + throws IOException, ApiException { + SessionsSettings.Builder sessionsSettingsBuilder = SessionsSettings.newBuilder(); + if (locationId.equals("global")) { + sessionsSettingsBuilder.setEndpoint("dialogflow.googleapis.com:443"); + } else { + sessionsSettingsBuilder.setEndpoint(locationId + "-dialogflow.googleapis.com:443"); + } + SessionsSettings sessionsSettings = sessionsSettingsBuilder.build(); + + Map queryResults = Maps.newHashMap(); + + // Instantiates a client by setting the session name. + // Format:`projects//locations//agents//sessions/` + + // Note: close() needs to be called on the SessionsClient object to clean up resources + // such as threads. In the example below, try-with-resources is used, + // which automatically calls close(). + try (SessionsClient sessionsClient = SessionsClient.create(sessionsSettings)) { + SessionName session = + SessionName.ofProjectLocationAgentSessionName(projectId, locationId, agentId, sessionId); + + // TODO : Uncomment if you want to print session path + // System.out.println("Session Path: " + session.toString()); + + // Detect intents for each text input. + for (String text : texts) { + // Set the text (hello) for the query. + TextInput.Builder textInput = TextInput.newBuilder().setText(text); + + // Build the query with the TextInput and language code (en-US). + QueryInput queryInput = + QueryInput.newBuilder().setText(textInput).setLanguageCode(languageCode).build(); + + // Build the query parameters and setDisableWebhook to true. + QueryParameters queryParameters = + QueryParameters.newBuilder().setDisableWebhook(true).build(); + + // Build the DetectIntentRequest with the SessionName, QueryInput, and QueryParameters. + DetectIntentRequest request = + DetectIntentRequest.newBuilder() + .setSession(session.toString()) + .setQueryInput(queryInput) + .setQueryParams(queryParameters) + .build(); + System.out.println(request.toString()); + + // Performs the detect intent request. + DetectIntentResponse response = sessionsClient.detectIntent(request); + + // Display the query result. + QueryResult queryResult = response.getQueryResult(); + + // TODO : Uncomment if you want to print queryResult + // System.out.println("===================="); + // System.out.format("Query Text: '%s'\n", queryResult.getText()); + // System.out.format( + // "Detected Intent: %s (confidence: %f)\n", + // queryResult.getIntent().getDisplayName(), + // queryResult.getIntentDetectionConfidence()); + + queryResults.put(text, queryResult); + } + } + return queryResults; + } +} +// [END dialogflow_cx_v3_detect_intent_disable_webhook] diff --git a/dialogflow-cx/src/main/java/dialogflow/cx/DetectIntentEventInput.java b/dialogflow-cx/src/main/java/dialogflow/cx/DetectIntentEventInput.java new file mode 100644 index 00000000000..ccd1fe3430c --- /dev/null +++ b/dialogflow-cx/src/main/java/dialogflow/cx/DetectIntentEventInput.java @@ -0,0 +1,102 @@ +/* + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package dialogflow.cx; + +// [START dialogflow_cx_v3_detect_intent_event_input] + +import com.google.api.gax.rpc.ApiException; +import com.google.cloud.dialogflow.cx.v3.DetectIntentRequest; +import com.google.cloud.dialogflow.cx.v3.DetectIntentResponse; +import com.google.cloud.dialogflow.cx.v3.EventInput; +import com.google.cloud.dialogflow.cx.v3.QueryInput; +import com.google.cloud.dialogflow.cx.v3.QueryResult; +import com.google.cloud.dialogflow.cx.v3.SessionName; +import com.google.cloud.dialogflow.cx.v3.SessionsClient; +import com.google.cloud.dialogflow.cx.v3.SessionsSettings; +import java.io.IOException; + +public class DetectIntentEventInput { + + // DialogFlow API Detect Intent sample with Event input. + public static void main(String[] args) throws IOException, ApiException { + String projectId = "my-project-id"; + String locationId = "global"; + String agentId = "my-agent-id"; + String sessionId = "my-UUID"; + String event = "my-event-id"; + String languageCode = "en"; + + detectIntent(projectId, locationId, agentId, sessionId, event, languageCode); + } + + public static void detectIntent( + String projectId, + String locationId, + String agentId, + String sessionId, + String event, + String languageCode) + throws IOException, ApiException { + + SessionsSettings.Builder sessionsSettingsBuilder = SessionsSettings.newBuilder(); + if (locationId.equals("global")) { + sessionsSettingsBuilder.setEndpoint("dialogflow.googleapis.com:443"); + } else { + sessionsSettingsBuilder.setEndpoint(locationId + "-dialogflow.googleapis.com:443"); + } + SessionsSettings sessionsSettings = sessionsSettingsBuilder.build(); + + // Instantiates a client by setting the session name. + // Format:`projects//locations//agents//sessions/` + + // Note: close() needs to be called on the SessionsClient object to clean up resources + // such as threads. In the example below, try-with-resources is used, + // which automatically calls close(). + try (SessionsClient sessionsClient = SessionsClient.create(sessionsSettings)) { + SessionName session = + SessionName.ofProjectLocationAgentSessionName(projectId, locationId, agentId, sessionId); + + // TODO : Uncomment if you want to print session path + // System.out.println("Session Path: " + session.toString()); + + EventInput.Builder eventInput = EventInput.newBuilder().setEvent(event); + + // Build the query with the EventInput and language code (en-US). + QueryInput queryInput = + QueryInput.newBuilder().setEvent(eventInput).setLanguageCode(languageCode).build(); + + // Build the DetectIntentRequest with the SessionName and QueryInput. + DetectIntentRequest request = + DetectIntentRequest.newBuilder() + .setSession(session.toString()) + .setQueryInput(queryInput) + .build(); + + // Performs the detect intent request. + DetectIntentResponse response = sessionsClient.detectIntent(request); + + // Display the query result. + QueryResult queryResult = response.getQueryResult(); + + // TODO : Uncomment if you want to print queryResult + System.out.println("===================="); + System.out.format("Triggering Event: %s \n", queryResult.getTriggerEvent()); + } + } +} + +// [END dialogflow_cx_v3_detect_intent_event_input] diff --git a/dialogflow-cx/src/main/java/dialogflow/cx/DetectIntentIntentInput.java b/dialogflow-cx/src/main/java/dialogflow/cx/DetectIntentIntentInput.java new file mode 100644 index 00000000000..a0e89547db6 --- /dev/null +++ b/dialogflow-cx/src/main/java/dialogflow/cx/DetectIntentIntentInput.java @@ -0,0 +1,104 @@ +/* + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package dialogflow.cx; + +// [START dialogflow_cx_v3_detect_intent_intent_input] + +import com.google.api.gax.rpc.ApiException; +import com.google.cloud.dialogflow.cx.v3.DetectIntentRequest; +import com.google.cloud.dialogflow.cx.v3.DetectIntentResponse; +import com.google.cloud.dialogflow.cx.v3.IntentInput; +import com.google.cloud.dialogflow.cx.v3.QueryInput; +import com.google.cloud.dialogflow.cx.v3.QueryResult; +import com.google.cloud.dialogflow.cx.v3.SessionName; +import com.google.cloud.dialogflow.cx.v3.SessionsClient; +import com.google.cloud.dialogflow.cx.v3.SessionsSettings; +import java.io.IOException; + +public class DetectIntentIntentInput { + + // DialogFlow API Detect Intent sample with Intent input. + public static void main(String[] args) throws IOException, ApiException { + String projectId = "my-project-id"; + String locationId = "global"; + String agentId = "my-agent-id"; + String sessionId = "my-UUID"; + String intent = "my-intent-id"; + String languageCode = "en"; + + detectIntent(projectId, locationId, agentId, sessionId, intent, languageCode); + } + + public static void detectIntent( + String projectId, + String locationId, + String agentId, + String sessionId, + String intent, + String languageCode) + throws IOException, ApiException { + + SessionsSettings.Builder sessionsSettingsBuilder = SessionsSettings.newBuilder(); + if (locationId.equals("global")) { + sessionsSettingsBuilder.setEndpoint("dialogflow.googleapis.com:443"); + } else { + sessionsSettingsBuilder.setEndpoint(locationId + "-dialogflow.googleapis.com:443"); + } + SessionsSettings sessionsSettings = sessionsSettingsBuilder.build(); + + // Instantiates a client by setting the session name. + // Format:`projects//locations//agents//sessions/` + + // Note: close() needs to be called on the SessionsClient object to clean up resources + // such as threads. In the example below, try-with-resources is used, + // which automatically calls close(). + try (SessionsClient sessionsClient = SessionsClient.create(sessionsSettings)) { + SessionName session = + SessionName.ofProjectLocationAgentSessionName(projectId, locationId, agentId, sessionId); + + // TODO : Uncomment if you want to print session path + // System.out.println("Session Path: " + session.toString()); + + IntentInput.Builder intentInput = IntentInput.newBuilder().setIntent(intent); + + // Build the query with the IntentInput and language code (en-US). + QueryInput queryInput = + QueryInput.newBuilder().setIntent(intentInput).setLanguageCode(languageCode).build(); + + // Build the DetectIntentRequest with the SessionName and QueryInput. + DetectIntentRequest request = + DetectIntentRequest.newBuilder() + .setSession(session.toString()) + .setQueryInput(queryInput) + .build(); + + // Performs the detect intent request. + DetectIntentResponse response = sessionsClient.detectIntent(request); + + // Display the query result. + QueryResult queryResult = response.getQueryResult(); + + // TODO : Uncomment if you want to print queryResult + System.out.println("===================="); + System.out.format( + "Detected Intent: %s (confidence: %f)\n", + queryResult.getIntent().getDisplayName(), queryResult.getIntentDetectionConfidence()); + } + } +} + +// [END dialogflow_cx_v3_detect_intent_intent_input] diff --git a/dialogflow-cx/src/main/java/dialogflow/cx/DetectIntentSentimentAnalysis.java b/dialogflow-cx/src/main/java/dialogflow/cx/DetectIntentSentimentAnalysis.java new file mode 100644 index 00000000000..f69331bbf29 --- /dev/null +++ b/dialogflow-cx/src/main/java/dialogflow/cx/DetectIntentSentimentAnalysis.java @@ -0,0 +1,121 @@ +/* + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package dialogflow.cx; + +// [START dialogflow_cx_v3_detect_intent_sentiment_analysis] + +import com.google.api.gax.rpc.ApiException; +import com.google.cloud.dialogflow.cx.v3.DetectIntentRequest; +import com.google.cloud.dialogflow.cx.v3.DetectIntentResponse; +import com.google.cloud.dialogflow.cx.v3.QueryInput; +import com.google.cloud.dialogflow.cx.v3.QueryParameters; +import com.google.cloud.dialogflow.cx.v3.QueryResult; +import com.google.cloud.dialogflow.cx.v3.SessionName; +import com.google.cloud.dialogflow.cx.v3.SessionsClient; +import com.google.cloud.dialogflow.cx.v3.SessionsSettings; +import com.google.cloud.dialogflow.cx.v3.TextInput; +import com.google.common.collect.Maps; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +public class DetectIntentSentimentAnalysis { + + public static void main(String[] args) throws IOException, ApiException { + String projectId = "my-project-id"; + String locationId = "global"; + String agentId = "my-agent-id"; + String sessionId = "my-UUID"; + List texts = new ArrayList<>(List.of("my-list", "of-texts")); + String languageCode = "en"; + + detectIntent(projectId, locationId, agentId, sessionId, texts, languageCode); + } + + // DialogFlow API Detect Intent sample with sentiment analysis. + public static Map detectIntent( + String projectId, + String locationId, + String agentId, + String sessionId, + List texts, + String languageCode) + throws IOException, ApiException { + SessionsSettings.Builder sessionsSettingsBuilder = SessionsSettings.newBuilder(); + if (locationId.equals("global")) { + sessionsSettingsBuilder.setEndpoint("dialogflow.googleapis.com:443"); + } else { + sessionsSettingsBuilder.setEndpoint(locationId + "-dialogflow.googleapis.com:443"); + } + SessionsSettings sessionsSettings = sessionsSettingsBuilder.build(); + + Map queryResults = Maps.newHashMap(); + + // Instantiates a client by setting the session name. + // Format:`projects//locations//agents//sessions/` + + // Note: close() needs to be called on the SessionsClient object to clean up resources + // such as threads. In the example below, try-with-resources is used, + // which automatically calls close(). + try (SessionsClient sessionsClient = SessionsClient.create(sessionsSettings)) { + SessionName session = + SessionName.ofProjectLocationAgentSessionName(projectId, locationId, agentId, sessionId); + + // TODO : Uncomment if you want to print session path + // System.out.println("Session Path: " + session.toString()); + + // Detect intents for each text input. + for (String text : texts) { + // Set the text (hello) for the query. + TextInput.Builder textInput = TextInput.newBuilder().setText(text); + + // Build the query with the TextInput and language code (en-US). + QueryInput queryInput = + QueryInput.newBuilder().setText(textInput).setLanguageCode(languageCode).build(); + + // Build the query parameters to analyze the sentiment of the query. + QueryParameters queryParameters = + QueryParameters.newBuilder().setAnalyzeQueryTextSentiment(true).build(); + + // Build the DetectIntentRequest with the SessionName, QueryInput, and QueryParameters. + DetectIntentRequest request = + DetectIntentRequest.newBuilder() + .setSession(session.toString()) + .setQueryInput(queryInput) + .setQueryParams(queryParameters) + .build(); + + // Performs the detect intent request. + DetectIntentResponse response = sessionsClient.detectIntent(request); + + // Display the query result. + QueryResult queryResult = response.getQueryResult(); + + // TODO : Uncomment if you want to print queryResult + // System.out.println("===================="); + // SentimentAnalysisResult sentimentAnalysisResult = + // queryResult.getSentimentAnalysisResult(); + // Float score = sentimentAnalysisResult.getScore(); + + queryResults.put(text, queryResult); + } + } + return queryResults; + } +} +// [END dialogflow_cx_v3_detect_intent_sentiment_analysis] diff --git a/dialogflow-cx/src/main/java/dialogflow/cx/DetectIntentStream.java b/dialogflow-cx/src/main/java/dialogflow/cx/DetectIntentStream.java new file mode 100644 index 00000000000..f1d05491e38 --- /dev/null +++ b/dialogflow-cx/src/main/java/dialogflow/cx/DetectIntentStream.java @@ -0,0 +1,151 @@ +/* + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package dialogflow.cx; + +// [START dialogflow_cx_detect_intent_streaming] + +import com.google.api.gax.rpc.ApiException; +import com.google.api.gax.rpc.BidiStream; +import com.google.cloud.dialogflow.cx.v3beta1.AudioEncoding; +import com.google.cloud.dialogflow.cx.v3beta1.AudioInput; +import com.google.cloud.dialogflow.cx.v3beta1.InputAudioConfig; +import com.google.cloud.dialogflow.cx.v3beta1.OutputAudioConfig; +import com.google.cloud.dialogflow.cx.v3beta1.OutputAudioEncoding; +import com.google.cloud.dialogflow.cx.v3beta1.QueryInput; +import com.google.cloud.dialogflow.cx.v3beta1.QueryResult; +import com.google.cloud.dialogflow.cx.v3beta1.SessionName; +import com.google.cloud.dialogflow.cx.v3beta1.SessionsClient; +import com.google.cloud.dialogflow.cx.v3beta1.SessionsSettings; +import com.google.cloud.dialogflow.cx.v3beta1.SsmlVoiceGender; +import com.google.cloud.dialogflow.cx.v3beta1.StreamingDetectIntentRequest; +import com.google.cloud.dialogflow.cx.v3beta1.StreamingDetectIntentResponse; +import com.google.cloud.dialogflow.cx.v3beta1.SynthesizeSpeechConfig; +import com.google.cloud.dialogflow.cx.v3beta1.VoiceSelectionParams; +import com.google.protobuf.ByteString; +import java.io.FileInputStream; +import java.io.IOException; + +public class DetectIntentStream { + + // DialogFlow API Detect Intent sample with audio files processes as an audio stream. + public static void detectIntentStream( + String projectId, String locationId, String agentId, String sessionId, String audioFilePath) + throws ApiException, IOException { + SessionsSettings.Builder sessionsSettingsBuilder = SessionsSettings.newBuilder(); + if (locationId.equals("global")) { + sessionsSettingsBuilder.setEndpoint("dialogflow.googleapis.com:443"); + } else { + sessionsSettingsBuilder.setEndpoint(locationId + "-dialogflow.googleapis.com:443"); + } + SessionsSettings sessionsSettings = sessionsSettingsBuilder.build(); + + // Instantiates a client by setting the session name. + // Format: `projects//locations//agents//sessions/` + // Using the same `sessionId` between requests allows continuation of the conversation. + + // Note: close() needs to be called on the SessionsClient object to clean up resources + // such as threads. In the example below, try-with-resources is used, + // which automatically calls close(). + try (SessionsClient sessionsClient = SessionsClient.create(sessionsSettings)) { + SessionName session = SessionName.of(projectId, locationId, agentId, sessionId); + + // Instructs the speech recognizer how to process the audio content. + // Note: hard coding audioEncoding and sampleRateHertz for simplicity. + // Audio encoding of the audio content sent in the query request. + InputAudioConfig inputAudioConfig = + InputAudioConfig.newBuilder() + .setAudioEncoding(AudioEncoding.AUDIO_ENCODING_LINEAR_16) + .setSampleRateHertz(16000) // sampleRateHertz = 16000 + .build(); + + // Build the AudioInput with the InputAudioConfig. + AudioInput audioInput = AudioInput.newBuilder().setConfig(inputAudioConfig).build(); + + // Build the query with the InputAudioConfig. + QueryInput queryInput = + QueryInput.newBuilder() + .setAudio(audioInput) + .setLanguageCode("en-US") // languageCode = "en-US" + .build(); + + // Create the Bidirectional stream + BidiStream bidiStream = + sessionsClient.streamingDetectIntentCallable().call(); + + // Specify sssml name and gender + VoiceSelectionParams voiceSelection = + // Voices that are available https://cloud.google.com/text-to-speech/docs/voices + VoiceSelectionParams.newBuilder() + .setName("en-GB-Standard-A") + .setSsmlGender(SsmlVoiceGender.SSML_VOICE_GENDER_FEMALE) + .build(); + + SynthesizeSpeechConfig speechConfig = + SynthesizeSpeechConfig.newBuilder().setVoice(voiceSelection).build(); + + // Setup audio config + OutputAudioConfig audioConfig = + // Output enconding explanation + // https://cloud.google.com/dialogflow/cx/docs/reference/rpc/google.cloud.dialogflow.cx.v3#outputaudioencoding + OutputAudioConfig.newBuilder() + .setAudioEncoding(OutputAudioEncoding.OUTPUT_AUDIO_ENCODING_UNSPECIFIED) + .setAudioEncodingValue(1) + .setSynthesizeSpeechConfig(speechConfig) + .build(); + + // The first request must **only** contain the audio configuration: + bidiStream.send( + StreamingDetectIntentRequest.newBuilder() + .setSession(session.toString()) + .setQueryInput(queryInput) + .setOutputAudioConfig(audioConfig) + .build()); + + try (FileInputStream audioStream = new FileInputStream(audioFilePath)) { + // Subsequent requests must **only** contain the audio data. + // Following messages: audio chunks. We just read the file in fixed-size chunks. In reality + // you would split the user input by time. + byte[] buffer = new byte[4096]; + int bytes; + while ((bytes = audioStream.read(buffer)) != -1) { + AudioInput subAudioInput = + AudioInput.newBuilder().setAudio(ByteString.copyFrom(buffer, 0, bytes)).build(); + QueryInput subQueryInput = + QueryInput.newBuilder() + .setAudio(subAudioInput) + .setLanguageCode("en-US") // languageCode = "en-US" + .build(); + bidiStream.send( + StreamingDetectIntentRequest.newBuilder().setQueryInput(subQueryInput).build()); + } + } + + // Tell the service you are done sending data. + bidiStream.closeSend(); + + for (StreamingDetectIntentResponse response : bidiStream) { + QueryResult queryResult = response.getDetectIntentResponse().getQueryResult(); + System.out.println("===================="); + System.out.format("Query Text: '%s'\n", queryResult.getTranscript()); + System.out.format( + "Detected Intent: %s (confidence: %f)\n", + queryResult.getIntent().getDisplayName(), queryResult.getIntentDetectionConfidence()); + } + } + } +} +// [END dialogflow_cx_detect_intent_streaming] diff --git a/dialogflow-cx/src/main/java/dialogflow/cx/DetectIntentStreamingPartialResponse.java b/dialogflow-cx/src/main/java/dialogflow/cx/DetectIntentStreamingPartialResponse.java new file mode 100644 index 00000000000..af725804366 --- /dev/null +++ b/dialogflow-cx/src/main/java/dialogflow/cx/DetectIntentStreamingPartialResponse.java @@ -0,0 +1,158 @@ +/* + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package dialogflow.cx; + +// [START dialogflow_cx_v3_detect_intent_streaming_partial_response] + +import com.google.api.gax.rpc.ApiException; +import com.google.api.gax.rpc.BidiStream; +import com.google.cloud.dialogflow.cx.v3.AudioEncoding; +import com.google.cloud.dialogflow.cx.v3.AudioInput; +import com.google.cloud.dialogflow.cx.v3.InputAudioConfig; +import com.google.cloud.dialogflow.cx.v3.OutputAudioConfig; +import com.google.cloud.dialogflow.cx.v3.OutputAudioEncoding; +import com.google.cloud.dialogflow.cx.v3.QueryInput; +import com.google.cloud.dialogflow.cx.v3.SessionName; +import com.google.cloud.dialogflow.cx.v3.SessionsClient; +import com.google.cloud.dialogflow.cx.v3.SessionsSettings; +import com.google.cloud.dialogflow.cx.v3.SsmlVoiceGender; +import com.google.cloud.dialogflow.cx.v3.StreamingDetectIntentRequest; +import com.google.cloud.dialogflow.cx.v3.StreamingDetectIntentResponse; +import com.google.cloud.dialogflow.cx.v3.SynthesizeSpeechConfig; +import com.google.cloud.dialogflow.cx.v3.VoiceSelectionParams; +import com.google.protobuf.ByteString; +import java.io.FileInputStream; +import java.io.IOException; + +public class DetectIntentStreamingPartialResponse { + + // DialogFlow API Detect Intent sample with audio files + // that processes as an audio stream. + public static void detectIntentStreamingPartialResponse( + String projectId, String locationId, String agentId, String sessionId, String audioFilePath) + throws ApiException, IOException { + SessionsSettings.Builder sessionsSettingsBuilder = SessionsSettings.newBuilder(); + if (locationId.equals("global")) { + sessionsSettingsBuilder.setEndpoint("dialogflow.googleapis.com:443"); + } else { + sessionsSettingsBuilder.setEndpoint(locationId + "-dialogflow.googleapis.com:443"); + } + SessionsSettings sessionsSettings = sessionsSettingsBuilder.build(); + + // Instantiates a client by setting the session name. + // Format:`projects//locations//agents//sessions/` + // Using the same `sessionId` between requests allows continuation of the conversation. + + // Note: close() needs to be called on the SessionsClient object to clean up resources + // such as threads. In the example below, try-with-resources is used, + // which automatically calls close(). + try (SessionsClient sessionsClient = SessionsClient.create(sessionsSettings)) { + SessionName session = SessionName.of(projectId, locationId, agentId, sessionId); + + // Instructs the speech recognizer how to process the audio content. + // Note: hard coding audioEncoding and sampleRateHertz for simplicity. + // Audio encoding of the audio content sent in the query request. + InputAudioConfig inputAudioConfig = + InputAudioConfig.newBuilder() + .setAudioEncoding(AudioEncoding.AUDIO_ENCODING_LINEAR_16) + .setSampleRateHertz(16000) // sampleRateHertz = 16000 + .build(); + + // Build the AudioInput with the InputAudioConfig. + AudioInput audioInput = AudioInput.newBuilder().setConfig(inputAudioConfig).build(); + + // Build the query with the InputAudioConfig. + QueryInput queryInput = + QueryInput.newBuilder() + .setAudio(audioInput) + .setLanguageCode("en-US") // languageCode = "en-US" + .build(); + + // Create the Bidirectional stream + BidiStream bidiStream = + sessionsClient.streamingDetectIntentCallable().call(); + + // Specify sssml name and gender + VoiceSelectionParams voiceSelection = + // Voices that are available https://cloud.google.com/text-to-speech/docs/voices + VoiceSelectionParams.newBuilder() + .setName("en-GB-Standard-A") + .setSsmlGender(SsmlVoiceGender.SSML_VOICE_GENDER_FEMALE) + .build(); + + SynthesizeSpeechConfig speechConfig = + SynthesizeSpeechConfig.newBuilder().setVoice(voiceSelection).build(); + + // Setup audio config + OutputAudioConfig audioConfig = + // Output encoding explanation + // https://cloud.google.com/dialogflow/cx/docs/reference/rpc/google.cloud.dialogflow.cx.v3#outputaudioencoding + OutputAudioConfig.newBuilder() + .setAudioEncoding(OutputAudioEncoding.OUTPUT_AUDIO_ENCODING_UNSPECIFIED) + .setAudioEncodingValue(1) + .setSynthesizeSpeechConfig(speechConfig) + .build(); + + StreamingDetectIntentRequest streamingDetectIntentRequest = + StreamingDetectIntentRequest.newBuilder() + .setSession(session.toString()) + .setQueryInput(queryInput) + .setEnablePartialResponse(true) + .setOutputAudioConfig(audioConfig) + .build(); + System.out.println(streamingDetectIntentRequest.toString()); + + // The first request must **only** contain the audio configuration: + bidiStream.send(streamingDetectIntentRequest); + + try (FileInputStream audioStream = new FileInputStream(audioFilePath)) { + // Subsequent requests must **only** contain the audio data. + // Following messages: audio chunks. We just read the file in fixed-size chunks. In reality + // you would split the user input by time. + byte[] buffer = new byte[4096]; + int bytes; + while ((bytes = audioStream.read(buffer)) != -1) { + AudioInput subAudioInput = + AudioInput.newBuilder().setAudio(ByteString.copyFrom(buffer, 0, bytes)).build(); + QueryInput subQueryInput = + QueryInput.newBuilder() + .setAudio(subAudioInput) + .setLanguageCode("en-US") // languageCode = "en-US" + .build(); + bidiStream.send( + StreamingDetectIntentRequest.newBuilder().setQueryInput(subQueryInput).build()); + } + } + + // Tell the service you are done sending data. + bidiStream.closeSend(); + + // TODO: Uncomment to print detectIntentResponse. + + // for (StreamingDetectIntentResponse response : bidiStream) { + // QueryResult queryResult = response.getDetectIntentResponse().getQueryResult(); + // System.out.println("===================="); + // System.out.format("Query Text: '%s'\n", queryResult.getTranscript()); + // System.out.format( + // "Detected Intent: %s (confidence: %f)\n", + // queryResult.getIntent() + // .getDisplayName(), queryResult.getIntentDetectionConfidence()); + // } + } + } +} +// [END dialogflow_cx_v3_detect_intent_streaming_partial_response] diff --git a/dialogflow-cx/src/main/java/dialogflow/cx/DetectIntentSynthesizeTextToSpeechOutput.java b/dialogflow-cx/src/main/java/dialogflow/cx/DetectIntentSynthesizeTextToSpeechOutput.java new file mode 100644 index 00000000000..74c155f4d0b --- /dev/null +++ b/dialogflow-cx/src/main/java/dialogflow/cx/DetectIntentSynthesizeTextToSpeechOutput.java @@ -0,0 +1,135 @@ +/* + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package dialogflow.cx; + +// [START dialogflow_cx_v3_detect_intent_synthesize_tts_output] + +import com.google.api.gax.rpc.ApiException; +import com.google.cloud.dialogflow.cx.v3.AudioEncoding; +import com.google.cloud.dialogflow.cx.v3.AudioInput; +import com.google.cloud.dialogflow.cx.v3.DetectIntentRequest; +import com.google.cloud.dialogflow.cx.v3.DetectIntentResponse; +import com.google.cloud.dialogflow.cx.v3.InputAudioConfig; +import com.google.cloud.dialogflow.cx.v3.OutputAudioConfig; +import com.google.cloud.dialogflow.cx.v3.OutputAudioEncoding; +import com.google.cloud.dialogflow.cx.v3.QueryInput; +import com.google.cloud.dialogflow.cx.v3.SessionName; +import com.google.cloud.dialogflow.cx.v3.SessionsClient; +import com.google.cloud.dialogflow.cx.v3.SessionsSettings; +import com.google.cloud.dialogflow.cx.v3.SynthesizeSpeechConfig; +import com.google.protobuf.ByteString; +import java.io.FileInputStream; +import java.io.IOException; + +public class DetectIntentSynthesizeTextToSpeechOutput { + + // DialogFlow API Detect Intent sample with synthesize TTS output. + public static void main(String[] args) throws IOException, ApiException { + String projectId = "my-project-id"; + String locationId = "my-location-id"; + String agentId = "my-agent-id"; + String audioFileName = "my-audio-file-name"; + int sampleRateHertz = 16000; + String sessionId = "my-session-id"; + String languageCode = "my-language-code"; + + detectIntent( + projectId, locationId, agentId, audioFileName, sampleRateHertz, sessionId, languageCode); + } + + public static void detectIntent( + String projectId, + String locationId, + String agentId, + String audioFileName, + int sampleRateHertz, + String sessionId, + String languageCode) + throws IOException, ApiException { + + SessionsSettings.Builder sessionsSettingsBuilder = SessionsSettings.newBuilder(); + if (locationId.equals("global")) { + sessionsSettingsBuilder.setEndpoint("dialogflow.googleapis.com:443"); + } else { + sessionsSettingsBuilder.setEndpoint(locationId + "-dialogflow.googleapis.com:443"); + } + SessionsSettings sessionsSettings = sessionsSettingsBuilder.build(); + + // Instantiates a client by setting the session name. + // Format:`projects//locations//agents//sessions/` + + // Note: close() needs to be called on the SessionsClient object to clean up resources + // such as threads. In the example below, try-with-resources is used, + // which automatically calls close(). + try (SessionsClient sessionsClient = SessionsClient.create(sessionsSettings)) { + SessionName session = + SessionName.ofProjectLocationAgentSessionName(projectId, locationId, agentId, sessionId); + + // TODO : Uncomment if you want to print session path + // System.out.println("Session Path: " + session.toString()); + InputAudioConfig inputAudioConfig = + InputAudioConfig.newBuilder() + .setAudioEncoding(AudioEncoding.AUDIO_ENCODING_LINEAR_16) + .setSampleRateHertz(sampleRateHertz) + .build(); + + try (FileInputStream audioStream = new FileInputStream(audioFileName)) { + // Subsequent requests must **only** contain the audio data. + // Following messages: audio chunks. We just read the file in fixed-size chunks. In reality + // you would split the user input by time. + byte[] buffer = new byte[4096]; + int bytes = audioStream.read(buffer); + AudioInput audioInput = + AudioInput.newBuilder() + .setAudio(ByteString.copyFrom(buffer, 0, bytes)) + .setConfig(inputAudioConfig) + .build(); + QueryInput queryInput = + QueryInput.newBuilder() + .setAudio(audioInput) + .setLanguageCode("en-US") // languageCode = "en-US" + .build(); + + SynthesizeSpeechConfig speechConfig = + SynthesizeSpeechConfig.newBuilder().setSpeakingRate(1.25).setPitch(10.0).build(); + + OutputAudioConfig outputAudioConfig = + OutputAudioConfig.newBuilder() + .setAudioEncoding(OutputAudioEncoding.OUTPUT_AUDIO_ENCODING_LINEAR_16) + .setSynthesizeSpeechConfig(speechConfig) + .build(); + + DetectIntentRequest request = + DetectIntentRequest.newBuilder() + .setSession(session.toString()) + .setQueryInput(queryInput) + .setOutputAudioConfig(outputAudioConfig) + .build(); + + // Performs the detect intent request. + DetectIntentResponse response = sessionsClient.detectIntent(request); + + // Display the output audio config retrieved from the response. + OutputAudioConfig audioConfigFromResponse = response.getOutputAudioConfig(); + + System.out.println("===================="); + System.out.format("Output Audio Config: %s \n", audioConfigFromResponse.toString()); + } + } + } +} +// [END dialogflow_cx_v3_detect_intent_synthesize_tts_output] diff --git a/dialogflow-cx/src/main/java/dialogflow/cx/ExportAgent.java b/dialogflow-cx/src/main/java/dialogflow/cx/ExportAgent.java new file mode 100644 index 00000000000..6b431f5108c --- /dev/null +++ b/dialogflow-cx/src/main/java/dialogflow/cx/ExportAgent.java @@ -0,0 +1,69 @@ +/* + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package dialogflow.cx; + +// [START dialogflow_cx_export_agent] + +import com.google.api.gax.longrunning.OperationFuture; +import com.google.cloud.dialogflow.cx.v3.AgentName; +import com.google.cloud.dialogflow.cx.v3.AgentsClient; +import com.google.cloud.dialogflow.cx.v3.AgentsSettings; +import com.google.cloud.dialogflow.cx.v3.ExportAgentRequest; +import com.google.cloud.dialogflow.cx.v3.ExportAgentResponse; +import com.google.protobuf.Struct; +import java.io.IOException; +import java.util.concurrent.ExecutionException; + +public class ExportAgent { + + public static void main(String[] args) + throws IOException, InterruptedException, ExecutionException { + // TODO(developer): Replace these variables before running the sample. + String projectId = "my-project-id"; + String agentId = "my-agent-id"; + String location = "my-location"; + + exportAgent(projectId, agentId, location); + } + + public static void exportAgent(String projectId, String agentId, String location) + throws IOException, InterruptedException, ExecutionException { + + // Sets the api endpoint to specified location + String apiEndpoint = String.format("%s-dialogflow.googleapis.com:443", location); + + AgentsSettings agentsSettings = AgentsSettings.newBuilder().setEndpoint(apiEndpoint).build(); + // Note: close() needs to be called on the AgentsClient object to clean up resources + // such as threads. In the example below, try-with-resources is used, + // which automatically calls close(). + try (AgentsClient agentsClient = AgentsClient.create(agentsSettings)) { + ExportAgentRequest request = + ExportAgentRequest.newBuilder() + .setName(AgentName.of(projectId, location, agentId).toString()) + .build(); + + // Returns a future of the operation + OperationFuture future = + agentsClient.exportAgentOperationCallable().futureCall(request); + + // get the export agent response after the operation is completed + ExportAgentResponse response = future.get(); + System.out.println(response); + } + } +} +// [END dialogflow_cx_export_agent] diff --git a/dialogflow-cx/src/main/java/dialogflow/cx/ListPages.java b/dialogflow-cx/src/main/java/dialogflow/cx/ListPages.java new file mode 100644 index 00000000000..9a180081f67 --- /dev/null +++ b/dialogflow-cx/src/main/java/dialogflow/cx/ListPages.java @@ -0,0 +1,61 @@ +/* + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package dialogflow.cx; + +// [START dialogflow_cx_list_pages] +import com.google.cloud.dialogflow.cx.v3.ListPagesRequest; +import com.google.cloud.dialogflow.cx.v3.ListPagesRequest.Builder; +import com.google.cloud.dialogflow.cx.v3.Page; +import com.google.cloud.dialogflow.cx.v3.PagesClient; +import java.io.IOException; + +public class ListPages { + + public static void main(String[] args) throws IOException { + // TODO(developer): Replace these variables before running the sample. + String projectId = "my-project-id"; + String agentId = "my-agent-id"; + String flowId = "my-flow-id"; + String location = "my-location"; + + listPages(projectId, agentId, flowId, location); + } + + // DialogFlow API List Pages Sample. + // Lists all pages from the provided parameters + public static void listPages(String projectId, String agentId, String flowId, String location) + throws IOException { + // Note: close() needs to be called on the PagesClient object to clean up resources + // such as threads. In the example below, try-with-resources is used, + // which automatically calls close(). + try (PagesClient client = PagesClient.create()) { + Builder listRequestBuilder = ListPagesRequest.newBuilder(); + + String parentPath = + String.format( + "projects/%s/locations/%s/agents/%s/flows/%s", projectId, location, agentId, flowId); + listRequestBuilder.setParent(parentPath); + listRequestBuilder.setLanguageCode("en"); + + // Make API request to list all pages in the project + for (Page element : client.listPages(listRequestBuilder.build()).iterateAll()) { + System.out.println(element); + } + } + } + // [END dialogflow_cx_list_pages] +} diff --git a/dialogflow-cx/src/main/java/dialogflow/cx/ListTestCaseResults.java b/dialogflow-cx/src/main/java/dialogflow/cx/ListTestCaseResults.java new file mode 100644 index 00000000000..2f34d6530c1 --- /dev/null +++ b/dialogflow-cx/src/main/java/dialogflow/cx/ListTestCaseResults.java @@ -0,0 +1,71 @@ +/* + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package dialogflow.cx; + +// [START dialogflow_cx_list_testcase_result_sample] + +import com.google.cloud.dialogflow.cx.v3.ListTestCaseResultsRequest; +import com.google.cloud.dialogflow.cx.v3.ListTestCaseResultsRequest.Builder; +import com.google.cloud.dialogflow.cx.v3.TestCaseResult; +import com.google.cloud.dialogflow.cx.v3.TestCasesClient; +import com.google.cloud.dialogflow.cx.v3.TestCasesSettings; +import java.io.IOException; + +public class ListTestCaseResults { + + public static void main(String[] args) throws IOException { + // TODO(developer): Replace these variables before running the sample. + String projectId = "my-project-id"; + String agentId = "my-agent-id"; + String testId = "my-test-id"; + String location = "my-location"; + listTestCaseResults(projectId, agentId, testId, location); + } + + public static void listTestCaseResults( + String projectId, String agentId, String testId, String location) throws IOException { + String parent = + "projects/" + + projectId + + "/locations/" + + location + + "/agents/" + + agentId + + "/testCases/" + + testId; + + Builder req = ListTestCaseResultsRequest.newBuilder(); + + req.setParent(parent); + req.setFilter("environment=draft"); + + TestCasesSettings testCasesSettings = + TestCasesSettings.newBuilder() + .setEndpoint(location + "-dialogflow.googleapis.com:443") + .build(); + + // Note: close() needs to be called on the TestCasesClient object to clean up resources + // such as threads. In the example below, try-with-resources is used, + // which automatically calls close(). + try (TestCasesClient client = TestCasesClient.create(testCasesSettings)) { + for (TestCaseResult element : client.listTestCaseResults(req.build()).iterateAll()) { + System.out.println(element); + } + } + } +} +// [END dialogflow_cx_list_testcase_result_sample] diff --git a/dialogflow-cx/src/main/java/dialogflow/cx/UpdateIntent.java b/dialogflow-cx/src/main/java/dialogflow/cx/UpdateIntent.java new file mode 100644 index 00000000000..ea16649f66a --- /dev/null +++ b/dialogflow-cx/src/main/java/dialogflow/cx/UpdateIntent.java @@ -0,0 +1,78 @@ +/* + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package dialogflow.cx; + +// [START dialogflow_cx_update_intent] + +import com.google.cloud.dialogflow.cx.v3.Intent; +import com.google.cloud.dialogflow.cx.v3.Intent.Builder; +import com.google.cloud.dialogflow.cx.v3.IntentsClient; +import com.google.cloud.dialogflow.cx.v3.UpdateIntentRequest; +import com.google.protobuf.FieldMask; +import java.io.IOException; + +public class UpdateIntent { + + public static void main(String[] args) throws IOException { + // TODO(developer): Replace these variables before running the sample. + String projectId = "my-project-id"; + String agentId = "my-agent-id"; + String intentId = "my-intent-id"; + String location = "my-location"; + String displayName = "my-display-name"; + updateIntent(projectId, agentId, intentId, location, displayName); + } + + // DialogFlow API Update Intent sample. + public static void updateIntent( + String projectId, String agentId, String intentId, String location, String displayName) + throws IOException { + + // Note: close() needs to be called on the IntentsClient object to clean up resources + // such as threads. In the example below, try-with-resources is used, + // which automatically calls close(). + try (IntentsClient client = IntentsClient.create()) { + String intentPath = + "projects/" + + projectId + + "/locations/" + + location + + "/agents/" + + agentId + + "/intents/" + + intentId; + + Builder intentBuilder = client.getIntent(intentPath).toBuilder(); + + intentBuilder.setDisplayName(displayName); + FieldMask fieldMask = FieldMask.newBuilder().addPaths("display_name").build(); + + Intent intent = intentBuilder.build(); + UpdateIntentRequest request = + UpdateIntentRequest.newBuilder() + .setIntent(intent) + .setLanguageCode("en") + .setUpdateMask(fieldMask) + .build(); + + // Make API request to update intent using fieldmask + Intent response = client.updateIntent(request); + System.out.println(response); + } + } +} +// [END dialogflow_cx_update_intent] diff --git a/dialogflow-cx/src/main/java/dialogflow/cx/WebhookConfigureSessionParameters.java b/dialogflow-cx/src/main/java/dialogflow/cx/WebhookConfigureSessionParameters.java new file mode 100644 index 00000000000..2d59a8ba7e1 --- /dev/null +++ b/dialogflow-cx/src/main/java/dialogflow/cx/WebhookConfigureSessionParameters.java @@ -0,0 +1,58 @@ +/* + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package dialogflow.cx; + +// The following snippet is used in https://cloud.google.com/dialogflow/cx/docs/concept/webhook +// Configures a webhook to set a session parameter + +// [START dialogflow_cx_v3_webhook_configure_session_parameters] + +// TODO: Change class name to Example +// TODO: Uncomment the line below before running cloud function +// package com.example; + +import com.google.cloud.functions.HttpFunction; +import com.google.cloud.functions.HttpRequest; +import com.google.cloud.functions.HttpResponse; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonObject; +import java.io.BufferedWriter; + +public class WebhookConfigureSessionParameters implements HttpFunction { + @Override + public void service(HttpRequest request, HttpResponse response) throws Exception { + JsonObject orderParameter = new JsonObject(); + orderParameter.addProperty("order_number", "12345"); + + JsonObject parameterObject = new JsonObject(); + parameterObject.add("parameters", orderParameter); + + // Creates webhook response object + JsonObject webhookResponse = new JsonObject(); + webhookResponse.add("session_info", parameterObject); + + Gson gson = new GsonBuilder().setPrettyPrinting().create(); + String jsonResponseObject = gson.toJson(webhookResponse); + + /** { "session_info": { "parameters": { "order_number": "12345" } } } */ + BufferedWriter writer = response.getWriter(); + // Sends the webhookResponseObject + writer.write(jsonResponseObject.toString()); + } +} +// [END dialogflow_cx_v3_webhook_configure_session_parameters] diff --git a/dialogflow-cx/src/main/java/dialogflow/cx/WebhookValidateFormParameter.java b/dialogflow-cx/src/main/java/dialogflow/cx/WebhookValidateFormParameter.java new file mode 100644 index 00000000000..320b57f3d65 --- /dev/null +++ b/dialogflow-cx/src/main/java/dialogflow/cx/WebhookValidateFormParameter.java @@ -0,0 +1,79 @@ +/* + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package dialogflow.cx; + +// The following snippet is used in https://cloud.google.com/dialogflow/cx/docs/concept/webhook + +// [START dialogflow_cx_v3_configure_webhooks_to_set_form_parameter_as_optional_or_required] + +// TODO: Change class name to Example +// TODO: Uncomment the line below before running cloud function +// package com.example; + +import com.google.cloud.functions.HttpFunction; +import com.google.cloud.functions.HttpRequest; +import com.google.cloud.functions.HttpResponse; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonArray; +import com.google.gson.JsonObject; +import java.io.BufferedWriter; + +public class WebhookValidateFormParameter implements HttpFunction { + @Override + public void service(HttpRequest request, HttpResponse response) throws Exception { + JsonObject sessionInfo = new JsonObject(); + JsonObject sessionParameter = new JsonObject(); + + sessionParameter.addProperty("order_number", "null"); + sessionInfo.add("parameters", sessionParameter); + + JsonObject parameterObject = new JsonObject(); + parameterObject.addProperty("display_name", "order_number"); + parameterObject.addProperty("required", "true"); + parameterObject.addProperty("state", "INVALID"); + parameterObject.addProperty("value", "123"); + + JsonArray parameterInfoList = new JsonArray(); + parameterInfoList.add(parameterObject); + + JsonObject parameterInfoObject = new JsonObject(); + parameterInfoObject.add("parameter_info", parameterInfoList); + + JsonObject pageInfo = new JsonObject(); + pageInfo.add("form_info", parameterInfoObject); + + // Constructs the webhook response object + JsonObject webhookResponse = new JsonObject(); + webhookResponse.add("page_info", pageInfo); + webhookResponse.add("session_info", sessionInfo); + + Gson gson = new GsonBuilder().setPrettyPrinting().create(); + String jsonResponseObject = gson.toJson(webhookResponse); + + /** + * { "page_info": { "form_info": { "parameter_info": [ { "display_name": "order_number", + * "required": "true", "state": "INVALID", "value": "123" } ] } }, "session_info": { + * "parameters": { "order_number": "null" } } } + */ + BufferedWriter writer = response.getWriter(); + + // Sends the responseObject + writer.write(jsonResponseObject.toString()); + } +} +// [END dialogflow_cx_v3_configure_webhooks_to_set_form_parameter_as_optional_or_required] diff --git a/dialogflow-cx/src/test/java/dialogflow/cx/ConfigureWebhookToSetFormParametersAsOptionalOrRequiredIT.java b/dialogflow-cx/src/test/java/dialogflow/cx/ConfigureWebhookToSetFormParametersAsOptionalOrRequiredIT.java new file mode 100644 index 00000000000..53e30e094e6 --- /dev/null +++ b/dialogflow-cx/src/test/java/dialogflow/cx/ConfigureWebhookToSetFormParametersAsOptionalOrRequiredIT.java @@ -0,0 +1,101 @@ +/* + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package dialogflow.cx; + +import static com.google.common.truth.Truth.assertThat; +import static org.mockito.Mockito.when; + +import com.google.cloud.dialogflow.cx.v3beta1.WebhookRequest; +import com.google.cloud.dialogflow.cx.v3beta1.WebhookRequest.FulfillmentInfo; +import com.google.cloud.functions.HttpRequest; +import com.google.cloud.functions.HttpResponse; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonArray; +import com.google.gson.JsonObject; +import java.io.BufferedReader; +import java.io.BufferedWriter; +import java.io.IOException; +import java.io.StringReader; +import java.io.StringWriter; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; + +public class ConfigureWebhookToSetFormParametersAsOptionalOrRequiredIT { + + @Mock HttpRequest request; + @Mock HttpResponse response; + + BufferedReader jsonReader; + StringReader stringReader; + BufferedWriter writerOut; + StringWriter responseOut; + + @Before + public void beforeTest() throws IOException { + MockitoAnnotations.initMocks(this); + + stringReader = new StringReader("{'fulfillmentInfo': {'tag': 'validate-form-parameter'}}"); + jsonReader = new BufferedReader(stringReader); + + responseOut = new StringWriter(); + writerOut = new BufferedWriter(responseOut); + + when(request.getReader()).thenReturn(jsonReader); + when(response.getWriter()).thenReturn(writerOut); + } + + @Test + public void helloHttp_bodyParamsPost() throws IOException, Exception { + + FulfillmentInfo fulfillmentInfo = + FulfillmentInfo.newBuilder() + .setTag("configure-form-parameters-optional-or-parameter") + .build(); + + WebhookRequest webhookRequest = + WebhookRequest.newBuilder().setFulfillmentInfo(fulfillmentInfo).build(); + + new ConfigureWebhookToSetFormParametersAsOptionalOrRequired().service(request, response); + writerOut.flush(); + + JsonObject parameterObject = new JsonObject(); + parameterObject.addProperty("display_name", "order_number"); + parameterObject.addProperty("required", "true"); + parameterObject.addProperty("state", "VALID"); + + JsonArray parameterInfoList = new JsonArray(); + parameterInfoList.add(parameterObject); + + JsonObject parameterInfoObject = new JsonObject(); + parameterInfoObject.add("parameter_info", parameterInfoList); + + JsonObject formInfo = new JsonObject(); + formInfo.add("form_info", parameterInfoObject); + + JsonObject webhookResponse = new JsonObject(); + webhookResponse.add("page_info", formInfo); + + Gson gson = new GsonBuilder().setPrettyPrinting().create(); + String expectedResponse = gson.toJson(webhookResponse); + + assertThat(responseOut.toString()).isEqualTo(expectedResponse); + Thread.sleep(200); + } +} diff --git a/dialogflow-cx/src/test/java/dialogflow/cx/CreateAgentIT.java b/dialogflow-cx/src/test/java/dialogflow/cx/CreateAgentIT.java new file mode 100644 index 00000000000..aee80c7dee1 --- /dev/null +++ b/dialogflow-cx/src/test/java/dialogflow/cx/CreateAgentIT.java @@ -0,0 +1,67 @@ +/* + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package dialogflow.cx; + +import static com.google.common.truth.Truth.assertThat; + +import com.google.cloud.dialogflow.cx.v3.AgentsClient; +import com.google.cloud.dialogflow.cx.v3.AgentsSettings; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.PrintStream; +import java.util.UUID; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +public class CreateAgentIT { + + private static String PROJECT_ID = System.getenv().get("GOOGLE_CLOUD_PROJECT"); + private static String agentPath = ""; + private ByteArrayOutputStream stdOut; + private static PrintStream originalOut; + + @Before + public void setUp() throws IOException { + originalOut = System.out; + stdOut = new ByteArrayOutputStream(); + System.setOut(new PrintStream(stdOut)); + } + + @After + public void tearDown() throws IOException, InterruptedException { + System.setOut(originalOut); + String apiEndpoint = "global-dialogflow.googleapis.com:443"; + + AgentsSettings agentsSettings = AgentsSettings.newBuilder().setEndpoint(apiEndpoint).build(); + try (AgentsClient client = AgentsClient.create(agentsSettings)) { + client.deleteAgent(CreateAgentIT.agentPath); + + // Small delay to prevent reaching quota limit of requests per minute + Thread.sleep(250); + } + } + + @Test + public void testCreateAgent() throws IOException { + String fakeAgent = String.format("fake_agent_%s", UUID.randomUUID().toString()); + + CreateAgentIT.agentPath = CreateAgent.createAgent(PROJECT_ID, fakeAgent).getName(); + + assertThat(stdOut.toString()).contains(fakeAgent); + } +} diff --git a/dialogflow-cx/src/test/java/dialogflow/cx/CreateFlowIT.java b/dialogflow-cx/src/test/java/dialogflow/cx/CreateFlowIT.java new file mode 100644 index 00000000000..7bbe9de68d6 --- /dev/null +++ b/dialogflow-cx/src/test/java/dialogflow/cx/CreateFlowIT.java @@ -0,0 +1,108 @@ +/* + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package dialogflow.cx; + +import static org.junit.Assert.assertEquals; + +import com.google.cloud.dialogflow.cx.v3beta1.Flow; +import com.google.cloud.dialogflow.cx.v3beta1.FlowsClient; +import com.google.cloud.dialogflow.cx.v3beta1.FlowsSettings; +import com.google.common.collect.ImmutableMap; +import java.util.Map; +import java.util.UUID; +import org.junit.AfterClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** Integration (system) tests for {@link CreateFlow}. */ +@RunWith(JUnit4.class) +@SuppressWarnings("checkstyle:abbreviationaswordinname") +public class CreateFlowIT { + + private static String DISPLAY_NAME = "flow-" + UUID.randomUUID().toString(); + private static String PROJECT_ID = System.getenv("GOOGLE_CLOUD_PROJECT"); + private static String LOCATION_GLOBAL = "global"; + private static String LOCATION_REGIONAL = "us-central1"; + private static String AGENT_ID_GLOBAL = + System.getenv() + .getOrDefault("DIALOGFLOW_CX_AGENT_ID_GLOBAL", "b8d0e85d-0741-4e6d-a66a-3671184b7b93"); + private static String AGENT_ID_REGIONAL = + System.getenv() + .getOrDefault("DIALOGFLOW_CX_AGENT_ID_REGIONAL", "1ea2bf10-d5ef-4442-b93f-a917d1991014"); + private static Map EVENT_TO_FULFILLMENT_MESSAGES = + ImmutableMap.of("event-1", "message-1", "event-2", "message-2"); + + private static String newFlowNameGlobal; + private static String newFlowNameRegional; + + @AfterClass + public static void tearDown() throws Exception { + // Delete the newly created Flow in the global location. + if (newFlowNameGlobal != null) { + try (FlowsClient flowsClient = FlowsClient.create()) { + flowsClient.deleteFlow(newFlowNameGlobal); + } + } + + // Delete the newly created Flow in the regional location. + if (newFlowNameRegional != null) { + FlowsSettings flowsSettings = + FlowsSettings.newBuilder() + .setEndpoint(LOCATION_REGIONAL + "-dialogflow.googleapis.com:443") + .build(); + try (FlowsClient flowsClient = FlowsClient.create(flowsSettings)) { + flowsClient.deleteFlow(newFlowNameRegional); + } + + // Small delay to prevent reaching quota limit of requests per minute + Thread.sleep(250); + } + } + + @Test + public void testCreateFlowGlobal() throws Exception { + Flow result = + CreateFlow.createFlow( + DISPLAY_NAME, + PROJECT_ID, + LOCATION_GLOBAL, + AGENT_ID_GLOBAL, + EVENT_TO_FULFILLMENT_MESSAGES); + newFlowNameGlobal = result.getName(); + + assertEquals(result.getDisplayName(), DISPLAY_NAME); + // Number of added event handlers + 2 default event handlers. + assertEquals(result.getEventHandlersCount(), EVENT_TO_FULFILLMENT_MESSAGES.size() + 2); + } + + @Test + public void testCreateFlowRegional() throws Exception { + Flow result = + CreateFlow.createFlow( + DISPLAY_NAME, + PROJECT_ID, + LOCATION_REGIONAL, + AGENT_ID_REGIONAL, + EVENT_TO_FULFILLMENT_MESSAGES); + newFlowNameRegional = result.getName(); + + assertEquals(result.getDisplayName(), DISPLAY_NAME); + // Number of added event handlers + 2 default event handlers. + assertEquals(result.getEventHandlersCount(), EVENT_TO_FULFILLMENT_MESSAGES.size() + 2); + } +} diff --git a/dialogflow-cx/src/test/java/dialogflow/cx/CreateIntentIT.java b/dialogflow-cx/src/test/java/dialogflow/cx/CreateIntentIT.java new file mode 100644 index 00000000000..6f317122f69 --- /dev/null +++ b/dialogflow-cx/src/test/java/dialogflow/cx/CreateIntentIT.java @@ -0,0 +1,107 @@ +/* + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package dialogflow.cx; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import com.google.cloud.dialogflow.cx.v3beta1.Intent; +import com.google.cloud.dialogflow.cx.v3beta1.Intent.TrainingPhrase; +import com.google.cloud.dialogflow.cx.v3beta1.IntentsClient; +import com.google.cloud.dialogflow.cx.v3beta1.IntentsSettings; +import java.util.Arrays; +import java.util.List; +import java.util.UUID; +import org.junit.AfterClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** Integration (system) tests for {@link CreateIntent}. */ +@RunWith(JUnit4.class) +@SuppressWarnings("checkstyle:abbreviationaswordinname") +public class CreateIntentIT { + + private static String DISPLAY_NAME = "intent-" + UUID.randomUUID().toString(); + private static String PROJECT_ID = System.getenv("GOOGLE_CLOUD_PROJECT"); + private static String LOCATION_GLOBAL = "global"; + private static String LOCATION_REGIONAL = "us-central1"; + private static String AGENT_ID_GLOBAL = + System.getenv() + .getOrDefault("DIALOGFLOW_CX_AGENT_ID_GLOBAL", "b8d0e85d-0741-4e6d-a66a-3671184b7b93"); + private static String AGENT_ID_REGIONAL = + System.getenv() + .getOrDefault("DIALOGFLOW_CX_AGENT_ID_REGIONAL", "1ea2bf10-d5ef-4442-b93f-a917d1991014"); + private static List TRAINING_PHRASES_PARTS = Arrays.asList("red", "blue", "green"); + + private static String newIntentNameGlobal; + private static String newIntentNameRegional; + + @AfterClass + public static void tearDown() throws Exception { + // Delete the newly created Intent in the global location. + if (newIntentNameGlobal != null) { + try (IntentsClient intentsClient = IntentsClient.create()) { + intentsClient.deleteIntent(newIntentNameGlobal); + } + } + + // Delete the newly created Intent in the regional location. + if (newIntentNameRegional != null) { + IntentsSettings intentsSettings = + IntentsSettings.newBuilder() + .setEndpoint(LOCATION_REGIONAL + "-dialogflow.googleapis.com:443") + .build(); + try (IntentsClient intentsClient = IntentsClient.create(intentsSettings)) { + intentsClient.deleteIntent(newIntentNameRegional); + } + } + + // Small delay to prevent reaching quota limit of requests per minute + Thread.sleep(250); + } + + @Test + public void testCreateIntentGlobal() throws Exception { + Intent result = + CreateIntent.createIntent( + DISPLAY_NAME, PROJECT_ID, LOCATION_GLOBAL, AGENT_ID_GLOBAL, TRAINING_PHRASES_PARTS); + newIntentNameGlobal = result.getName(); + + assertEquals(result.getTrainingPhrasesCount(), TRAINING_PHRASES_PARTS.size()); + for (TrainingPhrase trainingPhrase : result.getTrainingPhrasesList()) { + assertEquals(trainingPhrase.getPartsCount(), 1); + String partText = trainingPhrase.getParts(0).getText(); + assertTrue(partText.equals("red") || partText.equals("blue") || partText.equals("green")); + } + } + + @Test + public void testCreateIntentRegional() throws Exception { + Intent result = + CreateIntent.createIntent( + DISPLAY_NAME, PROJECT_ID, LOCATION_REGIONAL, AGENT_ID_REGIONAL, TRAINING_PHRASES_PARTS); + newIntentNameRegional = result.getName(); + + assertEquals(result.getTrainingPhrasesCount(), TRAINING_PHRASES_PARTS.size()); + for (TrainingPhrase trainingPhrase : result.getTrainingPhrasesList()) { + assertEquals(trainingPhrase.getPartsCount(), 1); + String partText = trainingPhrase.getParts(0).getText(); + assertTrue(partText.equals("red") || partText.equals("blue") || partText.equals("green")); + } + } +} diff --git a/dialogflow-cx/src/test/java/dialogflow/cx/CreatePageIT.java b/dialogflow-cx/src/test/java/dialogflow/cx/CreatePageIT.java new file mode 100644 index 00000000000..b392be98cba --- /dev/null +++ b/dialogflow-cx/src/test/java/dialogflow/cx/CreatePageIT.java @@ -0,0 +1,108 @@ +/* + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package dialogflow.cx; + +import static org.junit.Assert.assertEquals; + +import com.google.cloud.dialogflow.cx.v3beta1.Page; +import com.google.cloud.dialogflow.cx.v3beta1.PagesClient; +import com.google.cloud.dialogflow.cx.v3beta1.PagesSettings; +import java.util.Arrays; +import java.util.List; +import java.util.UUID; +import org.junit.AfterClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** Integration (system) tests for {@link CreatePage}. */ +@RunWith(JUnit4.class) +@SuppressWarnings("checkstyle:abbreviationaswordinname") +public class CreatePageIT { + + private static String DISPLAY_NAME = "page-" + UUID.randomUUID().toString(); + private static String PROJECT_ID = System.getenv("GOOGLE_CLOUD_PROJECT"); + private static String LOCATION_GLOBAL = "global"; + private static String LOCATION_REGIONAL = "us-central1"; + private static String AGENT_ID_GLOBAL = + System.getenv() + .getOrDefault("DIALOGFLOW_CX_AGENT_ID_GLOBAL", "b8d0e85d-0741-4e6d-a66a-3671184b7b93"); + private static String AGENT_ID_REGIONAL = + System.getenv() + .getOrDefault("DIALOGFLOW_CX_AGENT_ID_REGIONAL", "1ea2bf10-d5ef-4442-b93f-a917d1991014"); + private static String DEFAULT_START_FLOW_ID = "00000000-0000-0000-0000-000000000000"; + private static List ENTRY_TEXTS = Arrays.asList("Hi", "Hello", "How can I help you?"); + + private static String newPageNameGlobal; + private static String newPageNameRegional; + + @AfterClass + public static void tearDown() throws Exception { + // Delete the newly created Page in the global location. + if (newPageNameGlobal != null) { + try (PagesClient pagesClient = PagesClient.create()) { + pagesClient.deletePage(newPageNameGlobal); + } + + // Small delay to prevent reaching quota limit of requests per minute + Thread.sleep(250); + } + + // Delete the newly created Page in the regional location. + if (newPageNameRegional != null) { + PagesSettings pagesSettings = + PagesSettings.newBuilder() + .setEndpoint(LOCATION_REGIONAL + "-dialogflow.googleapis.com:443") + .build(); + try (PagesClient pagesClient = PagesClient.create(pagesSettings)) { + pagesClient.deletePage(newPageNameRegional); + } + } + } + + @Test + public void testCreatePageGlobal() throws Exception { + Page result = + CreatePage.createPage( + DISPLAY_NAME, + PROJECT_ID, + LOCATION_GLOBAL, + AGENT_ID_GLOBAL, + DEFAULT_START_FLOW_ID, + ENTRY_TEXTS); + newPageNameGlobal = result.getName(); + + assertEquals(result.getDisplayName(), DISPLAY_NAME); + assertEquals(result.getEntryFulfillment().getMessagesCount(), ENTRY_TEXTS.size()); + } + + @Test + public void testCreatePageRegional() throws Exception { + Page result = + CreatePage.createPage( + DISPLAY_NAME, + PROJECT_ID, + LOCATION_REGIONAL, + AGENT_ID_REGIONAL, + DEFAULT_START_FLOW_ID, + ENTRY_TEXTS); + newPageNameRegional = result.getName(); + + assertEquals(result.getDisplayName(), DISPLAY_NAME); + assertEquals(result.getEntryFulfillment().getMessagesCount(), ENTRY_TEXTS.size()); + } +} diff --git a/dialogflow-cx/src/test/java/dialogflow/cx/DetectIntentAudioInputTest.java b/dialogflow-cx/src/test/java/dialogflow/cx/DetectIntentAudioInputTest.java new file mode 100644 index 00000000000..ffe3619149d --- /dev/null +++ b/dialogflow-cx/src/test/java/dialogflow/cx/DetectIntentAudioInputTest.java @@ -0,0 +1,72 @@ +/* + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package dialogflow.cx; + +import static com.google.common.truth.Truth.assertThat; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.PrintStream; +import java.util.UUID; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +/** Unit test for {@link DetectIntentIntentAudioInput}. */ +@SuppressWarnings("checkstyle:abbreviationaswordinname") +public class DetectIntentAudioInputTest { + + private static String PROJECT_ID = System.getenv("GOOGLE_CLOUD_PROJECT"); + private static String LOCATION = "global"; + private static String AGENT_ID = + System.getenv() + .getOrDefault("DIALOGFLOW_CX_AGENT_ID_GLOBAL", "b8d0e85d-0741-4e6d-a66a-3671184b7b93"); + private static String AUDIO_FILE_NAME = "resources/book_a_room.wav"; + private static int SAMPLE_RATE_HERTZ = 16000; + private static String SESSION_ID = UUID.randomUUID().toString(); + private static String LANGUAGE_CODE = "en"; + + private ByteArrayOutputStream stdOut; + + @Before + public void setUp() throws IOException { + + stdOut = new ByteArrayOutputStream(); + System.setOut(new PrintStream(stdOut)); + } + + @After + public void tearDown() throws IOException { + stdOut = null; + System.setOut(null); + } + + @Test + public void testDetectIntentAudioInput() throws Exception { + + DetectIntentAudioInput.detectIntent( + PROJECT_ID, + LOCATION, + AGENT_ID, + AUDIO_FILE_NAME, + SAMPLE_RATE_HERTZ, + SESSION_ID, + LANGUAGE_CODE); + System.out.println(stdOut.toString()); + assertThat(stdOut.toString()).contains("Detected Intent:"); + } +} diff --git a/dialogflow-cx/src/test/java/dialogflow/cx/DetectIntentDisableWebhookTest.java b/dialogflow-cx/src/test/java/dialogflow/cx/DetectIntentDisableWebhookTest.java new file mode 100644 index 00000000000..3564ed1cc2f --- /dev/null +++ b/dialogflow-cx/src/test/java/dialogflow/cx/DetectIntentDisableWebhookTest.java @@ -0,0 +1,74 @@ +/* + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package dialogflow.cx; + +import static com.google.common.truth.Truth.assertThat; + +import com.google.cloud.dialogflow.cx.v3.QueryResult; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.PrintStream; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +/** Unit test for {@link DetectIntentDisableWebhook}. */ +@SuppressWarnings("checkstyle:abbreviationaswordinname") +public class DetectIntentDisableWebhookTest { + + private static String PROJECT_ID = System.getenv("GOOGLE_CLOUD_PROJECT"); + private static String LOCATION = "global"; + private static String AGENT_ID = + System.getenv() + .getOrDefault("DIALOGFLOW_CX_AGENT_ID_GLOBAL", "b8d0e85d-0741-4e6d-a66a-3671184b7b93"); + private static String SESSION_ID = UUID.randomUUID().toString(); + private static String LANGUAGE_CODE = "en-US"; + private static List TEXTS = Arrays.asList("hello", "unhappy"); + + private ByteArrayOutputStream stdOut; + + @Before + public void setUp() throws IOException { + + stdOut = new ByteArrayOutputStream(); + System.setOut(new PrintStream(stdOut)); + } + + @After + public void tearDown() throws IOException { + stdOut = null; + System.setOut(null); + } + + @Test + public void testDetectIntentDisableWebhook() throws Exception { + Map queryResults = + DetectIntentDisableWebhook.detectIntent( + PROJECT_ID, LOCATION, AGENT_ID, SESSION_ID, TEXTS, LANGUAGE_CODE); + + for (int i = 0; i < TEXTS.size(); i++) { + String text = TEXTS.get(i); + float score = queryResults.get(text).getSentimentAnalysisResult().getScore(); + System.out.println(stdOut.toString()); + assertThat(stdOut.toString()).contains("disable_webhook"); + } + } +} diff --git a/dialogflow-cx/src/test/java/dialogflow/cx/DetectIntentEventInputTest.java b/dialogflow-cx/src/test/java/dialogflow/cx/DetectIntentEventInputTest.java new file mode 100644 index 00000000000..f6362519411 --- /dev/null +++ b/dialogflow-cx/src/test/java/dialogflow/cx/DetectIntentEventInputTest.java @@ -0,0 +1,66 @@ +/* + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package dialogflow.cx; + +import static com.google.common.truth.Truth.assertThat; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.PrintStream; +import java.util.UUID; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +/** Unit test for {@link DetectIntentEventInput}. */ +@SuppressWarnings("checkstyle:abbreviationaswordinname") +public class DetectIntentEventInputTest { + + private static String PROJECT_ID = System.getenv("GOOGLE_CLOUD_PROJECT"); + private static String LOCATION = "global"; + private static String AGENT_ID = + System.getenv() + .getOrDefault("DIALOGFLOW_CX_AGENT_ID_GLOBAL", "b8d0e85d-0741-4e6d-a66a-3671184b7b93"); + private static String EVENT = "sys.no-match-default"; + private static String SESSION_ID = UUID.randomUUID().toString(); + private static String LANGUAGE_CODE = "en-US"; + + private ByteArrayOutputStream stdOut; + + @Before + public void setUp() throws IOException { + + stdOut = new ByteArrayOutputStream(); + System.setOut(new PrintStream(stdOut)); + } + + @After + public void tearDown() throws IOException { + stdOut = null; + System.setOut(null); + } + + @Test + public void testDetectIntentEventInput() throws Exception { + String triggeringEvent = "sys.no-match-default"; + + DetectIntentEventInput.detectIntent( + PROJECT_ID, LOCATION, AGENT_ID, SESSION_ID, EVENT, LANGUAGE_CODE); + System.out.println(stdOut.toString()); + assertThat(stdOut.toString()).contains(triggeringEvent); + } +} diff --git a/dialogflow-cx/src/test/java/dialogflow/cx/DetectIntentIT.java b/dialogflow-cx/src/test/java/dialogflow/cx/DetectIntentIT.java new file mode 100644 index 00000000000..66d356a9b2d --- /dev/null +++ b/dialogflow-cx/src/test/java/dialogflow/cx/DetectIntentIT.java @@ -0,0 +1,78 @@ +/* + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package dialogflow.cx; + +import static org.junit.Assert.assertEquals; + +import com.google.cloud.dialogflow.cx.v3beta1.QueryResult; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import org.junit.After; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** Integration (system) tests for {@link DetectIntentText}. */ +@RunWith(JUnit4.class) +@SuppressWarnings("checkstyle:abbreviationaswordinname") +public class DetectIntentIT { + + private static String PROJECT_ID = System.getenv("GOOGLE_CLOUD_PROJECT"); + private static String LOCATION_GLOBAL = "global"; + private static String LOCATION_REGIONAL = "us-central1"; + private static String AGENT_ID_GLOBAL = + System.getenv() + .getOrDefault("DIALOGFLOW_CX_AGENT_ID_GLOBAL", "b8d0e85d-0741-4e6d-a66a-3671184b7b93"); + private static String AGENT_ID_REGIONAL = + System.getenv() + .getOrDefault("DIALOGFLOW_CX_AGENT_ID_REGIONAL", "1ea2bf10-d5ef-4442-b93f-a917d1991014"); + 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"); + + @After + public void tearDown() throws InterruptedException { + // Small delay to prevent reaching quota limit of requests per minute + Thread.sleep(250); + } + + @Test + public void testDetectIntentGlobal() throws Exception { + Map queryResults = + DetectIntent.detectIntent( + PROJECT_ID, LOCATION_GLOBAL, AGENT_ID_GLOBAL, SESSION_ID, TEXTS, LANGUAGE_CODE); + assertEquals(queryResults.size(), TEXTS.size()); + for (int i = 0; i < TEXTS.size(); i++) { + String text = TEXTS.get(i); + assertEquals(queryResults.get(text).getText(), text); + } + } + + @Test + public void testDetectIntentRegional() throws Exception { + Map queryResults = + DetectIntent.detectIntent( + PROJECT_ID, LOCATION_REGIONAL, AGENT_ID_REGIONAL, SESSION_ID, TEXTS, LANGUAGE_CODE); + assertEquals(queryResults.size(), TEXTS.size()); + for (int i = 0; i < TEXTS.size(); i++) { + String text = TEXTS.get(i); + assertEquals(queryResults.get(text).getText(), text); + } + } +} diff --git a/dialogflow-cx/src/test/java/dialogflow/cx/DetectIntentIntentInputTest.java b/dialogflow-cx/src/test/java/dialogflow/cx/DetectIntentIntentInputTest.java new file mode 100644 index 00000000000..51dc3a560f8 --- /dev/null +++ b/dialogflow-cx/src/test/java/dialogflow/cx/DetectIntentIntentInputTest.java @@ -0,0 +1,75 @@ +/* + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package dialogflow.cx; + +import static com.google.common.truth.Truth.assertThat; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.PrintStream; +import java.util.UUID; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +/** Unit test for {@link DetectIntentIntentInput}. */ +@SuppressWarnings("checkstyle:abbreviationaswordinname") +public class DetectIntentIntentInputTest { + + private static String PROJECT_ID = System.getenv("GOOGLE_CLOUD_PROJECT"); + private static String LOCATION = "global"; + private static String AGENT_ID = + System.getenv() + .getOrDefault("DIALOGFLOW_CX_AGENT_ID_GLOBAL", "b8d0e85d-0741-4e6d-a66a-3671184b7b93"); + private static String INTENT_ID = "00000000-0000-0000-0000-000000000000"; + private static String SESSION_ID = UUID.randomUUID().toString(); + private static String LANGUAGE_CODE = "en-US"; + private static String INTENT = + "projects/" + + PROJECT_ID + + "/locations/" + + LOCATION + + "/agents/" + + AGENT_ID + + "/intents/" + + INTENT_ID; + + private ByteArrayOutputStream stdOut; + + @Before + public void setUp() throws IOException { + + stdOut = new ByteArrayOutputStream(); + System.setOut(new PrintStream(stdOut)); + } + + @After + public void tearDown() throws IOException { + stdOut = null; + System.setOut(null); + } + + @Test + public void testDetectIntentIntentInput() throws Exception { + String intentName = "Default Welcome Intent"; + + DetectIntentIntentInput.detectIntent( + PROJECT_ID, LOCATION, AGENT_ID, SESSION_ID, INTENT, LANGUAGE_CODE); + System.out.println(stdOut.toString()); + assertThat(stdOut.toString()).contains(intentName); + } +} diff --git a/dialogflow-cx/src/test/java/dialogflow/cx/DetectIntentSentimentAnalysisTest.java b/dialogflow-cx/src/test/java/dialogflow/cx/DetectIntentSentimentAnalysisTest.java new file mode 100644 index 00000000000..2194a9e70b8 --- /dev/null +++ b/dialogflow-cx/src/test/java/dialogflow/cx/DetectIntentSentimentAnalysisTest.java @@ -0,0 +1,56 @@ +/* + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package dialogflow.cx; + +import static org.junit.Assert.assertTrue; + +import com.google.cloud.dialogflow.cx.v3.QueryResult; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import org.junit.Test; + +/** Unit test for {@link DetectIntentSentimentAnalysis}. */ +@SuppressWarnings("checkstyle:abbreviationaswordinname") +public class DetectIntentSentimentAnalysisTest { + + private static String PROJECT_ID = System.getenv("GOOGLE_CLOUD_PROJECT"); + private static String LOCATION = "global"; + private static String AGENT_ID = + System.getenv() + .getOrDefault("DIALOGFLOW_CX_AGENT_ID_GLOBAL", "b8d0e85d-0741-4e6d-a66a-3671184b7b93"); + private static String SESSION_ID = UUID.randomUUID().toString(); + private static String LANGUAGE_CODE = "en-US"; + private static List TEXTS = Arrays.asList("hello", "unhappy"); + + @Test + public void testDetectIntentSentimentAnalysis() throws Exception { + int min = -1; + int max = 1; + + Map queryResults = + DetectIntentSentimentAnalysis.detectIntent( + PROJECT_ID, LOCATION, AGENT_ID, SESSION_ID, TEXTS, LANGUAGE_CODE); + + for (int i = 0; i < TEXTS.size(); i++) { + String text = TEXTS.get(i); + float score = queryResults.get(text).getSentimentAnalysisResult().getScore(); + assertTrue(min <= score && score <= max); + } + } +} diff --git a/dialogflow-cx/src/test/java/dialogflow/cx/DetectIntentStreamIT.java b/dialogflow-cx/src/test/java/dialogflow/cx/DetectIntentStreamIT.java new file mode 100644 index 00000000000..b941420f055 --- /dev/null +++ b/dialogflow-cx/src/test/java/dialogflow/cx/DetectIntentStreamIT.java @@ -0,0 +1,87 @@ +/* + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package dialogflow.cx; + +import static com.google.common.truth.Truth.assertThat; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.PrintStream; +import java.util.UUID; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** Integration (system) tests for {@link DetectIntentStream}. */ +@RunWith(JUnit4.class) +@SuppressWarnings("checkstyle:abbreviationaswordinname") +public class DetectIntentStreamIT { + + private static String AUDIO_FILE_PATH = "resources/book_a_room.wav"; + private static String PROJECT_ID = System.getenv("GOOGLE_CLOUD_PROJECT"); + private static String LOCATION_GLOBAL = "global"; + private static String LOCATION_REGIONAL = "us-central1"; + private static String AGENT_ID_GLOBAL = + System.getenv() + .getOrDefault("DIALOGFLOW_CX_AGENT_ID_GLOBAL", "b8d0e85d-0741-4e6d-a66a-3671184b7b93"); + private static String AGENT_ID_REGIONAL = + System.getenv() + .getOrDefault("DIALOGFLOW_CX_AGENT_ID_REGIONAL", "1ea2bf10-d5ef-4442-b93f-a917d1991014"); + private static String SESSION_ID = UUID.randomUUID().toString(); + private ByteArrayOutputStream bout; + private PrintStream original; + + @Before + public void setUp() { + original = System.out; + bout = new ByteArrayOutputStream(); + System.setOut(new PrintStream(bout)); + } + + @After + public void tearDown() throws InterruptedException { + System.setOut(original); + bout.reset(); + + // Small delay to prevent reaching quota limit of requests per minute + Thread.sleep(250); + } + + @Test + public void testDetectIntentStreamGlobal() throws IOException { + DetectIntentStream.detectIntentStream( + PROJECT_ID, LOCATION_GLOBAL, AGENT_ID_GLOBAL, SESSION_ID, AUDIO_FILE_PATH); + + String output = bout.toString(); + + assertThat(output).contains("Detected Intent"); + assertThat(output).contains("book"); + } + + @Test + public void testDetectIntentStreamRegional() throws IOException { + DetectIntentStream.detectIntentStream( + PROJECT_ID, LOCATION_REGIONAL, AGENT_ID_REGIONAL, SESSION_ID, AUDIO_FILE_PATH); + + String output = bout.toString(); + + assertThat(output).contains("Detected Intent"); + assertThat(output).contains("book"); + } +} diff --git a/dialogflow-cx/src/test/java/dialogflow/cx/DetectIntentStreamingPartialResponseTest.java b/dialogflow-cx/src/test/java/dialogflow/cx/DetectIntentStreamingPartialResponseTest.java new file mode 100644 index 00000000000..7f6f24a2ee4 --- /dev/null +++ b/dialogflow-cx/src/test/java/dialogflow/cx/DetectIntentStreamingPartialResponseTest.java @@ -0,0 +1,68 @@ +/* + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package dialogflow.cx; + +import static com.google.common.truth.Truth.assertThat; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.PrintStream; +import java.util.UUID; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** Integration (system) tests for {@link DetectIntentStream}. */ +@RunWith(JUnit4.class) +@SuppressWarnings("checkstyle:abbreviationaswordinname") +public class DetectIntentStreamingPartialResponseTest { + + private static String AUDIO_FILE_PATH = "resources/book_a_room.wav"; + private static String PROJECT_ID = System.getenv("GOOGLE_CLOUD_PROJECT"); + private static String LOCATION = "global"; + private static String AGENT_ID = + System.getenv() + .getOrDefault("DIALOGFLOW_CX_AGENT_ID_GLOBAL", "b8d0e85d-0741-4e6d-a66a-3671184b7b93"); + private static String SESSION_ID = UUID.randomUUID().toString(); + private ByteArrayOutputStream bout; + private PrintStream original; + + @Before + public void setUp() { + original = System.out; + bout = new ByteArrayOutputStream(); + System.setOut(new PrintStream(bout)); + } + + @After + public void tearDown() { + System.setOut(original); + bout.reset(); + } + + @Test + public void testDetectIntentStreamingPartialResponse() throws IOException { + DetectIntentStreamingPartialResponse.detectIntentStreamingPartialResponse( + PROJECT_ID, LOCATION, AGENT_ID, SESSION_ID, AUDIO_FILE_PATH); + + String output = bout.toString(); + + assertThat(output).contains("enable_partial_response"); + } +} diff --git a/dialogflow-cx/src/test/java/dialogflow/cx/DetectIntentSynthesizeTextToSpeechOutputTest.java b/dialogflow-cx/src/test/java/dialogflow/cx/DetectIntentSynthesizeTextToSpeechOutputTest.java new file mode 100644 index 00000000000..20d84e37a1e --- /dev/null +++ b/dialogflow-cx/src/test/java/dialogflow/cx/DetectIntentSynthesizeTextToSpeechOutputTest.java @@ -0,0 +1,72 @@ +/* + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package dialogflow.cx; + +import static com.google.common.truth.Truth.assertThat; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.PrintStream; +import java.util.UUID; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +/** Unit test for {@link DetectIntentSynthesizeTtSOutput}. */ +@SuppressWarnings("checkstyle:abbreviationaswordinname") +public class DetectIntentSynthesizeTextToSpeechOutputTest { + + private static String PROJECT_ID = System.getenv("GOOGLE_CLOUD_PROJECT"); + private static String LOCATION = "global"; + private static String AGENT_ID = + System.getenv() + .getOrDefault("DIALOGFLOW_CX_AGENT_ID_GLOBAL", "b8d0e85d-0741-4e6d-a66a-3671184b7b93"); + private static String AUDIO_FILE_NAME = "resources/book_a_room.wav"; + private static int SAMPLE_RATE_HERTZ = 16000; + private static String SESSION_ID = UUID.randomUUID().toString(); + private static String LANGUAGE_CODE = "en"; + + private ByteArrayOutputStream stdOut; + + @Before + public void setUp() throws IOException { + + stdOut = new ByteArrayOutputStream(); + System.setOut(new PrintStream(stdOut)); + } + + @After + public void tearDown() throws IOException { + stdOut = null; + System.setOut(null); + } + + @Test + public void testDetectIntentSynthesizeTextToSpeechOutput() throws Exception { + + DetectIntentSynthesizeTextToSpeechOutput.detectIntent( + PROJECT_ID, + LOCATION, + AGENT_ID, + AUDIO_FILE_NAME, + SAMPLE_RATE_HERTZ, + SESSION_ID, + LANGUAGE_CODE); + System.out.println(stdOut.toString()); + assertThat(stdOut.toString()).contains("speaking_rate"); + } +} diff --git a/dialogflow-cx/src/test/java/dialogflow/cx/ExportAgentIT.java b/dialogflow-cx/src/test/java/dialogflow/cx/ExportAgentIT.java new file mode 100644 index 00000000000..e499fe726d7 --- /dev/null +++ b/dialogflow-cx/src/test/java/dialogflow/cx/ExportAgentIT.java @@ -0,0 +1,96 @@ +/* + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package dialogflow.cx; + +import static com.google.common.truth.Truth.assertThat; + +import com.google.cloud.dialogflow.cx.v3.Agent; +import com.google.cloud.dialogflow.cx.v3.Agent.Builder; +import com.google.cloud.dialogflow.cx.v3.AgentsClient; +import com.google.cloud.dialogflow.cx.v3.AgentsSettings; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.PrintStream; +import java.util.UUID; +import java.util.concurrent.ExecutionException; +import org.junit.After; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; + +public class ExportAgentIT { + + private static String PROJECT_ID = System.getenv("GOOGLE_CLOUD_PROJECT"); + private static String parent = ""; + private static String agentPath = ""; + private static String agentID = ""; + + private ByteArrayOutputStream stdOut; + + @BeforeClass + public static void beforeAll() { + assertThat(PROJECT_ID).isNotNull(); + } + + @Before + public void setUp() throws IOException { + stdOut = new ByteArrayOutputStream(); + System.setOut(new PrintStream(stdOut)); + + Builder build = Agent.newBuilder(); + build.setDefaultLanguageCode("en"); + build.setDisplayName("temp_agent_" + UUID.randomUUID().toString()); + build.setTimeZone("America/Los_Angeles"); + + Agent agent = build.build(); + + String apiEndpoint = "global-dialogflow.googleapis.com:443"; + String parentPath = "projects/" + PROJECT_ID + "/locations/global"; + + AgentsSettings agentsSettings = AgentsSettings.newBuilder().setEndpoint(apiEndpoint).build(); + AgentsClient client = AgentsClient.create(agentsSettings); + + parent = client.createAgent(parentPath, agent).getName(); + ExportAgentIT.agentPath = parent; + ExportAgentIT.agentID = parent.split("/")[5]; + client.close(); + } + + @After + public void tearDown() throws IOException, InterruptedException { + stdOut = null; + System.setOut(null); + String apiEndpoint = "global-dialogflow.googleapis.com:443"; + + AgentsSettings agentsSettings = AgentsSettings.newBuilder().setEndpoint(apiEndpoint).build(); + AgentsClient client = AgentsClient.create(agentsSettings); + + client.deleteAgent(ExportAgentIT.agentPath); + client.close(); + + // Small delay to prevent reaching quota limit of requests per minute + Thread.sleep(250); + } + + @Test + public void testUpdateExportAgent() throws IOException, InterruptedException, ExecutionException { + + ExportAgent.exportAgent(PROJECT_ID, ExportAgentIT.agentID, "global"); + + assertThat(stdOut.toString()).contains(ExportAgentIT.agentID); + } +} diff --git a/dialogflow-cx/src/test/java/dialogflow/cx/ListTestCaseResultsIT.java b/dialogflow-cx/src/test/java/dialogflow/cx/ListTestCaseResultsIT.java new file mode 100644 index 00000000000..2214356f1c9 --- /dev/null +++ b/dialogflow-cx/src/test/java/dialogflow/cx/ListTestCaseResultsIT.java @@ -0,0 +1,58 @@ +/* + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package dialogflow.cx; + +import static com.google.common.truth.Truth.assertThat; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.PrintStream; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +public class ListTestCaseResultsIT { + + private static String PROJECT_ID = System.getenv().get("GOOGLE_CLOUD_PROJECT"); + private static String agentId = "1499b8e1-ab7d-43fd-9b08-30ee57194fc1"; + private static String testId = "694a5447-6c40-4752-944e-e3e70580b273"; + private static String location = "global"; + + private ByteArrayOutputStream stdOut; + private static PrintStream originalOut; + + @Before + public void setUp() throws IOException { + originalOut = System.out; + stdOut = new ByteArrayOutputStream(); + System.setOut(new PrintStream(stdOut)); + } + + @After + public void tearDown() throws IOException, InterruptedException { + System.setOut(originalOut); + + // Small delay to prevent reaching quota limit of requests per minute + Thread.sleep(250); + } + + @Test + public void testListTestCaseResults() throws IOException { + ListTestCaseResults.listTestCaseResults(PROJECT_ID, agentId, testId, location); + assertThat(stdOut.toString()).contains(testId); + } +} diff --git a/dialogflow-cx/src/test/java/dialogflow/cx/PageManagementIT.java b/dialogflow-cx/src/test/java/dialogflow/cx/PageManagementIT.java new file mode 100644 index 00000000000..47c100107d4 --- /dev/null +++ b/dialogflow-cx/src/test/java/dialogflow/cx/PageManagementIT.java @@ -0,0 +1,117 @@ +/* + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package dialogflow.cx; + +import static com.google.common.truth.Truth.assertThat; + +import com.google.cloud.dialogflow.cx.v3.Agent; +import com.google.cloud.dialogflow.cx.v3.Agent.Builder; +import com.google.cloud.dialogflow.cx.v3.AgentsClient; +import com.google.cloud.dialogflow.cx.v3.AgentsSettings; +import com.google.cloud.dialogflow.cx.v3.Page; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.PrintStream; +import java.util.UUID; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; + +/** Integration (system) tests for {@link PageManagment}. */ +public class PageManagementIT { + + private static String PROJECT_ID = System.getenv().get("GOOGLE_CLOUD_PROJECT"); + private static String flowID = "00000000-0000-0000-0000-000000000000"; + private static String location = "global"; + private static String displayName = "temp_page_" + UUID.randomUUID().toString(); + private static String parent; + private static String agentID; + private static String pageID; + private static ByteArrayOutputStream stdOut; + + @BeforeClass + public static void setUp() throws IOException { + stdOut = new ByteArrayOutputStream(); + System.setOut(new PrintStream(stdOut)); + + String apiEndpoint = "global-dialogflow.googleapis.com:443"; + + AgentsSettings agentsSettings = AgentsSettings.newBuilder().setEndpoint(apiEndpoint).build(); + try (AgentsClient client = AgentsClient.create(agentsSettings)) { + + Builder build = Agent.newBuilder(); + build.setDefaultLanguageCode("en"); + build.setDisplayName("temp_agent_" + UUID.randomUUID().toString()); + build.setTimeZone("America/Los_Angeles"); + + Agent agent = build.build(); + String parentPath = "projects/" + PROJECT_ID + "/locations/global"; + + parent = client.createAgent(parentPath, agent).getName(); + + agentID = parent.split("/")[5]; + } + } + + @AfterClass + public static void tearDown() throws IOException, InterruptedException { + String apiEndpoint = "global-dialogflow.googleapis.com:443"; + String parentPath = "projects/" + PROJECT_ID + "/locations/global"; + + AgentsSettings agentsSettings = AgentsSettings.newBuilder().setEndpoint(apiEndpoint).build(); + try (AgentsClient client = AgentsClient.create(agentsSettings)) { + client.deleteAgent(parent); + + // Small delay to prevent reaching quota limit of requests per minute + Thread.sleep(250); + } + } + + @Test + public void testCreatePage() throws IOException { + try { + Page p = CreateSimplePage.createPage(PROJECT_ID, agentID, flowID, location, displayName); + pageID = p.getName().split("/")[9]; + assertThat(p.getDisplayName()).isEqualTo(displayName); + } catch (Exception e) { + assertThat(e).isEqualTo(""); + } + } + + @Test + public void testListPages() throws IOException { + String name = "temp_page_" + UUID.randomUUID().toString(); + // Page p + try { + CreateSimplePage.createPage(PROJECT_ID, agentID, flowID, location, name); + ListPages.listPages(PROJECT_ID, agentID, flowID, location); + assertThat(stdOut.toString()).contains(name); + } catch (Exception e) { + assertThat(e).isEqualTo(""); + } + } + + @Test + public void testDeletePage() throws IOException { + try { + DeletePage.deletePage(PROJECT_ID, agentID, flowID, pageID, location); + assertThat(1).isEqualTo(1); + } catch (Exception e) { + assertThat(e).isEqualTo(""); + } + } +} diff --git a/dialogflow-cx/src/test/java/dialogflow/cx/UpdateIntentTest.java b/dialogflow-cx/src/test/java/dialogflow/cx/UpdateIntentTest.java new file mode 100644 index 00000000000..635b16b781b --- /dev/null +++ b/dialogflow-cx/src/test/java/dialogflow/cx/UpdateIntentTest.java @@ -0,0 +1,106 @@ +/* + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package dialogflow.cx; + +import static com.google.common.truth.Truth.assertThat; + +import com.google.cloud.dialogflow.cx.v3.Agent; +import com.google.cloud.dialogflow.cx.v3.Agent.Builder; +import com.google.cloud.dialogflow.cx.v3.AgentsClient; +import com.google.cloud.dialogflow.cx.v3.AgentsSettings; +import com.google.cloud.dialogflow.cx.v3.Intent; +import com.google.cloud.dialogflow.cx.v3.IntentsClient; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.PrintStream; +import java.util.UUID; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +public class UpdateIntentTest { + + private static String PROJECT_ID = System.getenv().get("GOOGLE_CLOUD_PROJECT"); + private static String parent = ""; + private static String intentID = ""; + private static String intentPath = ""; + private static String agentID = ""; + + private ByteArrayOutputStream stdOut; + + @Before + public void setUp() throws IOException { + + stdOut = new ByteArrayOutputStream(); + System.setOut(new PrintStream(stdOut)); + + String apiEndpoint = "global-dialogflow.googleapis.com:443"; + + AgentsSettings agentsSettings = AgentsSettings.newBuilder().setEndpoint(apiEndpoint).build(); + try (AgentsClient agentsClient = AgentsClient.create(agentsSettings)) { + + Builder build = Agent.newBuilder(); + + build.setDefaultLanguageCode("en"); + build.setDisplayName("temp_agent_" + UUID.randomUUID().toString()); + build.setTimeZone("America/Los_Angeles"); + + Agent agent = build.build(); + String parentPath = String.format("projects/%s/locations/global", PROJECT_ID); + + parent = agentsClient.createAgent(parentPath, agent).getName(); + + UpdateIntentTest.agentID = parent.split("/")[5]; + } + + try (IntentsClient intentsClient = IntentsClient.create()) { + com.google.cloud.dialogflow.cx.v3.Intent.Builder intent = Intent.newBuilder(); + intent.setDisplayName("temp_intent_" + UUID.randomUUID().toString()); + + UpdateIntentTest.intentPath = intentsClient.createIntent(parent, intent.build()).getName(); + UpdateIntentTest.intentID = UpdateIntentTest.intentPath.split("/")[7]; + } + } + + @After + public void tearDown() throws IOException, InterruptedException { + stdOut = null; + System.setOut(null); + + String apiEndpoint = "global-dialogflow.googleapis.com:443"; + + AgentsSettings agentsSettings = AgentsSettings.newBuilder().setEndpoint(apiEndpoint).build(); + try (AgentsClient client = AgentsClient.create(agentsSettings)) { + String parentPath = "projects/" + PROJECT_ID + "/locations/global"; + client.deleteAgent(parent); + + // Small delay to prevent reaching quota limit of requests per minute + Thread.sleep(250); + } + } + + @Test + public void testUpdateIntent() throws IOException { + + String fakeIntent = "fake_intent_" + UUID.randomUUID().toString(); + + UpdateIntent.updateIntent( + PROJECT_ID, UpdateIntentTest.agentID, UpdateIntentTest.intentID, "global", fakeIntent); + + assertThat(stdOut.toString()).contains(fakeIntent); + } +} diff --git a/dialogflow-cx/src/test/java/dialogflow/cx/WebhookConfigureSessionParametersIT.java b/dialogflow-cx/src/test/java/dialogflow/cx/WebhookConfigureSessionParametersIT.java new file mode 100644 index 00000000000..9c1d2a71929 --- /dev/null +++ b/dialogflow-cx/src/test/java/dialogflow/cx/WebhookConfigureSessionParametersIT.java @@ -0,0 +1,87 @@ +/* + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package dialogflow.cx; + +import static com.google.common.truth.Truth.assertThat; +import static org.mockito.Mockito.when; + +import com.google.cloud.dialogflow.cx.v3beta1.WebhookRequest; +import com.google.cloud.dialogflow.cx.v3beta1.WebhookRequest.FulfillmentInfo; +import com.google.cloud.functions.HttpRequest; +import com.google.cloud.functions.HttpResponse; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonObject; +import java.io.BufferedReader; +import java.io.BufferedWriter; +import java.io.IOException; +import java.io.StringReader; +import java.io.StringWriter; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; + +public class WebhookConfigureSessionParametersIT { + + @Mock HttpRequest request; + @Mock HttpResponse response; + + BufferedReader jsonReader; + StringReader stringReader; + BufferedWriter writerOut; + StringWriter responseOut; + + @Before + public void beforeTest() throws IOException { + MockitoAnnotations.initMocks(this); + + stringReader = new StringReader("{'fulfillmentInfo': {'tag': 'configure-session-parameter'}}"); + jsonReader = new BufferedReader(stringReader); + + responseOut = new StringWriter(); + writerOut = new BufferedWriter(responseOut); + + when(request.getReader()).thenReturn(jsonReader); + when(response.getWriter()).thenReturn(writerOut); + } + + @Test + public void helloHttp_bodyParamsPost() throws IOException, Exception { + FulfillmentInfo fulfillmentInfo = + FulfillmentInfo.newBuilder().setTag("configure-session-parameters").build(); + + WebhookRequest webhookRequest = + WebhookRequest.newBuilder().setFulfillmentInfo(fulfillmentInfo).build(); + + new WebhookConfigureSessionParameters().service(request, response); + writerOut.flush(); + + JsonObject webhookResponse = new JsonObject(); + JsonObject parameterObject = new JsonObject(); + JsonObject orderParameter = new JsonObject(); + orderParameter.addProperty("order_number", "12345"); + parameterObject.add("parameters", orderParameter); + webhookResponse.add("session_info", parameterObject); + + Gson gson = new GsonBuilder().setPrettyPrinting().create(); + String expectedResponse = gson.toJson(webhookResponse); + + assertThat(responseOut.toString()).isEqualTo(expectedResponse); + Thread.sleep(200); + } +} diff --git a/dialogflow-cx/src/test/java/dialogflow/cx/WebhookValidateFormParameterIT.java b/dialogflow-cx/src/test/java/dialogflow/cx/WebhookValidateFormParameterIT.java new file mode 100644 index 00000000000..4500e3f9467 --- /dev/null +++ b/dialogflow-cx/src/test/java/dialogflow/cx/WebhookValidateFormParameterIT.java @@ -0,0 +1,106 @@ +/* + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package dialogflow.cx; + +import static com.google.common.truth.Truth.assertThat; +import static org.mockito.Mockito.when; + +import com.google.cloud.dialogflow.cx.v3beta1.WebhookRequest; +import com.google.cloud.dialogflow.cx.v3beta1.WebhookRequest.FulfillmentInfo; +import com.google.cloud.functions.HttpRequest; +import com.google.cloud.functions.HttpResponse; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonArray; +import com.google.gson.JsonObject; +import java.io.BufferedReader; +import java.io.BufferedWriter; +import java.io.IOException; +import java.io.StringReader; +import java.io.StringWriter; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; + +public class WebhookValidateFormParameterIT { + + @Mock HttpRequest request; + @Mock HttpResponse response; + + BufferedReader jsonReader; + StringReader stringReader; + BufferedWriter writerOut; + StringWriter responseOut; + + @Before + public void beforeTest() throws IOException { + MockitoAnnotations.initMocks(this); + + stringReader = new StringReader("{'fulfillmentInfo': {'tag': 'validate-form-parameter'}}"); + jsonReader = new BufferedReader(stringReader); + + responseOut = new StringWriter(); + writerOut = new BufferedWriter(responseOut); + + when(request.getReader()).thenReturn(jsonReader); + when(response.getWriter()).thenReturn(writerOut); + } + + @Test + public void helloHttp_bodyParamsPost() throws IOException, Exception { + FulfillmentInfo fulfillmentInfo = + FulfillmentInfo.newBuilder().setTag("configure-session-parameters").build(); + + WebhookRequest webhookRequest = + WebhookRequest.newBuilder().setFulfillmentInfo(fulfillmentInfo).build(); + + new WebhookValidateFormParameter().service(request, response); + writerOut.flush(); + + JsonObject sessionParameter = new JsonObject(); + sessionParameter.addProperty("order_number", "null"); + + JsonObject sessionInfo = new JsonObject(); + sessionInfo.add("parameters", sessionParameter); + + JsonObject parameterObject = new JsonObject(); + parameterObject.addProperty("display_name", "order_number"); + parameterObject.addProperty("required", "true"); + parameterObject.addProperty("state", "INVALID"); + parameterObject.addProperty("value", "123"); + + JsonArray parameterInfoList = new JsonArray(); + parameterInfoList.add(parameterObject); + + JsonObject parameterInfoObject = new JsonObject(); + parameterInfoObject.add("parameter_info", parameterInfoList); + + JsonObject formInfo = new JsonObject(); + formInfo.add("form_info", parameterInfoObject); + + JsonObject webhookResponse = new JsonObject(); + webhookResponse.add("page_info", formInfo); + webhookResponse.add("session_info", sessionInfo); + + Gson gson = new GsonBuilder().setPrettyPrinting().create(); + String expectedResponse = gson.toJson(webhookResponse); + + assertThat(responseOut.toString()).isEqualTo(expectedResponse); + Thread.sleep(250); + } +}