diff --git a/README.md b/README.md index fc1ab2ef6..67b704b64 100644 --- a/README.md +++ b/README.md @@ -80,37 +80,6 @@ use this Dialogflow CX Client Library. -## Samples - -Samples are in the [`samples/`](https://github.com/googleapis/java-dialogflow-cx/tree/main/samples) directory. - -| Sample | Source Code | Try it | -| --------------------------- | --------------------------------- | ------ | -| Configure Webhook To Set Form Parameters As Optional Or Required | [source code](https://github.com/googleapis/java-dialogflow-cx/blob/main/samples/snippets/src/main/java/dialogflow/cx/ConfigureWebhookToSetFormParametersAsOptionalOrRequired.java) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/java-dialogflow-cx&page=editor&open_in_editor=samples/snippets/src/main/java/dialogflow/cx/ConfigureWebhookToSetFormParametersAsOptionalOrRequired.java) | -| Create Agent | [source code](https://github.com/googleapis/java-dialogflow-cx/blob/main/samples/snippets/src/main/java/dialogflow/cx/CreateAgent.java) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/java-dialogflow-cx&page=editor&open_in_editor=samples/snippets/src/main/java/dialogflow/cx/CreateAgent.java) | -| Create Flow | [source code](https://github.com/googleapis/java-dialogflow-cx/blob/main/samples/snippets/src/main/java/dialogflow/cx/CreateFlow.java) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/java-dialogflow-cx&page=editor&open_in_editor=samples/snippets/src/main/java/dialogflow/cx/CreateFlow.java) | -| Create Intent | [source code](https://github.com/googleapis/java-dialogflow-cx/blob/main/samples/snippets/src/main/java/dialogflow/cx/CreateIntent.java) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/java-dialogflow-cx&page=editor&open_in_editor=samples/snippets/src/main/java/dialogflow/cx/CreateIntent.java) | -| Create Page | [source code](https://github.com/googleapis/java-dialogflow-cx/blob/main/samples/snippets/src/main/java/dialogflow/cx/CreatePage.java) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/java-dialogflow-cx&page=editor&open_in_editor=samples/snippets/src/main/java/dialogflow/cx/CreatePage.java) | -| Create Simple Page | [source code](https://github.com/googleapis/java-dialogflow-cx/blob/main/samples/snippets/src/main/java/dialogflow/cx/CreateSimplePage.java) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/java-dialogflow-cx&page=editor&open_in_editor=samples/snippets/src/main/java/dialogflow/cx/CreateSimplePage.java) | -| Delete Page | [source code](https://github.com/googleapis/java-dialogflow-cx/blob/main/samples/snippets/src/main/java/dialogflow/cx/DeletePage.java) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/java-dialogflow-cx&page=editor&open_in_editor=samples/snippets/src/main/java/dialogflow/cx/DeletePage.java) | -| Detect Intent | [source code](https://github.com/googleapis/java-dialogflow-cx/blob/main/samples/snippets/src/main/java/dialogflow/cx/DetectIntent.java) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/java-dialogflow-cx&page=editor&open_in_editor=samples/snippets/src/main/java/dialogflow/cx/DetectIntent.java) | -| Detect Intent Audio Input | [source code](https://github.com/googleapis/java-dialogflow-cx/blob/main/samples/snippets/src/main/java/dialogflow/cx/DetectIntentAudioInput.java) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/java-dialogflow-cx&page=editor&open_in_editor=samples/snippets/src/main/java/dialogflow/cx/DetectIntentAudioInput.java) | -| Detect Intent Disable Webhook | [source code](https://github.com/googleapis/java-dialogflow-cx/blob/main/samples/snippets/src/main/java/dialogflow/cx/DetectIntentDisableWebhook.java) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/java-dialogflow-cx&page=editor&open_in_editor=samples/snippets/src/main/java/dialogflow/cx/DetectIntentDisableWebhook.java) | -| Detect Intent Event Input | [source code](https://github.com/googleapis/java-dialogflow-cx/blob/main/samples/snippets/src/main/java/dialogflow/cx/DetectIntentEventInput.java) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/java-dialogflow-cx&page=editor&open_in_editor=samples/snippets/src/main/java/dialogflow/cx/DetectIntentEventInput.java) | -| Detect Intent Intent Input | [source code](https://github.com/googleapis/java-dialogflow-cx/blob/main/samples/snippets/src/main/java/dialogflow/cx/DetectIntentIntentInput.java) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/java-dialogflow-cx&page=editor&open_in_editor=samples/snippets/src/main/java/dialogflow/cx/DetectIntentIntentInput.java) | -| Detect Intent Sentiment Analysis | [source code](https://github.com/googleapis/java-dialogflow-cx/blob/main/samples/snippets/src/main/java/dialogflow/cx/DetectIntentSentimentAnalysis.java) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/java-dialogflow-cx&page=editor&open_in_editor=samples/snippets/src/main/java/dialogflow/cx/DetectIntentSentimentAnalysis.java) | -| Detect Intent Stream | [source code](https://github.com/googleapis/java-dialogflow-cx/blob/main/samples/snippets/src/main/java/dialogflow/cx/DetectIntentStream.java) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/java-dialogflow-cx&page=editor&open_in_editor=samples/snippets/src/main/java/dialogflow/cx/DetectIntentStream.java) | -| Detect Intent Streaming Partial Response | [source code](https://github.com/googleapis/java-dialogflow-cx/blob/main/samples/snippets/src/main/java/dialogflow/cx/DetectIntentStreamingPartialResponse.java) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/java-dialogflow-cx&page=editor&open_in_editor=samples/snippets/src/main/java/dialogflow/cx/DetectIntentStreamingPartialResponse.java) | -| Detect Intent Synthesize Text To Speech Output | [source code](https://github.com/googleapis/java-dialogflow-cx/blob/main/samples/snippets/src/main/java/dialogflow/cx/DetectIntentSynthesizeTextToSpeechOutput.java) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/java-dialogflow-cx&page=editor&open_in_editor=samples/snippets/src/main/java/dialogflow/cx/DetectIntentSynthesizeTextToSpeechOutput.java) | -| Export Agent | [source code](https://github.com/googleapis/java-dialogflow-cx/blob/main/samples/snippets/src/main/java/dialogflow/cx/ExportAgent.java) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/java-dialogflow-cx&page=editor&open_in_editor=samples/snippets/src/main/java/dialogflow/cx/ExportAgent.java) | -| List Pages | [source code](https://github.com/googleapis/java-dialogflow-cx/blob/main/samples/snippets/src/main/java/dialogflow/cx/ListPages.java) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/java-dialogflow-cx&page=editor&open_in_editor=samples/snippets/src/main/java/dialogflow/cx/ListPages.java) | -| List Test Case Results | [source code](https://github.com/googleapis/java-dialogflow-cx/blob/main/samples/snippets/src/main/java/dialogflow/cx/ListTestCaseResults.java) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/java-dialogflow-cx&page=editor&open_in_editor=samples/snippets/src/main/java/dialogflow/cx/ListTestCaseResults.java) | -| List Training Phrases | [source code](https://github.com/googleapis/java-dialogflow-cx/blob/main/samples/snippets/src/main/java/dialogflow/cx/ListTrainingPhrases.java) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/java-dialogflow-cx&page=editor&open_in_editor=samples/snippets/src/main/java/dialogflow/cx/ListTrainingPhrases.java) | -| Update Intent | [source code](https://github.com/googleapis/java-dialogflow-cx/blob/main/samples/snippets/src/main/java/dialogflow/cx/UpdateIntent.java) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/java-dialogflow-cx&page=editor&open_in_editor=samples/snippets/src/main/java/dialogflow/cx/UpdateIntent.java) | -| Webhook Configure Session Parameters | [source code](https://github.com/googleapis/java-dialogflow-cx/blob/main/samples/snippets/src/main/java/dialogflow/cx/WebhookConfigureSessionParameters.java) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/java-dialogflow-cx&page=editor&open_in_editor=samples/snippets/src/main/java/dialogflow/cx/WebhookConfigureSessionParameters.java) | -| Webhook Validate Form Parameter | [source code](https://github.com/googleapis/java-dialogflow-cx/blob/main/samples/snippets/src/main/java/dialogflow/cx/WebhookValidateFormParameter.java) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/java-dialogflow-cx&page=editor&open_in_editor=samples/snippets/src/main/java/dialogflow/cx/WebhookValidateFormParameter.java) | - - ## Troubleshooting diff --git a/samples/snippets/pom.xml b/samples/snippets/pom.xml index 940a4006a..6b15bfd74 100644 --- a/samples/snippets/pom.xml +++ b/samples/snippets/pom.xml @@ -2,14 +2,14 @@ 4.0.0 com.google.cloud - dialogflow-cx-snippets + -snippets jar Google Dialogflow CX Snippets https://github.com/googleapis/java-dialogflow-cx com.google.cloud.samples @@ -28,36 +28,15 @@ 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 + 0.17.0 + 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 diff --git a/samples/snippets/resources/book_a_room.wav b/samples/snippets/resources/book_a_room.wav deleted file mode 100644 index 9124e9279..000000000 Binary files a/samples/snippets/resources/book_a_room.wav and /dev/null differ diff --git a/samples/snippets/src/main/java/dialogflow/cx/ConfigureWebhookToSetFormParametersAsOptionalOrRequired.java b/samples/snippets/src/main/java/dialogflow/cx/ConfigureWebhookToSetFormParametersAsOptionalOrRequired.java deleted file mode 100644 index b94c55242..000000000 --- a/samples/snippets/src/main/java/dialogflow/cx/ConfigureWebhookToSetFormParametersAsOptionalOrRequired.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * 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/samples/snippets/src/main/java/dialogflow/cx/CreateAgent.java b/samples/snippets/src/main/java/dialogflow/cx/CreateAgent.java deleted file mode 100644 index 657abed0e..000000000 --- a/samples/snippets/src/main/java/dialogflow/cx/CreateAgent.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * 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/samples/snippets/src/main/java/dialogflow/cx/CreateFlow.java b/samples/snippets/src/main/java/dialogflow/cx/CreateFlow.java deleted file mode 100644 index 1719f1526..000000000 --- a/samples/snippets/src/main/java/dialogflow/cx/CreateFlow.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * 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/samples/snippets/src/main/java/dialogflow/cx/CreateIntent.java b/samples/snippets/src/main/java/dialogflow/cx/CreateIntent.java deleted file mode 100644 index 3469c1848..000000000 --- a/samples/snippets/src/main/java/dialogflow/cx/CreateIntent.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * 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/samples/snippets/src/main/java/dialogflow/cx/CreatePage.java b/samples/snippets/src/main/java/dialogflow/cx/CreatePage.java deleted file mode 100644 index b45bc46f8..000000000 --- a/samples/snippets/src/main/java/dialogflow/cx/CreatePage.java +++ /dev/null @@ -1,116 +0,0 @@ -/* - * 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/samples/snippets/src/main/java/dialogflow/cx/CreateSimplePage.java b/samples/snippets/src/main/java/dialogflow/cx/CreateSimplePage.java deleted file mode 100644 index 26b10e854..000000000 --- a/samples/snippets/src/main/java/dialogflow/cx/CreateSimplePage.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * 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/samples/snippets/src/main/java/dialogflow/cx/DeletePage.java b/samples/snippets/src/main/java/dialogflow/cx/DeletePage.java deleted file mode 100644 index 8403a690a..000000000 --- a/samples/snippets/src/main/java/dialogflow/cx/DeletePage.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * 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/samples/snippets/src/main/java/dialogflow/cx/DetectIntent.java b/samples/snippets/src/main/java/dialogflow/cx/DetectIntent.java deleted file mode 100644 index 3109a4fc5..000000000 --- a/samples/snippets/src/main/java/dialogflow/cx/DetectIntent.java +++ /dev/null @@ -1,105 +0,0 @@ -/* - * 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/samples/snippets/src/main/java/dialogflow/cx/DetectIntentAudioInput.java b/samples/snippets/src/main/java/dialogflow/cx/DetectIntentAudioInput.java deleted file mode 100644 index 36a6a17c7..000000000 --- a/samples/snippets/src/main/java/dialogflow/cx/DetectIntentAudioInput.java +++ /dev/null @@ -1,132 +0,0 @@ -/* - * 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/samples/snippets/src/main/java/dialogflow/cx/DetectIntentDisableWebhook.java b/samples/snippets/src/main/java/dialogflow/cx/DetectIntentDisableWebhook.java deleted file mode 100644 index ee97aabda..000000000 --- a/samples/snippets/src/main/java/dialogflow/cx/DetectIntentDisableWebhook.java +++ /dev/null @@ -1,124 +0,0 @@ -/* - * 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/samples/snippets/src/main/java/dialogflow/cx/DetectIntentEventInput.java b/samples/snippets/src/main/java/dialogflow/cx/DetectIntentEventInput.java deleted file mode 100644 index ccd1fe343..000000000 --- a/samples/snippets/src/main/java/dialogflow/cx/DetectIntentEventInput.java +++ /dev/null @@ -1,102 +0,0 @@ -/* - * 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/samples/snippets/src/main/java/dialogflow/cx/DetectIntentIntentInput.java b/samples/snippets/src/main/java/dialogflow/cx/DetectIntentIntentInput.java deleted file mode 100644 index a0e89547d..000000000 --- a/samples/snippets/src/main/java/dialogflow/cx/DetectIntentIntentInput.java +++ /dev/null @@ -1,104 +0,0 @@ -/* - * 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/samples/snippets/src/main/java/dialogflow/cx/DetectIntentSentimentAnalysis.java b/samples/snippets/src/main/java/dialogflow/cx/DetectIntentSentimentAnalysis.java deleted file mode 100644 index f69331bbf..000000000 --- a/samples/snippets/src/main/java/dialogflow/cx/DetectIntentSentimentAnalysis.java +++ /dev/null @@ -1,121 +0,0 @@ -/* - * 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/samples/snippets/src/main/java/dialogflow/cx/DetectIntentStream.java b/samples/snippets/src/main/java/dialogflow/cx/DetectIntentStream.java deleted file mode 100644 index f1d05491e..000000000 --- a/samples/snippets/src/main/java/dialogflow/cx/DetectIntentStream.java +++ /dev/null @@ -1,151 +0,0 @@ -/* - * 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/samples/snippets/src/main/java/dialogflow/cx/DetectIntentStreamingPartialResponse.java b/samples/snippets/src/main/java/dialogflow/cx/DetectIntentStreamingPartialResponse.java deleted file mode 100644 index af7258043..000000000 --- a/samples/snippets/src/main/java/dialogflow/cx/DetectIntentStreamingPartialResponse.java +++ /dev/null @@ -1,158 +0,0 @@ -/* - * 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/samples/snippets/src/main/java/dialogflow/cx/DetectIntentSynthesizeTextToSpeechOutput.java b/samples/snippets/src/main/java/dialogflow/cx/DetectIntentSynthesizeTextToSpeechOutput.java deleted file mode 100644 index 74c155f4d..000000000 --- a/samples/snippets/src/main/java/dialogflow/cx/DetectIntentSynthesizeTextToSpeechOutput.java +++ /dev/null @@ -1,135 +0,0 @@ -/* - * 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/samples/snippets/src/main/java/dialogflow/cx/ExportAgent.java b/samples/snippets/src/main/java/dialogflow/cx/ExportAgent.java deleted file mode 100644 index 6b431f510..000000000 --- a/samples/snippets/src/main/java/dialogflow/cx/ExportAgent.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * 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/samples/snippets/src/main/java/dialogflow/cx/ListPages.java b/samples/snippets/src/main/java/dialogflow/cx/ListPages.java deleted file mode 100644 index 9a180081f..000000000 --- a/samples/snippets/src/main/java/dialogflow/cx/ListPages.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * 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/samples/snippets/src/main/java/dialogflow/cx/ListTestCaseResults.java b/samples/snippets/src/main/java/dialogflow/cx/ListTestCaseResults.java deleted file mode 100644 index 2f34d6530..000000000 --- a/samples/snippets/src/main/java/dialogflow/cx/ListTestCaseResults.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * 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/samples/snippets/src/main/java/dialogflow/cx/ListTrainingPhrases.java b/samples/snippets/src/main/java/dialogflow/cx/ListTrainingPhrases.java deleted file mode 100644 index 425753051..000000000 --- a/samples/snippets/src/main/java/dialogflow/cx/ListTrainingPhrases.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * 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_list_training_phrases] -import com.google.cloud.dialogflow.cx.v3.GetIntentRequest; -import com.google.cloud.dialogflow.cx.v3.Intent; -import com.google.cloud.dialogflow.cx.v3.IntentName; -import com.google.cloud.dialogflow.cx.v3.IntentsClient; -import java.io.IOException; -import java.util.List; - -public class ListTrainingPhrases { - public static void main(String[] args) throws IOException { - // TODO(developer): Replace these variables before running the sample. - String projectId = "my-project-id"; - String location = "location"; - String agentId = "my-agent-id"; - String intentId = "my-intent-id"; - - listTrainingPhrases(projectId, location, agentId, intentId); - } - - // DialogFlow API List Training Phrases sample. - public static void listTrainingPhrases( - String projectId, String location, String agentId, String intentId) 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()) { - // Set the intent name - IntentName name = IntentName.of(projectId, location, agentId, intentId); - - // Compose the get-intent request - GetIntentRequest request = GetIntentRequest.newBuilder().setName(name.toString()).build(); - - // Make API request to get intent - Intent response = client.getIntent(request); - - // Loop through the results - for (Intent.TrainingPhrase phrase : response.getTrainingPhrasesList()) { - System.out.println("***********************************************"); - List parts = phrase.getPartsList(); - for (Intent.TrainingPhrase.Part part : parts) { - System.out.println(String.format("Training Phrase: %s", part.getText())); - } - } - } - } -} -// [END dialogflow_list_training_phrases] diff --git a/samples/snippets/src/main/java/dialogflow/cx/UpdateIntent.java b/samples/snippets/src/main/java/dialogflow/cx/UpdateIntent.java deleted file mode 100644 index ea16649f6..000000000 --- a/samples/snippets/src/main/java/dialogflow/cx/UpdateIntent.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * 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/samples/snippets/src/main/java/dialogflow/cx/WebhookConfigureSessionParameters.java b/samples/snippets/src/main/java/dialogflow/cx/WebhookConfigureSessionParameters.java deleted file mode 100644 index 2d59a8ba7..000000000 --- a/samples/snippets/src/main/java/dialogflow/cx/WebhookConfigureSessionParameters.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * 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/samples/snippets/src/main/java/dialogflow/cx/WebhookValidateFormParameter.java b/samples/snippets/src/main/java/dialogflow/cx/WebhookValidateFormParameter.java deleted file mode 100644 index 320b57f3d..000000000 --- a/samples/snippets/src/main/java/dialogflow/cx/WebhookValidateFormParameter.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * 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/samples/snippets/src/test/java/dialogflow/cx/ConfigureWebhookToSetFormParametersAsOptionalOrRequiredIT.java b/samples/snippets/src/test/java/dialogflow/cx/ConfigureWebhookToSetFormParametersAsOptionalOrRequiredIT.java deleted file mode 100644 index 53e30e094..000000000 --- a/samples/snippets/src/test/java/dialogflow/cx/ConfigureWebhookToSetFormParametersAsOptionalOrRequiredIT.java +++ /dev/null @@ -1,101 +0,0 @@ -/* - * 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/samples/snippets/src/test/java/dialogflow/cx/CreateAgentIT.java b/samples/snippets/src/test/java/dialogflow/cx/CreateAgentIT.java deleted file mode 100644 index aee80c7de..000000000 --- a/samples/snippets/src/test/java/dialogflow/cx/CreateAgentIT.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * 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/samples/snippets/src/test/java/dialogflow/cx/CreateFlowIT.java b/samples/snippets/src/test/java/dialogflow/cx/CreateFlowIT.java deleted file mode 100644 index 7bbe9de68..000000000 --- a/samples/snippets/src/test/java/dialogflow/cx/CreateFlowIT.java +++ /dev/null @@ -1,108 +0,0 @@ -/* - * 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/samples/snippets/src/test/java/dialogflow/cx/CreateIntentIT.java b/samples/snippets/src/test/java/dialogflow/cx/CreateIntentIT.java deleted file mode 100644 index 6f317122f..000000000 --- a/samples/snippets/src/test/java/dialogflow/cx/CreateIntentIT.java +++ /dev/null @@ -1,107 +0,0 @@ -/* - * 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/samples/snippets/src/test/java/dialogflow/cx/CreatePageIT.java b/samples/snippets/src/test/java/dialogflow/cx/CreatePageIT.java deleted file mode 100644 index b392be98c..000000000 --- a/samples/snippets/src/test/java/dialogflow/cx/CreatePageIT.java +++ /dev/null @@ -1,108 +0,0 @@ -/* - * 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/samples/snippets/src/test/java/dialogflow/cx/DetectIntentAudioInputTest.java b/samples/snippets/src/test/java/dialogflow/cx/DetectIntentAudioInputTest.java deleted file mode 100644 index ffe361914..000000000 --- a/samples/snippets/src/test/java/dialogflow/cx/DetectIntentAudioInputTest.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * 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/samples/snippets/src/test/java/dialogflow/cx/DetectIntentDisableWebhookTest.java b/samples/snippets/src/test/java/dialogflow/cx/DetectIntentDisableWebhookTest.java deleted file mode 100644 index 3564ed1cc..000000000 --- a/samples/snippets/src/test/java/dialogflow/cx/DetectIntentDisableWebhookTest.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * 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/samples/snippets/src/test/java/dialogflow/cx/DetectIntentEventInputTest.java b/samples/snippets/src/test/java/dialogflow/cx/DetectIntentEventInputTest.java deleted file mode 100644 index f63625194..000000000 --- a/samples/snippets/src/test/java/dialogflow/cx/DetectIntentEventInputTest.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * 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/samples/snippets/src/test/java/dialogflow/cx/DetectIntentIT.java b/samples/snippets/src/test/java/dialogflow/cx/DetectIntentIT.java deleted file mode 100644 index 66d356a9b..000000000 --- a/samples/snippets/src/test/java/dialogflow/cx/DetectIntentIT.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * 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/samples/snippets/src/test/java/dialogflow/cx/DetectIntentIntentInputTest.java b/samples/snippets/src/test/java/dialogflow/cx/DetectIntentIntentInputTest.java deleted file mode 100644 index 51dc3a560..000000000 --- a/samples/snippets/src/test/java/dialogflow/cx/DetectIntentIntentInputTest.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * 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/samples/snippets/src/test/java/dialogflow/cx/DetectIntentSentimentAnalysisTest.java b/samples/snippets/src/test/java/dialogflow/cx/DetectIntentSentimentAnalysisTest.java deleted file mode 100644 index 2194a9e70..000000000 --- a/samples/snippets/src/test/java/dialogflow/cx/DetectIntentSentimentAnalysisTest.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * 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/samples/snippets/src/test/java/dialogflow/cx/DetectIntentStreamIT.java b/samples/snippets/src/test/java/dialogflow/cx/DetectIntentStreamIT.java deleted file mode 100644 index b941420f0..000000000 --- a/samples/snippets/src/test/java/dialogflow/cx/DetectIntentStreamIT.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * 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/samples/snippets/src/test/java/dialogflow/cx/DetectIntentStreamingPartialResponseTest.java b/samples/snippets/src/test/java/dialogflow/cx/DetectIntentStreamingPartialResponseTest.java deleted file mode 100644 index 7f6f24a2e..000000000 --- a/samples/snippets/src/test/java/dialogflow/cx/DetectIntentStreamingPartialResponseTest.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * 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/samples/snippets/src/test/java/dialogflow/cx/DetectIntentSynthesizeTextToSpeechOutputTest.java b/samples/snippets/src/test/java/dialogflow/cx/DetectIntentSynthesizeTextToSpeechOutputTest.java deleted file mode 100644 index 20d84e37a..000000000 --- a/samples/snippets/src/test/java/dialogflow/cx/DetectIntentSynthesizeTextToSpeechOutputTest.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * 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/samples/snippets/src/test/java/dialogflow/cx/ExportAgentIT.java b/samples/snippets/src/test/java/dialogflow/cx/ExportAgentIT.java deleted file mode 100644 index e499fe726..000000000 --- a/samples/snippets/src/test/java/dialogflow/cx/ExportAgentIT.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - * 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/samples/snippets/src/test/java/dialogflow/cx/ListTestCaseResultsIT.java b/samples/snippets/src/test/java/dialogflow/cx/ListTestCaseResultsIT.java deleted file mode 100644 index 2214356f1..000000000 --- a/samples/snippets/src/test/java/dialogflow/cx/ListTestCaseResultsIT.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * 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/samples/snippets/src/test/java/dialogflow/cx/ListTrainingPhrasesTest.java b/samples/snippets/src/test/java/dialogflow/cx/ListTrainingPhrasesTest.java deleted file mode 100644 index 347b39804..000000000 --- a/samples/snippets/src/test/java/dialogflow/cx/ListTrainingPhrasesTest.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * 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 ListTrainingPhrasesTest { - private static String PROJECT_ID = System.getenv().get("GOOGLE_CLOUD_PROJECT"); - private static String LOCATION = "global"; - private static String AGENT_ID = "b8d0e85d-0741-4e6d-a66a-3671184b7b93"; - private static String INTENT_ID = "e2d688a6-c8b4-448e-a7d6-208f147ae689"; - - private ByteArrayOutputStream stdOut; - - @Before - public void setUp() throws IOException { - stdOut = new ByteArrayOutputStream(); - System.setOut(new PrintStream(stdOut)); - } - - @After - public void tearDown() throws IOException, InterruptedException { - stdOut = null; - System.setOut(null); - - // Small delay to prevent reaching quota limit of requests per minute - Thread.sleep(250); - } - - @Test - public void testListTrainingPhrases() throws IOException { - ListTrainingPhrases.listTrainingPhrases(PROJECT_ID, LOCATION, AGENT_ID, INTENT_ID); - assertThat(stdOut.toString()).contains("green"); - } -} diff --git a/samples/snippets/src/test/java/dialogflow/cx/PageManagementIT.java b/samples/snippets/src/test/java/dialogflow/cx/PageManagementIT.java deleted file mode 100644 index 47c100107..000000000 --- a/samples/snippets/src/test/java/dialogflow/cx/PageManagementIT.java +++ /dev/null @@ -1,117 +0,0 @@ -/* - * 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/samples/snippets/src/test/java/dialogflow/cx/UpdateIntentTest.java b/samples/snippets/src/test/java/dialogflow/cx/UpdateIntentTest.java deleted file mode 100644 index 635b16b78..000000000 --- a/samples/snippets/src/test/java/dialogflow/cx/UpdateIntentTest.java +++ /dev/null @@ -1,106 +0,0 @@ -/* - * 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/samples/snippets/src/test/java/dialogflow/cx/WebhookConfigureSessionParametersIT.java b/samples/snippets/src/test/java/dialogflow/cx/WebhookConfigureSessionParametersIT.java deleted file mode 100644 index 9c1d2a719..000000000 --- a/samples/snippets/src/test/java/dialogflow/cx/WebhookConfigureSessionParametersIT.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * 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/samples/snippets/src/test/java/dialogflow/cx/WebhookValidateFormParameterIT.java b/samples/snippets/src/test/java/dialogflow/cx/WebhookValidateFormParameterIT.java deleted file mode 100644 index 4500e3f94..000000000 --- a/samples/snippets/src/test/java/dialogflow/cx/WebhookValidateFormParameterIT.java +++ /dev/null @@ -1,106 +0,0 @@ -/* - * 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); - } -}