├── .circleci └── config.yml ├── .gitignore ├── LICENSE ├── README.md └── samples ├── README.md ├── pom.xml ├── resources ├── 230pm.wav ├── RoomReservation.zip ├── book_a_room.wav ├── half_an_hour.wav ├── mountain_view.wav ├── today.wav └── two_people.wav └── src ├── main └── java │ └── com │ └── example │ └── dialogflow │ ├── ContextManagement.java │ ├── DetectIntentAudio.java │ ├── DetectIntentKnowledge.java │ ├── DetectIntentSentimentAnalysis.java │ ├── DetectIntentStream.java │ ├── DetectIntentTTSResponses.java │ ├── DetectIntentTexts.java │ ├── DetectIntentWithModelSelection.java │ ├── DocumentManagement.java │ ├── EntityManagement.java │ ├── EntityTypeManagement.java │ ├── IntentManagement.java │ ├── KnowledgebaseManagement.java │ └── SessionEntityTypeManagement.java └── test └── java └── com └── example └── dialogflow ├── ContextManagementIT.java ├── CreateDeleteEntityIT.java ├── DetectIntentAudioIT.java ├── DetectIntentSentimentAnalysisIT.java ├── DetectIntentStreamIT.java ├── DetectIntentTTSResponsesIT.java ├── DetectIntentTextsIT.java ├── DetectIntentWithModelSelectionIT.java ├── IntentManagementIT.java ├── KnowledgeBaseIT.java └── SessionEntityTypeIT.java /.circleci/config.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | jobs: 3 | sample_integration_test: 4 | working_directory: ~/dialogflow-java 5 | docker: 6 | - image: circleci/openjdk:8-jdk-browsers 7 | steps: 8 | - checkout 9 | - run: 10 | name: Create Google Application Credential file 11 | command: | 12 | echo ${GOOGLE_APPLICATION_CREDENTIALS_CONTENT} > /tmp/key.json 13 | - run: 14 | name: Run integration test 15 | environment: 16 | GCLOUD_PROJECT: ${GCLOUD_PROJECT} 17 | GOOGLE_APPLICATION_CREDENTIALS: /tmp/key.json 18 | command: | 19 | cd samples 20 | mvn clean verify 21 | - run: 22 | name: Delete Google Application Credential file 23 | when: always 24 | command: | 25 | rm /tmp/key.json 26 | - store_test_results: 27 | path: samples/target/failsafe-reports 28 | workflows: 29 | version: 2 30 | sample_build_integration_test: 31 | jobs: 32 | - sample_integration_test: 33 | filters: 34 | branches: 35 | only: 36 | - master 37 | - circleci-config 38 | - dialogflow-ci-integration 39 | tags: 40 | only: /^v[\d.]+$/ -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Google App Engine generated folder 2 | appengine-generated/ 3 | 4 | # Java 5 | *.class 6 | 7 | # Mobile Tools for Java (J2ME) 8 | .mtj.tmp/ 9 | 10 | # Package Files # 11 | *.jar 12 | *.war 13 | *.ear 14 | 15 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 16 | hs_err_pid* 17 | 18 | # maven 19 | target/ 20 | pom.xml.tag 21 | pom.xml.releaseBackup 22 | pom.xml.versionsBackup 23 | pom.xml.next 24 | release.properties 25 | dependency-reduced-pom.xml 26 | buildNumber.properties 27 | 28 | # Secrets 29 | service-account.json 30 | secrets.env 31 | 32 | # intellij 33 | .idea/ 34 | *.iml 35 | 36 | # Eclipse files 37 | .project 38 | .classpath 39 | .settings 40 | 41 | # vim 42 | [._]*.s[a-w][a-z] 43 | [._]s[a-w][a-z] 44 | Session.vim 45 | .netrwhist 46 | *~ 47 | tags 48 | 49 | # Gradle 50 | out/ 51 | 52 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Dialogflow 2 | 3 | [Dialogflow](https://dialogflow.com/) is an enterprise-grade NLU platform that makes it easy for 4 | developers to design and integrate conversational user interfaces int 5 | mobile apps, web applications, devices, and bots. 6 | 7 | The client library can be found in the [google-cloud-java](https://github.com/GoogleCloudPlatform/google-cloud-java) repository and can be found directly at [google-cloud-dialogflow](https://github.com/GoogleCloudPlatform/google-cloud-java/tree/master/google-cloud-clients/google-cloud-dialogflow) -------------------------------------------------------------------------------- /samples/README.md: -------------------------------------------------------------------------------- 1 | # Dialogflow API Java examples 2 | 3 | These samples demonstrate the use of the [Dialogflow API][dialogflow]. 4 | 5 | These samples show how to detect intents with text, audio, and streaming audio. 6 | 7 | These samples show how to manage contexts, entities, entity types, and intents 8 | 9 | [dialogflow]: https://dialogflow.com/docs/getting-started/basics 10 | [google-cloud-java]: https://github.com/GoogleCloudPlatform/google-cloud-java 11 | 12 | ## Java Version 13 | 14 | This sample requires you to have 15 | [Java8](https://docs.oracle.com/javase/8/docs/technotes/guides/install/install_overview.html). 16 | 17 | ### Download Maven 18 | 19 | To get started, [download][maven-download] and [install][maven-install] it. 20 | 21 | [maven]: https://maven.apache.org 22 | [maven-download]: https://maven.apache.org/download.cgi 23 | [maven-install]: https://maven.apache.org/install.html 24 | 25 | ### Setup 26 | 27 | * Create a project with the [Google Cloud Console][cloud-console], and enable 28 | the [Dialogflow API][dialogflow-api]. 29 | * [Set up][auth] authentication. For 30 | example, from the Cloud Console, create a service account, 31 | download its json credentials file, then set the appropriate environment 32 | variable: 33 | 34 | ```bash 35 | export GOOGLE_APPLICATION_CREDENTIALS=/path/to/your-project-credentials.json 36 | ``` 37 | * To run tests, set GOOGLE_CLOUD_PROJECT to your PROJECT_ID: 38 | ``` 39 | export GOOGLE_CLOUD_PROJECT=PROJECT_ID 40 | ``` 41 | ``` 42 | mvn clean verify 43 | ``` 44 | * Set PROJECT_ID in pom.xml to your Google Cloud Project Id. 45 | * Set SESSION_ID in pom.xml to a session name of your choice. (Defaults to SESSION_ID) 46 | * Set CONTEXT_ID in pom.xml to a context name of your choice. (Defaults to CONTEXT_ID) 47 | 48 | [cloud-console]: https://console.cloud.google.com 49 | [dialogflow-api]: https://console.cloud.google.com/apis/library/dialogflow.googleapis.com 50 | [auth]: https://cloud.google.com/docs/authentication/getting-started 51 | 52 | ## Run the sample 53 | 54 | To build the sample, we use Maven. 55 | 56 | ```bash 57 | mvn clean package 58 | ``` 59 | 60 | ### Set up the Agent 61 | Import the sample agent (RoomReservation.zip) from the resources directory to your 62 | [Dialogflow Project][dialogflow-import] using the following guide: 63 | [Versioning with Import/Export][import-export-versioning] 64 | 65 | [dialogflow-import]: https://console.dialogflow.com/api-client/#/editAgent/ 66 | [import-export-versioning]: https://dialogflow.com/docs/best-practices/import-export-for-versions 67 | 68 | ## Samples 69 | 70 | ### Detect Intent Texts 71 | DialogFlow API Detect Intent sample with text inputs. 72 | 73 | ``` 74 | mvn exec:java -DDetectIntentTexts 75 | ``` 76 | 77 | ### Detect Intent Audio 78 | DialogFlow API Detect Intent sample with audio files. Returns the result of detect intent with an 79 | audio file as input. 80 | 81 | Note: Execute the following commands in order to yield reasonable outputs. 82 | ``` 83 | mvn exec:java -DDetectIntentAudioBookARoom 84 | ``` 85 | ``` 86 | mvn exec:java -DDetectIntentAudioMountainView 87 | ``` 88 | ``` 89 | mvn exec:java -DDetectIntentAudioToday 90 | ``` 91 | ``` 92 | mvn exec:java -DDetectIntentAudio230PM 93 | ``` 94 | ``` 95 | mvn exec:java -DDetectIntentAudioHalfAnHour 96 | ``` 97 | ``` 98 | mvn exec:java -DDetectIntentAudioTwoPeople 99 | ``` 100 | 101 | ### Detect Intent Stream 102 | DialogFlow API Detect Intent sample with audio files processes as an audio stream. 103 | 104 | ``` 105 | mvn exec:java -DDetectIntentStreamBookARoom 106 | ``` 107 | ``` 108 | mvn exec:java -DDetectIntentStreamMountainView 109 | ``` 110 | 111 | ### Context Management 112 | DialogFlow API Context sample. 113 | 114 | Lists contexts 115 | ``` 116 | mvn exec:java -DContextManagementList 117 | ``` 118 | Create an entity type 119 | ``` 120 | mvn exec:java -DContextManagementCreate 121 | ``` 122 | Delete entity type 123 | ``` 124 | mvn exec:java -DContextManagementDelete 125 | ``` 126 | 127 | ### Entity Management 128 | DialogFlow API Entity sample. 129 | 130 | List entities 131 | ``` 132 | mvn exec:java -DEntityManagementList 133 | ``` 134 | Create an entity 135 | ``` 136 | mvn exec:java -DEntityManagementCreate 137 | ``` 138 | Delete entity 139 | ``` 140 | mvn exec:java -DEntityManagementDelete 141 | ``` 142 | 143 | ### Entity Type Management 144 | DialogFlow API EntityType sample. 145 | 146 | List entity types 147 | ``` 148 | mvn exec:java -DEntityTypeManagementList 149 | ``` 150 | Create an entity type 151 | ``` 152 | mvn exec:java -DEntityTypeManagementCreate 153 | ``` 154 | Delete entity type 155 | ``` 156 | mvn exec:java -DEntityTypeManagementDelete 157 | ``` 158 | 159 | ### Intent Management 160 | DialogFlow API Intent sample. 161 | 162 | List intents 163 | ``` 164 | mvn exec:java -DIntentManagementList 165 | ``` 166 | Create an intent 167 | ``` 168 | mvn exec:java -DIntentManagementCreate 169 | ``` 170 | Delete intent 171 | ``` 172 | mvn exec:java -DIntentManagementDelete 173 | ``` 174 | 175 | ### Session Entity Type Management 176 | DialogFlow API SessionEntityType sample. 177 | 178 | List session entity types 179 | ``` 180 | mvn exec:java -DSessionEntityTypeManagementList 181 | ``` 182 | Create session entity type 183 | ``` 184 | mvn exec:java -DSessionEntityTypeManagementCreate 185 | ``` 186 | Delete session entity type 187 | ``` 188 | mvn exec:java -DSessionEntityTypeManagementDelete 189 | ``` 190 | -------------------------------------------------------------------------------- /samples/resources/230pm.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dialogflow/dialogflow-java-client-v2/3cbacec43fa30f3ff0779a94cb1a528ce3e014c0/samples/resources/230pm.wav -------------------------------------------------------------------------------- /samples/resources/RoomReservation.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dialogflow/dialogflow-java-client-v2/3cbacec43fa30f3ff0779a94cb1a528ce3e014c0/samples/resources/RoomReservation.zip -------------------------------------------------------------------------------- /samples/resources/book_a_room.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dialogflow/dialogflow-java-client-v2/3cbacec43fa30f3ff0779a94cb1a528ce3e014c0/samples/resources/book_a_room.wav -------------------------------------------------------------------------------- /samples/resources/half_an_hour.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dialogflow/dialogflow-java-client-v2/3cbacec43fa30f3ff0779a94cb1a528ce3e014c0/samples/resources/half_an_hour.wav -------------------------------------------------------------------------------- /samples/resources/mountain_view.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dialogflow/dialogflow-java-client-v2/3cbacec43fa30f3ff0779a94cb1a528ce3e014c0/samples/resources/mountain_view.wav -------------------------------------------------------------------------------- /samples/resources/today.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dialogflow/dialogflow-java-client-v2/3cbacec43fa30f3ff0779a94cb1a528ce3e014c0/samples/resources/today.wav -------------------------------------------------------------------------------- /samples/resources/two_people.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dialogflow/dialogflow-java-client-v2/3cbacec43fa30f3ff0779a94cb1a528ce3e014c0/samples/resources/two_people.wav -------------------------------------------------------------------------------- /samples/src/main/java/com/example/dialogflow/ContextManagement.java: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2017, Google, Inc. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package com.example.dialogflow; 18 | 19 | // [START dialogflow_import_libraries] 20 | // Imports the Google Cloud client library 21 | import com.google.cloud.dialogflow.v2.Context; 22 | import com.google.cloud.dialogflow.v2.ContextName; 23 | import com.google.cloud.dialogflow.v2.ContextsClient; 24 | import com.google.cloud.dialogflow.v2.SessionName; 25 | import com.google.protobuf.Value; 26 | 27 | import java.util.Map.Entry; 28 | // [END dialogflow_import_libraries] 29 | 30 | /** 31 | * DialogFlow API Context sample. 32 | */ 33 | public class ContextManagement { 34 | 35 | /** 36 | * Lists contexts 37 | * @param sessionId Identifier of the DetectIntent session. 38 | * @param projectId Project/Agent Id. 39 | */ 40 | public static void listContexts(String sessionId, String projectId) throws Exception { 41 | // Instantiates a client 42 | try (ContextsClient contextsClient = ContextsClient.create()) { 43 | // Set the session name using the sessionId (UUID) and projectId (my-project-id) 44 | SessionName session = SessionName.of(projectId, sessionId); 45 | 46 | // Performs the list contexts request 47 | System.out.format("Contexts for session %s:\n", session.toString()); 48 | for (Context context : contextsClient.listContexts(session).iterateAll()) { 49 | System.out.format("Context name: %s\n", context.getName()); 50 | System.out.format("Lifespan Count: %d\n", context.getLifespanCount()); 51 | System.out.format("Fields:\n"); 52 | for (Entry entry : context.getParameters().getFieldsMap().entrySet()) { 53 | if (entry.getValue().hasStructValue()) { 54 | System.out.format("\t%s: %s\n", entry.getKey(), entry.getValue()); 55 | } 56 | } 57 | } 58 | } 59 | } 60 | 61 | // [START dialogflow_create_context] 62 | /** 63 | * Create an entity type with the given display name 64 | * @param contextId The Id of the context. 65 | * @param sessionId Identifier of the DetectIntent session. 66 | * @param lifespanCount The lifespan count of the context. 67 | * @param projectId Project/Agent Id. 68 | */ 69 | public static void createContext(String contextId, String sessionId, String projectId, 70 | int lifespanCount) throws Exception { 71 | // Instantiates a client 72 | try (ContextsClient contextsClient = ContextsClient.create()) { 73 | // Set the session name using the sessionId (UUID) and projectID (my-project-id) 74 | SessionName session = SessionName.of(projectId, sessionId); 75 | 76 | // Create the context name with the projectId, sessionId, and contextId 77 | ContextName contextName = ContextName.newBuilder() 78 | .setProject(projectId) 79 | .setSession(sessionId) 80 | .setContext(contextId) 81 | .build(); 82 | 83 | // Create the context with the context name and lifespan count 84 | Context context = Context.newBuilder() 85 | .setName(contextName.toString()) // The unique identifier of the context 86 | .setLifespanCount(lifespanCount) // Number of query requests before the context expires. 87 | .build(); 88 | 89 | // Performs the create context request 90 | Context response = contextsClient.createContext(session, context); 91 | System.out.format("Context created: %s\n", response); 92 | } 93 | } 94 | // [END dialogflow_create_context] 95 | 96 | // [START dialogflow_delete_context] 97 | /** 98 | * Delete entity type with the given entity type name 99 | * @param contextId The Id of the context. 100 | * @param sessionId Identifier of the DetectIntent session. 101 | * @param projectId Project/Agent Id. 102 | */ 103 | public static void deleteContext(String contextId, String sessionId, String projectId) 104 | throws Exception { 105 | // Instantiates a client 106 | try (ContextsClient contextsClient = ContextsClient.create()) { 107 | // Create the context name with the projectId, sessionId, and contextId 108 | ContextName contextName = ContextName.of(projectId, sessionId, contextId); 109 | // Performs the delete context request 110 | contextsClient.deleteContext(contextName); 111 | } 112 | } 113 | // [END dialogflow_delete_context] 114 | 115 | // [START run_application] 116 | public static void main(String[] args) throws Exception { 117 | String method = ""; 118 | String sessionId = ""; 119 | String contextId = ""; 120 | int lifeSpanCount = 1; 121 | String projectId = ""; 122 | 123 | try { 124 | method = args[0]; 125 | String command = args[1]; 126 | if (method.equals("list")) { 127 | if (command.equals("--sessionId")) { 128 | sessionId = args[2]; 129 | } 130 | 131 | command = args[3]; 132 | if (command.equals("--projectId")) { 133 | projectId = args[4]; 134 | } 135 | } else if (method.equals("create") || method.equals("delete")) { 136 | if (command.equals("--sessionId")) { 137 | sessionId = args[2]; 138 | } 139 | 140 | command = args[3]; 141 | if (command.equals("--projectId")) { 142 | projectId = args[4]; 143 | } 144 | 145 | command = args[5]; 146 | if (command.equals("--contextId")) { 147 | contextId = args[6]; 148 | } 149 | 150 | if (method.equals("create") && args.length > 7) { 151 | command = args[7]; 152 | if (command.equals("--lifespanCount")) { 153 | lifeSpanCount = Integer.valueOf(args[8]); 154 | } 155 | } 156 | } 157 | } catch (Exception e) { 158 | System.out.println("Usage:"); 159 | System.out.println("mvn exec:java -DContextManagement " 160 | + "-Dexec.args='list --sessionId SESSION_ID --projectId PROJECT_ID'\n"); 161 | 162 | System.out.println("mvn exec:java -DContextManagement " 163 | + "-Dexec.args='create --sessionId SESSION_ID --projectId PROJECT_ID " 164 | + "--contextId CONTEXT_ID'\n"); 165 | 166 | System.out.println("mvn exec:java -DContextManagement " 167 | + "-Dexec.args='delete --sessionId SESSION_ID --projectId PROJECT_ID " 168 | + "--contextId CONTEXT_ID'\n"); 169 | 170 | System.out.println("Commands: list | delete"); 171 | System.out.println("\t--sessionId - Identifier of the DetectIntent session"); 172 | System.out.println("\t--projectId - Project/Agent Id"); 173 | System.out.println("\nCommands: create"); 174 | System.out.println("\t--sessionId - Identifier of the DetectIntent session"); 175 | System.out.println("\t--projectId - Project/Agent Id"); 176 | System.out.println("\t--contextId - The Id of the context"); 177 | System.out.println("\nOptional Commands [For create]:"); 178 | System.out.println("\t--lifespanCount - The lifespan count of the context " 179 | + "(Defaults to 1.)"); 180 | } 181 | 182 | if (method.equals("list")) { 183 | listContexts(sessionId, projectId); 184 | } else if (method.equals("create")) { 185 | createContext(contextId, sessionId, projectId, lifeSpanCount); 186 | } else if (method.equals("delete")) { 187 | deleteContext(contextId, sessionId, projectId); 188 | } 189 | } 190 | // [END run_application] 191 | } 192 | -------------------------------------------------------------------------------- /samples/src/main/java/com/example/dialogflow/DetectIntentAudio.java: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2017, Google, Inc. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package com.example.dialogflow; 18 | 19 | // [START dialogflow_import_libraries] 20 | // Imports the Google Cloud client library 21 | import com.google.cloud.dialogflow.v2.AudioEncoding; 22 | import com.google.cloud.dialogflow.v2.DetectIntentRequest; 23 | import com.google.cloud.dialogflow.v2.DetectIntentResponse; 24 | import com.google.cloud.dialogflow.v2.InputAudioConfig; 25 | import com.google.cloud.dialogflow.v2.QueryInput; 26 | import com.google.cloud.dialogflow.v2.QueryResult; 27 | import com.google.cloud.dialogflow.v2.SessionName; 28 | import com.google.cloud.dialogflow.v2.SessionsClient; 29 | import com.google.protobuf.ByteString; 30 | 31 | import java.nio.file.Files; 32 | import java.nio.file.Paths; 33 | import java.util.UUID; 34 | // [END dialogflow_import_libraries] 35 | 36 | 37 | /** 38 | * DialogFlow API Detect Intent sample with audio files. 39 | */ 40 | public class DetectIntentAudio { 41 | 42 | // [START dialogflow_detect_intent_audio] 43 | /** 44 | * Returns the result of detect intent with an audio file as input. 45 | * 46 | * Using the same `session_id` between requests allows continuation of the conversation. 47 | * @param projectId Project/Agent Id. 48 | * @param audioFilePath Path to the audio file. 49 | * @param sessionId Identifier of the DetectIntent session. 50 | * @param languageCode Language code of the query. 51 | */ 52 | public static void detectIntentAudio(String projectId, String audioFilePath, String sessionId, 53 | String languageCode) 54 | throws Exception { 55 | // Instantiates a client 56 | try (SessionsClient sessionsClient = SessionsClient.create()) { 57 | // Set the session name using the sessionId (UUID) and projectID (my-project-id) 58 | SessionName session = SessionName.of(projectId, sessionId); 59 | System.out.println("Session Path: " + session.toString()); 60 | 61 | // Note: hard coding audioEncoding and sampleRateHertz for simplicity. 62 | // Audio encoding of the audio content sent in the query request. 63 | AudioEncoding audioEncoding = AudioEncoding.AUDIO_ENCODING_LINEAR_16; 64 | int sampleRateHertz = 16000; 65 | 66 | // Instructs the speech recognizer how to process the audio content. 67 | InputAudioConfig inputAudioConfig = InputAudioConfig.newBuilder() 68 | .setAudioEncoding(audioEncoding) // audioEncoding = AudioEncoding.AUDIO_ENCODING_LINEAR_16 69 | .setLanguageCode(languageCode) // languageCode = "en-US" 70 | .setSampleRateHertz(sampleRateHertz) // sampleRateHertz = 16000 71 | .build(); 72 | 73 | // Build the query with the InputAudioConfig 74 | QueryInput queryInput = QueryInput.newBuilder().setAudioConfig(inputAudioConfig).build(); 75 | 76 | // Read the bytes from the audio file 77 | byte[] inputAudio = Files.readAllBytes(Paths.get(audioFilePath)); 78 | 79 | // Build the DetectIntentRequest 80 | DetectIntentRequest request = DetectIntentRequest.newBuilder() 81 | .setSession(session.toString()) 82 | .setQueryInput(queryInput) 83 | .setInputAudio(ByteString.copyFrom(inputAudio)) 84 | .build(); 85 | 86 | // Performs the detect intent request 87 | DetectIntentResponse response = sessionsClient.detectIntent(request); 88 | 89 | // Display the query result 90 | QueryResult queryResult = response.getQueryResult(); 91 | System.out.println("===================="); 92 | System.out.format("Query Text: '%s'\n", queryResult.getQueryText()); 93 | System.out.format("Detected Intent: %s (confidence: %f)\n", 94 | queryResult.getIntent().getDisplayName(), queryResult.getIntentDetectionConfidence()); 95 | System.out.format("Fulfillment Text: '%s'\n", queryResult.getFulfillmentText()); 96 | } 97 | } 98 | // [END dialogflow_detect_intent_audio] 99 | 100 | // [START run_application] 101 | public static void main(String[] args) throws Exception { 102 | String audioFilePath = ""; 103 | String projectId = ""; 104 | String sessionId = UUID.randomUUID().toString(); 105 | String languageCode = "en-US"; 106 | 107 | try { 108 | String command = args[0]; 109 | if (command.equals("--projectId")) { 110 | projectId = args[1]; 111 | } 112 | 113 | command = args[2]; 114 | if (command.equals("--audioFilePath")) { 115 | audioFilePath = args[3]; 116 | } 117 | 118 | for (int i = 4; i < args.length; i += 2) { 119 | if (args[i].equals("--sessionId")) { 120 | sessionId = args[i + 1]; 121 | } else if (args[i].equals("--languageCode")) { 122 | languageCode = args[i + 1]; 123 | } 124 | } 125 | } catch (Exception e) { 126 | System.out.println("Usage:"); 127 | System.out.println("mvn exec:java -DDetectIntentAudio " 128 | + "-Dexec.args='--projectId PROJECT_ID --audioFilePath resources/book_a_room.wav " 129 | + "--sessionId SESSION_ID'\n"); 130 | 131 | System.out.println("Commands: audioFilePath"); 132 | System.out.println("\t--audioFilePath - Path to the audio file"); 133 | System.out.println("\t--projectId - Project/Agent Id"); 134 | System.out.println("Optional Commands:"); 135 | System.out.println("\t--languageCode - Language Code of the query (Defaults " 136 | + "to \"en-US\".)"); 137 | System.out.println("\t--sessionId - Identifier of the DetectIntent session " 138 | + "(Defaults to a random UUID.)"); 139 | } 140 | 141 | detectIntentAudio(projectId, audioFilePath, sessionId, languageCode); 142 | } 143 | // [END run_application] 144 | } 145 | -------------------------------------------------------------------------------- /samples/src/main/java/com/example/dialogflow/DetectIntentKnowledge.java: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2018, Google, Inc. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package com.example.dialogflow; 18 | 19 | // [START dialogflow_import_libraries] 20 | // Imports the Google Cloud client library 21 | import com.google.cloud.dialogflow.v2beta1.DetectIntentRequest; 22 | import com.google.cloud.dialogflow.v2beta1.DetectIntentResponse; 23 | import com.google.cloud.dialogflow.v2beta1.KnowledgeAnswers; 24 | import com.google.cloud.dialogflow.v2beta1.KnowledgeAnswers.Answer; 25 | import com.google.cloud.dialogflow.v2beta1.KnowledgeBaseName; 26 | import com.google.cloud.dialogflow.v2beta1.QueryInput; 27 | import com.google.cloud.dialogflow.v2beta1.QueryParameters; 28 | import com.google.cloud.dialogflow.v2beta1.QueryResult; 29 | import com.google.cloud.dialogflow.v2beta1.SessionName; 30 | import com.google.cloud.dialogflow.v2beta1.SessionsClient; 31 | import com.google.cloud.dialogflow.v2beta1.TextInput; 32 | import com.google.cloud.dialogflow.v2beta1.TextInput.Builder; 33 | 34 | import java.util.ArrayList; 35 | import java.util.List; 36 | import java.util.UUID; 37 | 38 | // [END dialogflow_import_libraries] 39 | 40 | /** DialogFlow API Detect Intent sample with querying knowledge connector. */ 41 | public class DetectIntentKnowledge { 42 | 43 | // [START dialogflow_detect_intent_knowledge] 44 | /** 45 | * Returns the result of detect intent with text as input. 46 | * 47 | *

Using the same `session_id` between requests allows continuation of the conversation. 48 | * 49 | * @param projectId Project/Agent Id. 50 | * @param knowledgeBaseId Knowledge base Id. 51 | * @param sessionId Identifier of the DetectIntent session. 52 | * @param languageCode Language code of the query. 53 | * @param texts The texts to be processed. 54 | * @throws Exception 55 | */ 56 | public static void detectIntentKnowledge( 57 | String projectId, 58 | String knowledgeBaseId, 59 | String sessionId, 60 | String languageCode, 61 | List texts) 62 | throws Exception { 63 | // Instantiates a client 64 | try (SessionsClient sessionsClient = SessionsClient.create()) { 65 | // Set the session name using the sessionId (UUID) and projectID (my-project-id) 66 | SessionName session = SessionName.of(projectId, sessionId); 67 | System.out.println("Session Path: " + session.toString()); 68 | 69 | // Detect intents for each text input 70 | for (String text : texts) { 71 | // Set the text and language code (en-US) for the query 72 | Builder textInput = TextInput.newBuilder().setText(text).setLanguageCode(languageCode); 73 | // Build the query with the TextInput 74 | QueryInput queryInput = QueryInput.newBuilder().setText(textInput).build(); 75 | 76 | KnowledgeBaseName knowledgeBaseName = KnowledgeBaseName.of(projectId, knowledgeBaseId); 77 | QueryParameters queryParameters = 78 | QueryParameters.newBuilder() 79 | .addKnowledgeBaseNames(knowledgeBaseName.toString()) 80 | .build(); 81 | 82 | DetectIntentRequest detectIntentRequest = 83 | DetectIntentRequest.newBuilder() 84 | .setSession(session.toString()) 85 | .setQueryInput(queryInput) 86 | .setQueryParams(queryParameters) 87 | .build(); 88 | // Performs the detect intent request 89 | DetectIntentResponse response = sessionsClient.detectIntent(detectIntentRequest); 90 | 91 | // Display the query result 92 | QueryResult queryResult = response.getQueryResult(); 93 | 94 | System.out.format("Knowledge results:\n"); 95 | System.out.format("====================\n"); 96 | System.out.format("Query Text: '%s'\n", queryResult.getQueryText()); 97 | System.out.format( 98 | "Detected Intent: %s (confidence: %f)\n", 99 | queryResult.getIntent().getDisplayName(), queryResult.getIntentDetectionConfidence()); 100 | System.out.format("Fulfillment Text: '%s'\n", queryResult.getFulfillmentText()); 101 | KnowledgeAnswers knowledgeAnswers = queryResult.getKnowledgeAnswers(); 102 | for (Answer answer : knowledgeAnswers.getAnswersList()) { 103 | System.out.format(" - Answer: '%s'\n", answer.getAnswer()); 104 | System.out.format(" - Confidence: '%s'\n", answer.getMatchConfidence()); 105 | } 106 | } 107 | } 108 | } 109 | 110 | // [END dialogflow_detect_intent_knowledge] 111 | 112 | // [START run_application] 113 | public static void main(String[] args) throws Exception { 114 | ArrayList texts = new ArrayList<>(); 115 | String projectId = ""; 116 | String sessionId = UUID.randomUUID().toString(); 117 | String languageCode = "en-US"; 118 | String knowledgeBaseId = ""; 119 | 120 | try { 121 | String command = args[0]; 122 | if (command.equals("--projectId")) { 123 | projectId = args[1]; 124 | } 125 | command = args[2]; 126 | if (command.equals("--knowledgeBaseId")) { 127 | knowledgeBaseId = args[3]; 128 | } 129 | 130 | for (int i = 4; i < args.length; i++) { 131 | switch (args[i]) { 132 | case "--sessionId": 133 | sessionId = args[++i]; 134 | break; 135 | case "--languageCode": 136 | languageCode = args[++i]; 137 | break; 138 | default: 139 | texts.add(args[i]); 140 | break; 141 | } 142 | } 143 | 144 | } catch (Exception e) { 145 | System.out.println("Usage:"); 146 | System.out.println( 147 | "mvn exec:java -DDetectIntentKnowledge " 148 | + "-Dexec.args=\"--projectId PROJECT_ID --knowledgeBaseId KNOWLEDGE_BASE_ID --sessionId SESSION_ID " 149 | + "'Where can I find pricing information?\"\n"); 150 | System.out.println("Commands: "); 151 | System.out.println("\t--projectId - Project/Agent Id"); 152 | System.out.println("\t--knowledgeBaseId - KnowledgeBase Id "); 153 | System.out.println( 154 | "\tText: \"hello\" \"book a meeting room\" \"Mountain View\" \"tomorrow\" " 155 | + "\"10am\" \"2 hours\" \"10 people\" \"A\" \"yes\""); 156 | System.out.println("Optional Commands:"); 157 | System.out.println( 158 | "\t--languageCode - Language Code of the query (Defaults " 159 | + "to \"en-US\".)"); 160 | System.out.println( 161 | "\t--sessionId - Identifier of the DetectIntent session " 162 | + "(Defaults to a random UUID.)"); 163 | } 164 | 165 | detectIntentKnowledge(projectId, knowledgeBaseId, sessionId, languageCode, texts); 166 | } 167 | // [END run_application] 168 | } 169 | -------------------------------------------------------------------------------- /samples/src/main/java/com/example/dialogflow/DetectIntentSentimentAnalysis.java: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2018, Google, Inc. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package com.example.dialogflow; 18 | 19 | import com.google.cloud.dialogflow.v2beta1.DetectIntentRequest; 20 | import com.google.cloud.dialogflow.v2beta1.DetectIntentResponse; 21 | import com.google.cloud.dialogflow.v2beta1.SessionName; 22 | import com.google.cloud.dialogflow.v2beta1.SessionsClient; 23 | import com.google.cloud.dialogflow.v2beta1.QueryInput; 24 | import com.google.cloud.dialogflow.v2beta1.QueryParameters; 25 | import com.google.cloud.dialogflow.v2beta1.QueryResult; 26 | import com.google.cloud.dialogflow.v2beta1.SentimentAnalysisRequestConfig; 27 | import com.google.cloud.dialogflow.v2beta1.TextInput; 28 | import com.google.cloud.dialogflow.v2beta1.TextInput.Builder; 29 | 30 | import java.util.ArrayList; 31 | import java.util.List; 32 | import java.util.UUID; 33 | 34 | public class DetectIntentSentimentAnalysis { 35 | 36 | // [START dialogflow_detect_intent_with_sentiment_analysis] 37 | /** 38 | * Returns the result of detect intent with texts as inputs. 39 | * 40 | *

Using the same `session_id` between requests allows continuation of the conversation. 41 | * 42 | * @param projectId Project/Agent Id. 43 | * @param texts The text intents to be detected based on what a user says. 44 | * @param sessionId Identifier of the DetectIntent session. 45 | * @param languageCode Language code of the query. 46 | */ 47 | public static void detectIntentSentimentAnalysis( 48 | String projectId, List texts, String sessionId, String languageCode) 49 | throws Exception { 50 | // Instantiates a client 51 | try (SessionsClient sessionsClient = SessionsClient.create()) { 52 | // Set the session name using the sessionId (UUID) and projectID (my-project-id) 53 | SessionName session = SessionName.of(projectId, sessionId); 54 | System.out.println("Session Path: " + session.toString()); 55 | 56 | // Detect intents for each text input 57 | for (String text : texts) { 58 | // Set the text (hello) and language code (en-US) for the query 59 | Builder textInput = TextInput.newBuilder().setText(text).setLanguageCode(languageCode); 60 | 61 | // Build the query with the TextInput 62 | QueryInput queryInput = QueryInput.newBuilder().setText(textInput).build(); 63 | 64 | // 65 | SentimentAnalysisRequestConfig sentimentAnalysisRequestConfig = 66 | SentimentAnalysisRequestConfig.newBuilder().setAnalyzeQueryTextSentiment(true).build(); 67 | 68 | QueryParameters queryParameters = 69 | QueryParameters.newBuilder() 70 | .setSentimentAnalysisRequestConfig(sentimentAnalysisRequestConfig) 71 | .build(); 72 | DetectIntentRequest detectIntentRequest = 73 | DetectIntentRequest.newBuilder() 74 | .setSession(session.toString()) 75 | .setQueryInput(queryInput) 76 | .setQueryParams(queryParameters) 77 | .build(); 78 | 79 | // Performs the detect intent request 80 | DetectIntentResponse response = sessionsClient.detectIntent(detectIntentRequest); 81 | 82 | // Display the query result 83 | QueryResult queryResult = response.getQueryResult(); 84 | 85 | System.out.println("===================="); 86 | System.out.format("Query Text: '%s'\n", queryResult.getQueryText()); 87 | System.out.format( 88 | "Detected Intent: %s (confidence: %f)\n", 89 | queryResult.getIntent().getDisplayName(), queryResult.getIntentDetectionConfidence()); 90 | System.out.format("Fulfillment Text: '%s'\n", queryResult.getFulfillmentText()); 91 | System.out.format( 92 | "Sentiment Score: '%s'\n", 93 | queryResult.getSentimentAnalysisResult().getQueryTextSentiment().getScore()); 94 | } 95 | } 96 | } 97 | // [END dialogflow_detect_intent_with_sentiment_analysis] 98 | 99 | // [START run_application] 100 | public static void main(String[] args) throws Exception { 101 | ArrayList texts = new ArrayList<>(); 102 | String projectId = ""; 103 | String sessionId = UUID.randomUUID().toString(); 104 | String languageCode = "en-US"; 105 | 106 | try { 107 | String command = args[0]; 108 | if (command.equals("--projectId")) { 109 | projectId = args[1]; 110 | } 111 | 112 | for (int i = 2; i < args.length; i++) { 113 | switch (args[i]) { 114 | case "--sessionId": 115 | sessionId = args[++i]; 116 | break; 117 | case "--languageCode": 118 | languageCode = args[++i]; 119 | break; 120 | default: 121 | texts.add(args[i]); 122 | break; 123 | } 124 | } 125 | 126 | } catch (Exception e) { 127 | System.out.println("Usage:"); 128 | System.out.println( 129 | "mvn exec:java -DDetectIntentWithSentimentAnalysis " 130 | + "-Dexec.args=\"--projectId PROJECT_ID --sessionId SESSION_ID " 131 | + "'hello' 'book a meeting room' 'Mountain View' 'tomorrow' '10 am' '2 hours' " 132 | + "'10 people' 'A' 'yes'\"\n"); 133 | 134 | System.out.println("Commands: text"); 135 | System.out.println("\t--projectId - Project/Agent Id"); 136 | System.out.println( 137 | "\tText: \"hello\" \"book a meeting room\" \"Mountain View\" \"tomorrow\" " 138 | + "\"10am\" \"2 hours\" \"10 people\" \"A\" \"yes\""); 139 | System.out.println("Optional Commands:"); 140 | System.out.println( 141 | "\t--languageCode - Language Code of the query (Defaults " 142 | + "to \"en-US\".)"); 143 | System.out.println( 144 | "\t--sessionId - Identifier of the DetectIntent session " 145 | + "(Defaults to a random UUID.)"); 146 | } 147 | 148 | detectIntentSentimentAnalysis(projectId, texts, sessionId, languageCode); 149 | } 150 | // [END run_application] 151 | 152 | } 153 | -------------------------------------------------------------------------------- /samples/src/main/java/com/example/dialogflow/DetectIntentStream.java: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2017, Google, Inc. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package com.example.dialogflow; 18 | 19 | // [START dialogflow_import_libraries] 20 | // Imports the Google Cloud client library 21 | import com.google.api.gax.rpc.ApiStreamObserver; 22 | import com.google.cloud.dialogflow.v2.AudioEncoding; 23 | import com.google.cloud.dialogflow.v2.InputAudioConfig; 24 | import com.google.cloud.dialogflow.v2.QueryInput; 25 | import com.google.cloud.dialogflow.v2.QueryResult; 26 | import com.google.cloud.dialogflow.v2.SessionName; 27 | import com.google.cloud.dialogflow.v2.SessionsClient; 28 | import com.google.cloud.dialogflow.v2.StreamingDetectIntentRequest; 29 | import com.google.cloud.dialogflow.v2.StreamingDetectIntentResponse; 30 | import com.google.protobuf.ByteString; 31 | 32 | import java.io.FileInputStream; 33 | import java.util.ArrayList; 34 | import java.util.List; 35 | import java.util.UUID; 36 | import java.util.concurrent.CountDownLatch; 37 | // [END dialogflow_import_libraries] 38 | 39 | /** 40 | * DialogFlow API Detect Intent sample with audio files processes as an audio stream. 41 | */ 42 | public class DetectIntentStream { 43 | 44 | // [START dialogflow_detect_intent_streaming] 45 | /** 46 | * Returns the result of detect intent with streaming audio as input. 47 | * 48 | * Using the same `session_id` between requests allows continuation of the conversation. 49 | * @param projectId Project/Agent Id. 50 | * @param audioFilePath The audio file to be processed. 51 | * @param sessionId Identifier of the DetectIntent session. 52 | * @param languageCode Language code of the query. 53 | */ 54 | public static void detectIntentStream(String projectId, String audioFilePath, String sessionId, 55 | String languageCode) throws Throwable { 56 | // Start bi-directional StreamingDetectIntent stream. 57 | final CountDownLatch notification = new CountDownLatch(1); 58 | final List responseThrowables = new ArrayList<>(); 59 | final List responses = new ArrayList<>(); 60 | 61 | // Instantiates a client 62 | try (SessionsClient sessionsClient = SessionsClient.create()) { 63 | // Set the session name using the sessionId (UUID) and projectID (my-project-id) 64 | SessionName session = SessionName.of(projectId, sessionId); 65 | System.out.println("Session Path: " + session.toString()); 66 | 67 | // Note: hard coding audioEncoding and sampleRateHertz for simplicity. 68 | // Audio encoding of the audio content sent in the query request. 69 | AudioEncoding audioEncoding = AudioEncoding.AUDIO_ENCODING_LINEAR_16; 70 | int sampleRateHertz = 16000; 71 | 72 | // Instructs the speech recognizer how to process the audio content. 73 | InputAudioConfig inputAudioConfig = InputAudioConfig.newBuilder() 74 | .setAudioEncoding(audioEncoding) // audioEncoding = AudioEncoding.AUDIO_ENCODING_LINEAR_16 75 | .setLanguageCode(languageCode) // languageCode = "en-US" 76 | .setSampleRateHertz(sampleRateHertz) // sampleRateHertz = 16000 77 | .build(); 78 | 79 | ApiStreamObserver responseObserver = 80 | new ApiStreamObserver() { 81 | @Override 82 | public void onNext(StreamingDetectIntentResponse response) { 83 | // Do something when receive a response 84 | responses.add(response); 85 | } 86 | 87 | @Override 88 | public void onError(Throwable t) { 89 | // Add error-handling 90 | responseThrowables.add(t); 91 | } 92 | 93 | @Override 94 | public void onCompleted() { 95 | // Do something when complete. 96 | notification.countDown(); 97 | } 98 | }; 99 | 100 | // Performs the streaming detect intent callable request 101 | ApiStreamObserver requestObserver = 102 | sessionsClient.streamingDetectIntentCallable().bidiStreamingCall(responseObserver); 103 | 104 | // Build the query with the InputAudioConfig 105 | QueryInput queryInput = QueryInput.newBuilder().setAudioConfig(inputAudioConfig).build(); 106 | 107 | try (FileInputStream audioStream = new FileInputStream(audioFilePath)) { 108 | // The first request contains the configuration 109 | StreamingDetectIntentRequest request = StreamingDetectIntentRequest.newBuilder() 110 | .setSession(session.toString()) 111 | .setQueryInput(queryInput) 112 | .build(); 113 | 114 | // Make the first request 115 | requestObserver.onNext(request); 116 | 117 | // Following messages: audio chunks. We just read the file in fixed-size chunks. In reality 118 | // you would split the user input by time. 119 | byte[] buffer = new byte[4096]; 120 | int bytes; 121 | while ((bytes = audioStream.read(buffer)) != -1) { 122 | requestObserver.onNext( 123 | StreamingDetectIntentRequest.newBuilder() 124 | .setInputAudio(ByteString.copyFrom(buffer, 0, bytes)) 125 | .build()); 126 | } 127 | } catch (RuntimeException e) { 128 | // Cancel stream. 129 | requestObserver.onError(e); 130 | } 131 | // Half-close the stream. 132 | requestObserver.onCompleted(); 133 | // Wait for the final response (without explicit timeout). 134 | notification.await(); 135 | // Process errors/responses. 136 | if (!responseThrowables.isEmpty()) { 137 | throw responseThrowables.get(0); 138 | } 139 | if (responses.isEmpty()) { 140 | throw new RuntimeException("No response from Dialogflow."); 141 | } 142 | 143 | for (StreamingDetectIntentResponse response : responses) { 144 | if (response.hasRecognitionResult()) { 145 | System.out.format( 146 | "Intermediate transcript: '%s'\n", response.getRecognitionResult().getTranscript()); 147 | } 148 | } 149 | 150 | // Display the last query result 151 | QueryResult queryResult = responses.get(responses.size() - 1).getQueryResult(); 152 | System.out.println("===================="); 153 | System.out.format("Query Text: '%s'\n", queryResult.getQueryText()); 154 | System.out.format("Detected Intent: %s (confidence: %f)\n", 155 | queryResult.getIntent().getDisplayName(), queryResult.getIntentDetectionConfidence()); 156 | System.out.format("Fulfillment Text: '%s'\n", queryResult.getFulfillmentText()); 157 | } 158 | } 159 | // [END dialogflow_detect_intent_streaming] 160 | 161 | // [START run_application] 162 | public static void main(String[] args) throws Throwable { 163 | String audioFilePath = ""; 164 | String projectId = ""; 165 | String sessionId = UUID.randomUUID().toString(); 166 | String languageCode = "en-US"; 167 | 168 | try { 169 | String command = args[0]; 170 | if (command.equals("--projectId")) { 171 | projectId = args[1]; 172 | } 173 | 174 | command = args[2]; 175 | if (command.equals("--audioFilePath")) { 176 | audioFilePath = args[3]; 177 | } 178 | 179 | for (int i = 4; i < args.length; i += 2) { 180 | if (args[i].equals("--sessionId")) { 181 | sessionId = args[i + 1]; 182 | } else if (args[i].equals("--languageCode")) { 183 | languageCode = args[i + 1]; 184 | } 185 | } 186 | } catch (Exception e) { 187 | System.out.println("Usage:"); 188 | System.out.println("mvn exec:java -DDetectIntentStream " 189 | + "-Dexec.args='--projectId PROJECT_ID --audioFilePath resources/book_a_room.wav " 190 | + "--sessionId SESSION_ID'\n"); 191 | 192 | System.out.println("Commands: --audioFilePath"); 193 | System.out.println("\t--projectId - Project/Agent Id"); 194 | System.out.println("\t--audioFilePath - Path to the audio file"); 195 | System.out.println("Optional Commands:"); 196 | System.out.println("\t--languageCode - Language Code of the query (Defaults " 197 | + "to \"en-US\".)"); 198 | System.out.println("\t--sessionId - Identifier of the DetectIntent session " 199 | + "(Defaults to a random UUID.)"); 200 | } 201 | 202 | detectIntentStream(projectId, audioFilePath, sessionId, languageCode); 203 | } 204 | // [END run_application] 205 | } 206 | -------------------------------------------------------------------------------- /samples/src/main/java/com/example/dialogflow/DetectIntentTTSResponses.java: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2018, Google, Inc. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package com.example.dialogflow; 18 | 19 | import com.google.cloud.dialogflow.v2beta1.DetectIntentRequest; 20 | import com.google.cloud.dialogflow.v2beta1.DetectIntentResponse; 21 | import com.google.cloud.dialogflow.v2beta1.OutputAudioConfig; 22 | import com.google.cloud.dialogflow.v2beta1.OutputAudioEncoding; 23 | import com.google.cloud.dialogflow.v2beta1.QueryInput; 24 | import com.google.cloud.dialogflow.v2beta1.QueryResult; 25 | import com.google.cloud.dialogflow.v2beta1.SessionName; 26 | import com.google.cloud.dialogflow.v2beta1.SessionsClient; 27 | import com.google.cloud.dialogflow.v2beta1.TextInput; 28 | import com.google.cloud.dialogflow.v2beta1.TextInput.Builder; 29 | 30 | import java.util.ArrayList; 31 | import java.util.List; 32 | import java.util.UUID; 33 | 34 | public class DetectIntentTTSResponses { 35 | 36 | // [START dialogflow_detect_intent_with_texttospeech_response] 37 | /** 38 | * Returns the result of detect intent with texts as inputs. 39 | * 40 | *

Using the same `session_id` between requests allows continuation of the conversation. 41 | * 42 | * @param projectId Project/Agent Id. 43 | * @param texts The text intents to be detected based on what a user says. 44 | * @param sessionId Identifier of the DetectIntent session. 45 | * @param languageCode Language code of the query. 46 | */ 47 | public static void detectIntentWithTexttoSpeech( 48 | String projectId, List texts, String sessionId, String languageCode) 49 | throws Exception { 50 | // Instantiates a client 51 | try (SessionsClient sessionsClient = SessionsClient.create()) { 52 | // Set the session name using the sessionId (UUID) and projectID (my-project-id) 53 | SessionName session = SessionName.of(projectId, sessionId); 54 | System.out.println("Session Path: " + session.toString()); 55 | 56 | // Detect intents for each text input 57 | for (String text : texts) { 58 | // Set the text (hello) and language code (en-US) for the query 59 | Builder textInput = TextInput.newBuilder().setText(text).setLanguageCode(languageCode); 60 | 61 | // Build the query with the TextInput 62 | QueryInput queryInput = QueryInput.newBuilder().setText(textInput).build(); 63 | 64 | // 65 | OutputAudioEncoding audioEncoding = OutputAudioEncoding.OUTPUT_AUDIO_ENCODING_LINEAR_16; 66 | int sampleRateHertz = 16000; 67 | OutputAudioConfig outputAudioConfig = 68 | OutputAudioConfig.newBuilder() 69 | .setAudioEncoding(audioEncoding) 70 | .setSampleRateHertz(sampleRateHertz) 71 | .build(); 72 | 73 | DetectIntentRequest dr = 74 | DetectIntentRequest.newBuilder() 75 | .setQueryInput(queryInput) 76 | .setOutputAudioConfig(outputAudioConfig) 77 | .setSession(session.toString()) 78 | .build(); 79 | 80 | // Performs the detect intent request 81 | // DetectIntentResponse response = sessionsClient.detectIntent(session, 82 | // queryInput,outputAudioConfig); 83 | DetectIntentResponse response = sessionsClient.detectIntent(dr); 84 | 85 | // Display the query result 86 | QueryResult queryResult = response.getQueryResult(); 87 | 88 | System.out.println("===================="); 89 | System.out.format("Query Text: '%s'\n", queryResult.getQueryText()); 90 | System.out.format( 91 | "Detected Intent: %s (confidence: %f)\n", 92 | queryResult.getIntent().getDisplayName(), queryResult.getIntentDetectionConfidence()); 93 | System.out.format("Fulfillment Text: '%s'\n", queryResult.getFulfillmentText()); 94 | } 95 | } 96 | } 97 | 98 | // [END dialogflow_detect_intent_with_texttospeech_response] 99 | 100 | // [START run_application] 101 | public static void main(String[] args) throws Exception { 102 | ArrayList texts = new ArrayList<>(); 103 | String projectId = ""; 104 | String sessionId = UUID.randomUUID().toString(); 105 | String languageCode = "en-US"; 106 | 107 | try { 108 | String command = args[0]; 109 | if (command.equals("--projectId")) { 110 | projectId = args[1]; 111 | } 112 | 113 | for (int i = 2; i < args.length; i++) { 114 | switch (args[i]) { 115 | case "--sessionId": 116 | sessionId = args[++i]; 117 | break; 118 | case "--languageCode": 119 | languageCode = args[++i]; 120 | break; 121 | default: 122 | texts.add(args[i]); 123 | break; 124 | } 125 | } 126 | 127 | } catch (Exception e) { 128 | System.out.println("Usage:"); 129 | System.out.println( 130 | "mvn exec:java -DDetectIntentWithTTSResponses " 131 | + "-Dexec.args=\"--projectId PROJECT_ID --sessionId SESSION_ID " 132 | + "'hello' 'book a meeting room' 'Mountain View' 'tomorrow' '10 am' '2 hours' " 133 | + "'10 people' 'A' 'yes'\"\n"); 134 | 135 | System.out.println("Commands: text"); 136 | System.out.println("\t--projectId - Project/Agent Id"); 137 | System.out.println( 138 | "\tText: \"hello\" \"book a meeting room\" \"Mountain View\" \"tomorrow\" " 139 | + "\"10am\" \"2 hours\" \"10 people\" \"A\" \"yes\""); 140 | System.out.println("Optional Commands:"); 141 | System.out.println( 142 | "\t--languageCode - Language Code of the query (Defaults " 143 | + "to \"en-US\".)"); 144 | System.out.println( 145 | "\t--sessionId - Identifier of the DetectIntent session " 146 | + "(Defaults to a random UUID.)"); 147 | } 148 | 149 | detectIntentWithTexttoSpeech(projectId, texts, sessionId, languageCode); 150 | } 151 | // [END run_application] 152 | 153 | } 154 | -------------------------------------------------------------------------------- /samples/src/main/java/com/example/dialogflow/DetectIntentTexts.java: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2017, Google, Inc. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package com.example.dialogflow; 18 | 19 | // [START dialogflow_import_libraries] 20 | // Imports the Google Cloud client library 21 | import com.google.cloud.dialogflow.v2.DetectIntentResponse; 22 | import com.google.cloud.dialogflow.v2.QueryInput; 23 | import com.google.cloud.dialogflow.v2.QueryResult; 24 | import com.google.cloud.dialogflow.v2.SessionName; 25 | import com.google.cloud.dialogflow.v2.SessionsClient; 26 | import com.google.cloud.dialogflow.v2.TextInput; 27 | import com.google.cloud.dialogflow.v2.TextInput.Builder; 28 | 29 | import java.util.ArrayList; 30 | import java.util.List; 31 | import java.util.UUID; 32 | // [END dialogflow_import_libraries] 33 | 34 | 35 | /** 36 | * DialogFlow API Detect Intent sample with text inputs. 37 | */ 38 | public class DetectIntentTexts { 39 | 40 | // [START dialogflow_detect_intent_text] 41 | /** 42 | * Returns the result of detect intent with texts as inputs. 43 | * 44 | * Using the same `session_id` between requests allows continuation of the conversation. 45 | * @param projectId Project/Agent Id. 46 | * @param texts The text intents to be detected based on what a user says. 47 | * @param sessionId Identifier of the DetectIntent session. 48 | * @param languageCode Language code of the query. 49 | */ 50 | public static void detectIntentTexts(String projectId, List texts, String sessionId, 51 | String languageCode) throws Exception { 52 | // Instantiates a client 53 | try (SessionsClient sessionsClient = SessionsClient.create()) { 54 | // Set the session name using the sessionId (UUID) and projectID (my-project-id) 55 | SessionName session = SessionName.of(projectId, sessionId); 56 | System.out.println("Session Path: " + session.toString()); 57 | 58 | // Detect intents for each text input 59 | for (String text : texts) { 60 | // Set the text (hello) and language code (en-US) for the query 61 | Builder textInput = TextInput.newBuilder().setText(text).setLanguageCode(languageCode); 62 | 63 | // Build the query with the TextInput 64 | QueryInput queryInput = QueryInput.newBuilder().setText(textInput).build(); 65 | 66 | // Performs the detect intent request 67 | DetectIntentResponse response = sessionsClient.detectIntent(session, queryInput); 68 | 69 | // Display the query result 70 | QueryResult queryResult = response.getQueryResult(); 71 | 72 | System.out.println("===================="); 73 | System.out.format("Query Text: '%s'\n", queryResult.getQueryText()); 74 | System.out.format("Detected Intent: %s (confidence: %f)\n", 75 | queryResult.getIntent().getDisplayName(), queryResult.getIntentDetectionConfidence()); 76 | System.out.format("Fulfillment Text: '%s'\n", queryResult.getFulfillmentText()); 77 | } 78 | } 79 | } 80 | // [END dialogflow_detect_intent_text] 81 | 82 | // [START run_application] 83 | public static void main(String[] args) throws Exception { 84 | ArrayList texts = new ArrayList<>(); 85 | String projectId = ""; 86 | String sessionId = UUID.randomUUID().toString(); 87 | String languageCode = "en-US"; 88 | 89 | try { 90 | String command = args[0]; 91 | if (command.equals("--projectId")) { 92 | projectId = args[1]; 93 | } 94 | 95 | for (int i = 2; i < args.length; i++) { 96 | switch (args[i]) { 97 | case "--sessionId": 98 | sessionId = args[++i]; 99 | break; 100 | case "--languageCode": 101 | languageCode = args[++i]; 102 | break; 103 | default: 104 | texts.add(args[i]); 105 | break; 106 | } 107 | } 108 | 109 | } catch (Exception e) { 110 | System.out.println("Usage:"); 111 | System.out.println("mvn exec:java -DDetectIntentTexts " 112 | + "-Dexec.args=\"--projectId PROJECT_ID --sessionId SESSION_ID " 113 | + "'hello' 'book a meeting room' 'Mountain View' 'tomorrow' '10 am' '2 hours' " 114 | + "'10 people' 'A' 'yes'\"\n"); 115 | 116 | System.out.println("Commands: text"); 117 | System.out.println("\t--projectId - Project/Agent Id"); 118 | System.out.println("\tText: \"hello\" \"book a meeting room\" \"Mountain View\" \"tomorrow\" " 119 | + "\"10am\" \"2 hours\" \"10 people\" \"A\" \"yes\""); 120 | System.out.println("Optional Commands:"); 121 | System.out.println("\t--languageCode - Language Code of the query (Defaults " 122 | + "to \"en-US\".)"); 123 | System.out.println("\t--sessionId - Identifier of the DetectIntent session " 124 | + "(Defaults to a random UUID.)"); 125 | } 126 | 127 | detectIntentTexts(projectId, texts, sessionId, languageCode); 128 | } 129 | // [END run_application] 130 | } 131 | -------------------------------------------------------------------------------- /samples/src/main/java/com/example/dialogflow/DetectIntentWithModelSelection.java: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2018, Google, Inc. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package com.example.dialogflow; 18 | 19 | import com.google.cloud.dialogflow.v2beta1.DetectIntentRequest; 20 | import com.google.cloud.dialogflow.v2beta1.DetectIntentResponse; 21 | import com.google.cloud.dialogflow.v2beta1.QueryResult; 22 | import com.google.cloud.dialogflow.v2beta1.AudioEncoding; 23 | import com.google.cloud.dialogflow.v2beta1.InputAudioConfig; 24 | import com.google.cloud.dialogflow.v2beta1.QueryInput; 25 | import com.google.cloud.dialogflow.v2beta1.SessionName; 26 | import com.google.cloud.dialogflow.v2beta1.SessionsClient; 27 | import com.google.protobuf.ByteString; 28 | 29 | import java.nio.file.Files; 30 | import java.nio.file.Paths; 31 | import java.util.UUID; 32 | 33 | public class DetectIntentWithModelSelection { 34 | 35 | // [START dialogflow_detect_intent_with_model_selection] 36 | /** 37 | * Returns the result of detect intent with an audio file as input. 38 | * 39 | *

Using the same `session_id` between requests allows continuation of the conversation. 40 | * 41 | * @param projectId Project/Agent Id. 42 | * @param audioFilePath Path to the audio file. 43 | * @param sessionId Identifier of the DetectIntent session. 44 | * @param languageCode Language code of the query. 45 | */ 46 | public static void detectIntentWithModelSelection( 47 | String projectId, String sessionId, String audioFilePath, String languageCode) 48 | throws Exception { 49 | // Instantiates a client 50 | try (SessionsClient sessionsClient = SessionsClient.create()) { 51 | // Set the session name using the sessionId (UUID) and projectID (my-project-id) 52 | SessionName session = SessionName.of(projectId, sessionId); 53 | System.out.println("Session Path: " + session.toString()); 54 | 55 | // Note: hard coding audioEncoding and sampleRateHertz for simplicity. 56 | // Audio encoding of the audio content sent in the query request. 57 | AudioEncoding audioEncoding = AudioEncoding.AUDIO_ENCODING_LINEAR_16; 58 | int sampleRateHertz = 16000; 59 | 60 | // Instructs the speech recognizer how to process the audio content. 61 | InputAudioConfig inputAudioConfig = 62 | InputAudioConfig.newBuilder() 63 | .setAudioEncoding( 64 | audioEncoding) // audioEncoding = AudioEncoding.AUDIO_ENCODING_LINEAR_16 65 | .setLanguageCode(languageCode) // languageCode = "en-US" 66 | .setSampleRateHertz(sampleRateHertz) // sampleRateHertz = 16000 67 | .setModel("phone_call") // model = phone call 68 | .build(); 69 | 70 | // Build the query with the InputAudioConfig 71 | QueryInput queryInput = QueryInput.newBuilder().setAudioConfig(inputAudioConfig).build(); 72 | 73 | // Read the bytes from the audio file 74 | byte[] inputAudio = Files.readAllBytes(Paths.get(audioFilePath)); 75 | 76 | // Build the DetectIntentRequest 77 | DetectIntentRequest request = 78 | DetectIntentRequest.newBuilder() 79 | .setSession(session.toString()) 80 | .setQueryInput(queryInput) 81 | .setInputAudio(ByteString.copyFrom(inputAudio)) 82 | .build(); 83 | // Performs the detect intent request 84 | DetectIntentResponse response = sessionsClient.detectIntent(request); 85 | 86 | // Display the query result 87 | QueryResult queryResult = response.getQueryResult(); 88 | System.out.println("===================="); 89 | System.out.format("Query Text: '%s'\n", queryResult.getQueryText()); 90 | System.out.format( 91 | "Detected Intent: %s (confidence: %f)\n", 92 | queryResult.getIntent().getDisplayName(), queryResult.getIntentDetectionConfidence()); 93 | System.out.format("Fulfillment Text: '%s'\n", queryResult.getFulfillmentText()); 94 | } 95 | } 96 | // [END dialogflow_detect_intent_with_model_selection] 97 | 98 | // [START run_application] 99 | public static void main(String[] args) throws Exception { 100 | String audioFilePath = ""; 101 | String projectId = ""; 102 | String sessionId = UUID.randomUUID().toString(); 103 | String languageCode = "en-US"; 104 | 105 | try { 106 | String command = args[0]; 107 | if (command.equals("--projectId")) { 108 | projectId = args[1]; 109 | } 110 | 111 | command = args[2]; 112 | if (command.equals("--audioFilePath")) { 113 | audioFilePath = args[3]; 114 | } 115 | 116 | for (int i = 4; i < args.length; i += 2) { 117 | if (args[i].equals("--sessionId")) { 118 | sessionId = args[i + 1]; 119 | } else if (args[i].equals("--languageCode")) { 120 | languageCode = args[i + 1]; 121 | } 122 | } 123 | } catch (Exception e) { 124 | System.out.println("Usage:"); 125 | System.out.println( 126 | "mvn exec:java -DDetectIntentWithModelSelection " 127 | + "-Dexec.args='--projectId PROJECT_ID --audioFilePath resources/book_a_room.wav " 128 | + "--sessionId SESSION_ID'\n"); 129 | 130 | System.out.println("Commands: audioFilePath"); 131 | System.out.println("\t--audioFilePath - Path to the audio file"); 132 | System.out.println("\t--projectId - Project/Agent Id"); 133 | System.out.println("Optional Commands:"); 134 | System.out.println( 135 | "\t--languageCode - Language Code of the query (Defaults " 136 | + "to \"en-US\".)"); 137 | System.out.println( 138 | "\t--sessionId - Identifier of the DetectIntent session " 139 | + "(Defaults to a random UUID.)"); 140 | } 141 | 142 | detectIntentWithModelSelection(projectId, sessionId, audioFilePath, languageCode); 143 | } 144 | // [END run_application] 145 | } 146 | -------------------------------------------------------------------------------- /samples/src/main/java/com/example/dialogflow/DocumentManagement.java: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2018, Google, Inc. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package com.example.dialogflow; 18 | 19 | import com.google.api.gax.longrunning.OperationFuture; 20 | import com.google.cloud.dialogflow.v2beta1.CreateDocumentRequest; 21 | import com.google.cloud.dialogflow.v2beta1.Document; 22 | import com.google.cloud.dialogflow.v2beta1.Document.KnowledgeType; 23 | import com.google.cloud.dialogflow.v2beta1.DocumentName; 24 | import com.google.cloud.dialogflow.v2beta1.DocumentsClient; 25 | import com.google.cloud.dialogflow.v2beta1.KnowledgeBaseName; 26 | import com.google.cloud.dialogflow.v2beta1.KnowledgeOperationMetadata; 27 | 28 | public class DocumentManagement { 29 | 30 | // [START dialogflow_list_document] 31 | 32 | /** 33 | * @param projectId Project/Agent id. 34 | * @param knowledgeBaseId Knowledge Base id. 35 | * @throws Exception 36 | */ 37 | public static void listDocuments(String projectId, String knowledgeBaseId) throws Exception { 38 | // Instantiates a client 39 | try (DocumentsClient documentsClient = DocumentsClient.create()) { 40 | KnowledgeBaseName knowledgeBaseName = KnowledgeBaseName.of(projectId, knowledgeBaseId); 41 | for (Document document : documentsClient.listDocuments(knowledgeBaseName).iterateAll()) { 42 | System.out.format(" - Display Name: %s\n", document.getDisplayName()); 43 | System.out.format(" - Knowledge ID: %s\n", document.getName()); 44 | System.out.format(" - MIME Type: %s\n", document.getMimeType()); 45 | System.out.format(" - Knowledge Types:\n"); 46 | for (KnowledgeType knowledgeTypeId : document.getKnowledgeTypesList()) { 47 | System.out.format(" - %s \n", knowledgeTypeId.getValueDescriptor()); 48 | } 49 | System.out.format(" - Source: %s \n", document.getContentUri()); 50 | } 51 | } 52 | } 53 | 54 | // [END dialogflow_list_document] 55 | 56 | // [START dialogflow_create_document] 57 | 58 | /** 59 | * @param projectId Project/Agent id. 60 | * @param knowledgeBaseId Knowledge Base id. 61 | * @param displayName display name of the Document. 62 | * @param mimeType MIME type of the Document. e.g. text/csv, text/html 63 | * @param knowledgeType Knowledge Type of the Document. e.g. FAQ, EXTRACTIVE_QA 64 | * @param contentUri Uri of the Document. e.g. gs://path/mydoc.csv, http://mypage.com/faq.html 65 | * @throws Exception 66 | */ 67 | public static void createDocument( 68 | String projectId, 69 | String knowledgeBaseId, 70 | String displayName, 71 | String mimeType, 72 | String knowledgeType, 73 | String contentUri) 74 | throws Exception { 75 | // Instantiates a client 76 | try (DocumentsClient documentsClient = DocumentsClient.create()) { 77 | Document document = 78 | Document.newBuilder() 79 | .setDisplayName(displayName) 80 | .setContentUri(contentUri) 81 | .setMimeType(mimeType) 82 | .addKnowledgeTypes(KnowledgeType.valueOf(knowledgeType)) 83 | .build(); 84 | KnowledgeBaseName parent = KnowledgeBaseName.of(projectId, knowledgeBaseId); 85 | CreateDocumentRequest createDocumentRequest = 86 | CreateDocumentRequest.newBuilder() 87 | .setDocument(document) 88 | .setParent(parent.toString()) 89 | .build(); 90 | OperationFuture response = 91 | documentsClient.createDocumentAsync(createDocumentRequest); 92 | System.out.format("Created Document:\n"); 93 | System.out.format(" - Display Name: %s\n", response.get().getDisplayName()); 94 | System.out.format(" - Knowledge ID: %s\n", response.get().getName()); 95 | System.out.format(" - MIME Type: %s\n", response.get().getMimeType()); 96 | System.out.format(" - Knowledge Types:\n"); 97 | for (KnowledgeType knowledgeTypeId : document.getKnowledgeTypesList()) { 98 | System.out.format(" - %s \n", knowledgeTypeId.getValueDescriptor()); 99 | } 100 | System.out.format(" - Source: %s \n", document.getContentUri()); 101 | } 102 | } 103 | // [END dialogflow_create_document] 104 | 105 | // [START dialogflow_get_document] 106 | 107 | /** 108 | * @param projectId Project/Agent id. 109 | * @param knowledgeBaseId Knowledge Base id. 110 | * @param documentId Document Id. 111 | * @throws Exception 112 | */ 113 | public static void getDocument(String projectId, String knowledgeBaseId, String documentId) 114 | throws Exception { 115 | // Instantiates a client 116 | try (DocumentsClient documentsClient = DocumentsClient.create()) { 117 | DocumentName documentName = DocumentName.of(projectId, knowledgeBaseId, documentId); 118 | Document response = documentsClient.getDocument(documentName); 119 | System.out.format("Got Document: \n"); 120 | System.out.format(" - Display Name: %s\n", response.getDisplayName()); 121 | System.out.format(" - Knowledge ID: %s\n", response.getName()); 122 | System.out.format(" - MIME Type: %s\n", response.getMimeType()); 123 | System.out.format(" - Knowledge Types:\n"); 124 | for (KnowledgeType knowledgeTypeId : response.getKnowledgeTypesList()) { 125 | System.out.format(" - %s \n", knowledgeTypeId.getValueDescriptor()); 126 | } 127 | System.out.format(" - Source: %s \n", response.getContentUri()); 128 | } 129 | } 130 | // [END dialogflow_get_document] 131 | 132 | // [START dialogflow_delete_document] 133 | 134 | /** 135 | * @param projectId Project/Agent id. 136 | * @param knowledgeBaseId Knowledge Base id. 137 | * @param documentId Document Id. 138 | * @throws Exception 139 | */ 140 | public static void deleteDocument(String projectId, String knowledgeBaseId, String documentId) 141 | throws Exception { 142 | // Instantiates a client 143 | try (DocumentsClient documentsClient = DocumentsClient.create()) { 144 | DocumentName documentName = DocumentName.of(projectId, knowledgeBaseId, documentId); 145 | documentsClient.deleteDocumentAsync(documentName).getInitialFuture().get(); 146 | System.out.format("The document has been deleted."); 147 | } 148 | } 149 | 150 | // [START run_application] 151 | public static void main(String[] args) throws Exception { 152 | String method = ""; 153 | String knowledgeBaseId = ""; 154 | String displayName = ""; 155 | String mimeType = ""; 156 | String knowledgeType = ""; 157 | String contentUri = ""; 158 | String projectId = ""; 159 | String documentId = ""; 160 | 161 | try { 162 | method = args[0]; 163 | String command = args[1]; 164 | if (method.equals("list")) { 165 | if (command.equals("--projectId")) { 166 | projectId = args[2]; 167 | } 168 | command = args[3]; 169 | if (command.equals("--knowledgeBaseId")) { 170 | knowledgeBaseId = args[4]; 171 | } 172 | } else if (method.equals("create")) { 173 | if (command.equals("--projectId")) { 174 | projectId = args[2]; 175 | } 176 | command = args[3]; 177 | if (command.equals("--knowledgeBaseId")) { 178 | knowledgeBaseId = args[4]; 179 | } 180 | command = args[5]; 181 | if (command.equals("--displayName")) { 182 | displayName = args[6]; 183 | } 184 | command = args[7]; 185 | if (command.equals("--mimeType")) { 186 | mimeType = args[8]; 187 | } 188 | command = args[9]; 189 | if (command.equals("--knowledgeType")) { 190 | knowledgeType = args[10]; 191 | } 192 | command = args[11]; 193 | if (command.equals("--contentUri")) { 194 | contentUri = args[12]; 195 | } 196 | } else if (method.equals("get")) { 197 | if (command.equals("--projectId")) { 198 | projectId = args[2]; 199 | } 200 | command = args[3]; 201 | if (command.equals("--knowledgeBaseId")) { 202 | knowledgeBaseId = args[4]; 203 | } 204 | command = args[5]; 205 | if (command.equals("--documentId")) { 206 | documentId = args[6]; 207 | } 208 | } else if (method.equals("delete")) { 209 | if (command.equals("--projectId")) { 210 | projectId = args[2]; 211 | } 212 | command = args[3]; 213 | if (command.equals("--knowledgeBaseId")) { 214 | knowledgeBaseId = args[4]; 215 | } 216 | command = args[5]; 217 | if (command.equals("--documentId")) { 218 | documentId = args[6]; 219 | } 220 | } 221 | } catch (Exception e) { 222 | System.out.println("Usage:"); 223 | System.out.println( 224 | "mvn exec:java -DDocumentManagement " 225 | + "-Dexec.args='list --projectId PROJECT_ID " 226 | + "--knowledgeBaseId MTc5NjM0NTE1Mzg2OTczNTUyNjQ'\n"); 227 | 228 | System.out.print( 229 | "mvn exec:java -DDocumentManagement " 230 | + "-Dexec.args='create --projectId PROJECT_ID " 231 | + "--knowledgeBaseId MTc5NjM0NTE1Mzg2OTczNTUyNjQ" 232 | + "--displayName test_doc'\n" 233 | + "--mimeType text/html'\n" 234 | + "--knowledgeType FAQ'\n" 235 | + "--contentUri https://cloud.google.com/storage/docs/faq'\n"); 236 | 237 | System.out.print( 238 | "mvn exec:java -DDocumentManagement " 239 | + "-Dexec.args='get --projectId PROJECT_ID " 240 | + "--knowledgeBaseId MTc5NjM0NTE1Mzg2OTczNTUyNjQ'\n" 241 | + "--documentId MTE2OTcxMTQ4Njk2NzYzNzYwNjQ"); 242 | 243 | System.out.print( 244 | "mvn exec:java -DDocumentManagement " 245 | + "-Dexec.args='delete --projectId PROJECT_ID " 246 | + "--knowledgeBaseId MTc5NjM0NTE1Mzg2OTczNTUyNjQ'\n" 247 | + "--documentId MTE2OTcxMTQ4Njk2NzYzNzYwNjQ"); 248 | 249 | System.out.println("Commands: list"); 250 | System.out.println("\t--projectId - Project/Agent Id"); 251 | 252 | System.out.println("\nCommands: create"); 253 | System.out.println("\t--projectId - Project/Agent Id"); 254 | System.out.println( 255 | "\t--knowledgeBaseId - [For create] The id of the " 256 | + "Knowledge Base to add the Document"); 257 | System.out.println( 258 | "\t--displayName - [For create] The display name of the Document"); 259 | System.out.println("\t--mimeType - [For create] The MIME Type of the Document"); 260 | System.out.println( 261 | "\t--knowledgeType - [For create] The Knowledge Type of the " 262 | + "Document"); 263 | System.out.println("\t--contentUri - [For create] The Uri of the Document"); 264 | 265 | System.out.println("\nCommands: get | delete"); 266 | System.out.println("\t--projectId - Project/Agent Id"); 267 | System.out.println( 268 | "\t--knowledgeBaseId - [For get | delete] The id of the " 269 | + "Knowledge Base to add the Document"); 270 | System.out.println("\t--documentId - [For get | delete] The id of the Document"); 271 | } 272 | 273 | if (method.equals("list")) { 274 | listDocuments(projectId, knowledgeBaseId); 275 | } else if (method.equals("create")) { 276 | createDocument(projectId, knowledgeBaseId, displayName, mimeType, knowledgeType, contentUri); 277 | } else if (method.equals("get")) { 278 | getDocument(projectId, knowledgeBaseId, documentId); 279 | } else if (method.equals("delete")) { 280 | deleteDocument(projectId, knowledgeBaseId, documentId); 281 | } 282 | } 283 | // [END run_application] 284 | 285 | } 286 | -------------------------------------------------------------------------------- /samples/src/main/java/com/example/dialogflow/EntityManagement.java: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2017, Google, Inc. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package com.example.dialogflow; 18 | 19 | // [START dialogflow_import_libraries] 20 | // Imports the Google Cloud client library 21 | import com.google.cloud.dialogflow.v2.EntityType; 22 | import com.google.cloud.dialogflow.v2.EntityType.Entity; 23 | import com.google.cloud.dialogflow.v2.EntityTypeName; 24 | import com.google.cloud.dialogflow.v2.EntityTypesClient; 25 | import com.google.protobuf.Empty; 26 | 27 | import java.util.ArrayList; 28 | import java.util.Arrays; 29 | import java.util.List; 30 | // [END dialogflow_import_libraries] 31 | 32 | /** 33 | * DialogFlow API Entity sample. 34 | */ 35 | public class EntityManagement { 36 | 37 | /** 38 | * List entities 39 | * @param projectId Project/agent id. 40 | * @param entityTypeId The id of the entity_type. 41 | */ 42 | public static void listEntities(String projectId, String entityTypeId) throws Exception { 43 | // Instantiates a client 44 | try (EntityTypesClient entityTypesClient = EntityTypesClient.create()) { 45 | // Set the entity type name using the projectID (my-project-id) and entityTypeId (KIND_LIST) 46 | EntityTypeName name = EntityTypeName.of(projectId, entityTypeId); 47 | 48 | // Performs the get entity type request 49 | EntityType entityType = entityTypesClient.getEntityType(name); 50 | for (Entity entity : entityType.getEntitiesList()) { 51 | System.out.format("Entity value: %s\n", entity.getValue()); 52 | System.out.format("Entity synonyms: %s\n", entity.getSynonymsList().toString()); 53 | } 54 | } 55 | } 56 | 57 | // [START dialogflow_create_entity] 58 | /** 59 | * Create an entity of the given entity type 60 | * @param projectId Project/agent id. 61 | * @param entityTypeId The id of the entity_type. 62 | * @param entityValue The entity value to be added. 63 | * @param synonyms The synonyms that will map to the provided entity value. 64 | */ 65 | public static void createEntity(String projectId, String entityTypeId, String entityValue, 66 | List synonyms) throws Exception { 67 | // Note: synonyms must be exactly [entityValue] if the 68 | // entityTypeId's kind is KIND_LIST 69 | if (synonyms.size() == 0) { 70 | synonyms.add(entityValue); 71 | } 72 | 73 | // Instantiates a client 74 | try (EntityTypesClient entityTypesClient = EntityTypesClient.create()) { 75 | // Set the entity type name using the projectID (my-project-id) and entityTypeId (KINDS_LIST) 76 | EntityTypeName name = EntityTypeName.of(projectId, entityTypeId); 77 | 78 | // Build the entity 79 | Entity entity = Entity.newBuilder() 80 | .setValue(entityValue) 81 | .addAllSynonyms(synonyms) 82 | .build(); 83 | 84 | // Performs the create entity type request 85 | Empty response = entityTypesClient.batchCreateEntitiesAsync(name, 86 | Arrays.asList(entity)).get(); 87 | System.out.println("Entity created: " + response); 88 | } 89 | 90 | 91 | } 92 | // [END dialogflow_create_entity] 93 | 94 | // [START dialogflow_delete_entity] 95 | /** 96 | * Delete entity with the given entity type and entity value 97 | * @param projectId Project/agent id. 98 | * @param entityTypeId The id of the entity_type. 99 | * @param entityValue The value of the entity to delete. 100 | */ 101 | public static void deleteEntity(String projectId, String entityTypeId, String entityValue) 102 | throws Exception { 103 | // Instantiates a client 104 | try (EntityTypesClient entityTypesClient = EntityTypesClient.create()) { 105 | // Set the entity type name using the projectID (my-project-id) and entityTypeId (KINDS_LIST) 106 | EntityTypeName name = EntityTypeName.of(projectId, entityTypeId); 107 | 108 | // Performs the delete entity type request 109 | entityTypesClient.batchDeleteEntitiesAsync(name, Arrays.asList(entityValue)) 110 | .getInitialFuture().get(); 111 | } 112 | } 113 | // [END dialogflow_delete_entity] 114 | 115 | // [START run_application] 116 | public static void main(String[] args) throws Exception { 117 | String method = ""; 118 | String entityTypeId = ""; 119 | String entityValue = ""; 120 | List synonyms = new ArrayList<>(); 121 | String projectId = ""; 122 | 123 | try { 124 | method = args[0]; 125 | String command = args[1]; 126 | if (method.equals("list")) { 127 | if (command.equals("--projectId")) { 128 | projectId = args[2]; 129 | } 130 | 131 | command = args[3]; 132 | if (command.equals("--entityTypeId")) { 133 | entityTypeId = args[4]; 134 | } 135 | } else if (method.equals("create") || method.equals("delete")) { 136 | entityValue = command; 137 | command = args[2]; 138 | if (command.equals("--projectId")) { 139 | projectId = args[3]; 140 | } 141 | 142 | command = args[4]; 143 | if (command.equals("--entityTypeId")) { 144 | entityTypeId = args[5]; 145 | } 146 | 147 | if (method.equals("create") && args.length > 5) { 148 | command = args[6]; 149 | if (command.equals("--synonyms")) { 150 | for (int i = 7; i < args.length; i++) { 151 | synonyms.add(args[i]); 152 | } 153 | } 154 | } 155 | } 156 | } catch (Exception e) { 157 | System.out.println("Usage:"); 158 | System.out.println("mvn exec:java -DEntityManagement " 159 | + "-Dexec.args='list --projectId PROJECT_ID " 160 | + "--entityTypeId e57238e2-e692-44ea-9216-6be1b2332e2a'\n"); 161 | 162 | System.out.print("mvn exec:java -DEntityManagement " 163 | + "-Dexec.args='create new_room --projectId PROJECT_ID " 164 | + "--entityTypeId e57238e2-e692-44ea-9216-6be1b2332e2a" 165 | + "--synonyms basement cellar'\n"); 166 | 167 | System.out.print("mvn exec:java -DEntityManagement " 168 | + "-Dexec.args='delete new_room --projectId PROJECT_ID " 169 | + "--entityTypeId e57238e2-e692-44ea-9216-6be1b2332e2a'\n"); 170 | 171 | System.out.println("Commands: list"); 172 | System.out.println("\t--projectId - Project/Agent Id"); 173 | System.out.println("\nCommands: create | delete"); 174 | System.out.println("\t - The entity value to be added."); 175 | System.out.println("\t--projectId - Project/Agent Id"); 176 | System.out.println("\t--entityTypeId - [For create | delete] The id of the " 177 | + "entityType to which to add an entity."); 178 | System.out.println("\nOptional Commands [For create]:"); 179 | System.out.println("\t--synonyms - The synonyms that will map to the provided " 180 | + "entity value."); 181 | } 182 | 183 | if (method.equals("list")) { 184 | listEntities(projectId, entityTypeId); 185 | } else if (method.equals("create")) { 186 | createEntity(projectId, entityTypeId, entityValue, synonyms); 187 | } else if (method.equals("delete")) { 188 | deleteEntity(projectId, entityTypeId, entityValue); 189 | } 190 | } 191 | // [END run_application] 192 | } 193 | -------------------------------------------------------------------------------- /samples/src/main/java/com/example/dialogflow/EntityTypeManagement.java: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2017, Google, Inc. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package com.example.dialogflow; 18 | 19 | // [START dialogflow_import_libraries] 20 | // Imports the Google Cloud client library 21 | import com.google.cloud.dialogflow.v2.EntityType; 22 | import com.google.cloud.dialogflow.v2.EntityType.Kind; 23 | import com.google.cloud.dialogflow.v2.EntityTypeName; 24 | import com.google.cloud.dialogflow.v2.EntityTypesClient; 25 | import com.google.cloud.dialogflow.v2.ProjectAgentName; 26 | 27 | import java.util.ArrayList; 28 | import java.util.List; 29 | // [END dialogflow_import_libraries] 30 | 31 | /** 32 | * DialogFlow API EntityType sample. 33 | */ 34 | public class EntityTypeManagement { 35 | 36 | /** 37 | * List entity types 38 | * @param projectId Project/agent id. 39 | */ 40 | public static void listEntityTypes(String projectId) throws Exception { 41 | // Instantiates a client 42 | try (EntityTypesClient entityTypesClient = EntityTypesClient.create()) { 43 | // Set the project agent name using the projectID (my-project-id) 44 | ProjectAgentName parent = ProjectAgentName.of(projectId); 45 | 46 | // Performs the list entity types request 47 | for (EntityType entityType : entityTypesClient.listEntityTypes(parent).iterateAll()) { 48 | System.out.format("Entity type name %s\n", entityType.getName()); 49 | System.out.format("Entity type display name: %s\n", entityType.getDisplayName()); 50 | System.out.format("Number of entities: %d\n", entityType.getEntitiesCount()); 51 | } 52 | } 53 | } 54 | 55 | // [START dialogflow_create_entity_type] 56 | /** 57 | * Create an entity type with the given display name 58 | * @param displayName The display name of the entity. 59 | * @param projectId Project/agent id. 60 | * @param kind The kind of entity. KIND_MAP (default) or KIND_LIST. 61 | */ 62 | public static void createEntityType(String displayName, String projectId, String kind) 63 | throws Exception { 64 | // Instantiates a client 65 | try (EntityTypesClient entityTypesClient = EntityTypesClient.create()) { 66 | // Set the project agent name using the projectID (my-project-id) 67 | ProjectAgentName parent = ProjectAgentName.of(projectId); 68 | 69 | // Entity types serve as a tool for extracting parameter values from natural language queries. 70 | EntityType entityType = EntityType.newBuilder() 71 | .setDisplayName(displayName) 72 | .setKind(Kind.valueOf(kind)) 73 | .build(); 74 | 75 | // Performs the create entity type request 76 | EntityType response = entityTypesClient.createEntityType(parent, entityType); 77 | System.out.println("Entity type created: " + response); 78 | } 79 | } 80 | // [END dialogflow_create_entity_type] 81 | 82 | // [START dialogflow_delete_entity_type] 83 | /** 84 | * Delete entity type with the given entity type name 85 | * @param entityTypeId The id of the entity_type. 86 | * @param projectId Project/agent id. 87 | */ 88 | public static void deleteEntityType(String entityTypeId, String projectId) throws Exception { 89 | // Instantiates a client 90 | try (EntityTypesClient entityTypesClient = EntityTypesClient.create()) { 91 | // Set the entity type name using the projectID (my-project-id) and entityTypeId (KIND_LIST) 92 | EntityTypeName name = EntityTypeName.of(projectId, entityTypeId); 93 | 94 | // Performs the delete entity type request 95 | entityTypesClient.deleteEntityType(name); 96 | } 97 | } 98 | // [END dialogflow_delete_entity_type] 99 | 100 | /** 101 | * Helper method for testing to get entityTypeId from displayName. 102 | */ 103 | public static List getEntityTypeIds(String displayName, String projectId) 104 | throws Exception { 105 | List entityTypesIds = new ArrayList<>(); 106 | 107 | try (EntityTypesClient entityTypesClient = EntityTypesClient.create()) { 108 | ProjectAgentName parent = ProjectAgentName.of(projectId); 109 | // Performs the list entity types request 110 | for (EntityType entityType : entityTypesClient.listEntityTypes(parent).iterateAll()) { 111 | if (entityType.getDisplayName().equals(displayName)) { 112 | String[] splitName = entityType.getName().split("/"); 113 | entityTypesIds.add(splitName[splitName.length - 1]); 114 | } 115 | } 116 | } 117 | return entityTypesIds; 118 | } 119 | 120 | // [START run_application] 121 | public static void main(String[] args) throws Exception { 122 | String method = ""; 123 | String entityTypeId = ""; 124 | String displayName = ""; 125 | String kind = "KIND_MAP"; 126 | String projectId = ""; 127 | 128 | try { 129 | method = args[0]; 130 | String command; 131 | if (method.equals("list")) { 132 | command = args[1]; 133 | if (command.equals("--projectId")) { 134 | projectId = args[2]; 135 | } 136 | } else if (method.equals("create")) { 137 | displayName = args[1]; 138 | 139 | command = args[2]; 140 | if (command.equals("--projectId")) { 141 | projectId = args[3]; 142 | } 143 | 144 | if (args.length > 4) { 145 | command = args[4]; 146 | if (command.equals("--kind")) { 147 | kind = args[5]; 148 | } 149 | } 150 | } else if (method.equals("delete")) { 151 | entityTypeId = args[1]; 152 | 153 | command = args[2]; 154 | if (command.equals("--projectId")) { 155 | projectId = args[3]; 156 | } 157 | } 158 | } catch (Exception e) { 159 | System.out.println("Usage:"); 160 | System.out.println("mvn exec:java -DEntityTypeManagement " 161 | + "-Dexec.args='list --projectId PROJECT_ID'\n"); 162 | 163 | System.out.println("mvn exec:java -DEntityTypeManagement " 164 | + "-Dexec.args='create employee --projectId PROJECT_ID'\n"); 165 | 166 | System.out.println("mvn exec:java -DEntityTypeManagement " 167 | + "-Dexec.args='delete ENTITY_TYPE_ID --projectId PROJECT_ID'\n"); 168 | 169 | System.out.println("Commands: list"); 170 | System.out.println("\t--projectId - Project/Agent Id"); 171 | System.out.println("Commands: create"); 172 | System.out.println("\t - The display name of the entity."); 173 | System.out.println("\t--projectId - Project/Agent Id"); 174 | System.out.println("\nOptional Commands [For create]:"); 175 | System.out.println("\t--kind - The kind of entity. KIND_MAP (default) or KIND_LIST."); 176 | System.out.println("Commands: delete"); 177 | System.out.println("\t - [The id of the entity_type."); 178 | System.out.println("\t--projectId - Project/Agent Id"); 179 | } 180 | 181 | if (method.equals("list")) { 182 | listEntityTypes(projectId); 183 | } else if (method.equals("create")) { 184 | createEntityType(displayName, projectId, kind); 185 | } else if (method.equals("delete")) { 186 | deleteEntityType(entityTypeId, projectId); 187 | } 188 | } 189 | // [END run_application] 190 | } 191 | -------------------------------------------------------------------------------- /samples/src/main/java/com/example/dialogflow/IntentManagement.java: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2017, Google, Inc. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package com.example.dialogflow; 18 | 19 | // [START dialogflow_import_libraries] 20 | // Imports the Google Cloud client library 21 | import com.google.cloud.dialogflow.v2.Context; 22 | import com.google.cloud.dialogflow.v2.Intent; 23 | import com.google.cloud.dialogflow.v2.Intent.Message; 24 | import com.google.cloud.dialogflow.v2.Intent.Message.Text; 25 | import com.google.cloud.dialogflow.v2.Intent.TrainingPhrase; 26 | import com.google.cloud.dialogflow.v2.Intent.TrainingPhrase.Part; 27 | import com.google.cloud.dialogflow.v2.IntentName; 28 | import com.google.cloud.dialogflow.v2.IntentsClient; 29 | import com.google.cloud.dialogflow.v2.ProjectAgentName; 30 | 31 | import java.util.ArrayList; 32 | import java.util.List; 33 | // [END dialogflow_import_libraries] 34 | 35 | /** 36 | * DialogFlow API Intent sample. 37 | */ 38 | public class IntentManagement { 39 | 40 | // [START dialogflow_list_intents] 41 | /** 42 | * List intents 43 | * @param projectId Project/Agent Id. 44 | */ 45 | public static void listIntents(String projectId) throws Exception { 46 | // Instantiates a client 47 | try (IntentsClient intentsClient = IntentsClient.create()) { 48 | // Set the project agent name using the projectID (my-project-id) 49 | ProjectAgentName parent = ProjectAgentName.of(projectId); 50 | 51 | // Performs the list intents request 52 | for (Intent intent : intentsClient.listIntents(parent).iterateAll()) { 53 | System.out.println("===================="); 54 | System.out.format("Intent name: '%s'\n", intent.getName()); 55 | System.out.format("Intent display name: '%s'\n", intent.getDisplayName()); 56 | System.out.format("Action: '%s'\n", intent.getAction()); 57 | System.out.format("Root followup intent: '%s'\n", intent.getRootFollowupIntentName()); 58 | System.out.format("Parent followup intent: '%s'\n", intent.getParentFollowupIntentName()); 59 | 60 | System.out.format("Input contexts:\n"); 61 | for (String inputContextName : intent.getInputContextNamesList()) { 62 | System.out.format("\tName: %s\n", inputContextName); 63 | } 64 | 65 | System.out.format("Output contexts:\n"); 66 | for (Context outputContext : intent.getOutputContextsList()) { 67 | System.out.format("\tName: %s\n", outputContext.getName()); 68 | } 69 | } 70 | } 71 | } 72 | // [END dialogflow_list_intents] 73 | 74 | // [START dialogflow_create_intent] 75 | /** 76 | * Create an intent of the given intent type 77 | * @param displayName The display name of the intent. 78 | * @param projectId Project/Agent Id. 79 | * @param trainingPhrasesParts Training phrases. 80 | * @param messageTexts Message texts for the agent's response when the intent is detected. 81 | */ 82 | public static void createIntent(String displayName, String projectId, 83 | List trainingPhrasesParts, List messageTexts) 84 | throws Exception { 85 | // Instantiates a client 86 | try (IntentsClient intentsClient = IntentsClient.create()) { 87 | // Set the project agent name using the projectID (my-project-id) 88 | ProjectAgentName parent = ProjectAgentName.of(projectId); 89 | 90 | // Build the trainingPhrases from the trainingPhrasesParts 91 | List trainingPhrases = new ArrayList<>(); 92 | for (String trainingPhrase : trainingPhrasesParts) { 93 | trainingPhrases.add( 94 | TrainingPhrase.newBuilder().addParts( 95 | Part.newBuilder().setText(trainingPhrase).build()) 96 | .build()); 97 | } 98 | 99 | // Build the message texts for the agent's response 100 | Message message = Message.newBuilder() 101 | .setText( 102 | Text.newBuilder() 103 | .addAllText(messageTexts).build() 104 | ).build(); 105 | 106 | // Build the intent 107 | Intent intent = Intent.newBuilder() 108 | .setDisplayName(displayName) 109 | .addMessages(message) 110 | .addAllTrainingPhrases(trainingPhrases) 111 | .build(); 112 | 113 | // Performs the create intent request 114 | Intent response = intentsClient.createIntent(parent, intent); 115 | System.out.format("Intent created: %s\n", response); 116 | } 117 | } 118 | // [END dialogflow_create_intent] 119 | 120 | // [START dialogflow_delete_intent] 121 | /** 122 | * Delete intent with the given intent type and intent value 123 | * @param intentId The id of the intent. 124 | * @param projectId Project/Agent Id. 125 | */ 126 | public static void deleteIntent(String intentId, String projectId) throws Exception { 127 | // Instantiates a client 128 | try (IntentsClient intentsClient = IntentsClient.create()) { 129 | IntentName name = IntentName.of(projectId, intentId); 130 | // Performs the delete intent request 131 | intentsClient.deleteIntent(name); 132 | } 133 | } 134 | // [END dialogflow_delete_intent] 135 | 136 | /** 137 | * Helper method for testing to get intentIds from displayName. 138 | */ 139 | public static List getIntentIds(String displayName, String projectId) throws Exception { 140 | List intentIds = new ArrayList<>(); 141 | 142 | // Instantiates a client 143 | try (IntentsClient intentsClient = IntentsClient.create()) { 144 | ProjectAgentName parent = ProjectAgentName.of(projectId); 145 | for (Intent intent : intentsClient.listIntents(parent).iterateAll()) { 146 | if (intent.getDisplayName().equals(displayName)) { 147 | String[] splitName = intent.getName().split("/"); 148 | intentIds.add(splitName[splitName.length - 1]); 149 | } 150 | } 151 | } 152 | 153 | return intentIds; 154 | } 155 | 156 | public static void main(String[] args) throws Exception { 157 | String method = ""; 158 | String displayName = ""; 159 | String intentId = ""; 160 | List messageTexts = new ArrayList<>(); 161 | List trainingPhrasesParts = new ArrayList<>(); 162 | String projectId = ""; 163 | 164 | try { 165 | method = args[0]; 166 | String command = args[1]; 167 | if (method.equals("list")) { 168 | if (command.equals("--projectId")) { 169 | projectId = args[2]; 170 | } 171 | } else if (method.equals("create")) { 172 | displayName = args[1]; 173 | command = args[2]; 174 | if (command.equals("--projectId")) { 175 | projectId = args[3]; 176 | } 177 | 178 | for (int i = 4; i < args.length; i += 2) { 179 | if (args[i].equals("--messageTexts")) { 180 | while ((i + 1) < args.length && !args[(i + 1)].contains("--")) { 181 | messageTexts.add(args[++i]); 182 | } 183 | } else if (args[i].equals("--trainingPhrasesParts")) { 184 | while ((i + 1) < args.length && !args[(i + 1)].contains("--")) { 185 | trainingPhrasesParts.add(args[++i]); 186 | } 187 | } 188 | } 189 | } else if (method.equals("delete")) { 190 | intentId = args[1]; 191 | command = args[2]; 192 | if (command.equals("--projectId")) { 193 | projectId = args[3]; 194 | } 195 | } 196 | } catch (Exception e) { 197 | System.out.println("Usage:"); 198 | System.out.println("mvn exec:java -DIntentManagement " 199 | + "-Dexec.args='list --projectId PROJECT_ID'\n"); 200 | 201 | System.out.println("mvn exec:java -DIntentManagement " 202 | + "-Dexec.args='create \"room.cancellation - yes\" --projectId PROJECT_ID " 203 | + "--trainingPhrasesParts \"cancel\" \"cancellation\"" 204 | + "--messageTexts \"Are you sure you want to cancel?\" \"Cancelled.\"'\n"); 205 | 206 | System.out.println("mvn exec:java -DIntentManagement " 207 | + "-Dexec.args='delete INTENT_ID --projectId PROJECT_ID'\n"); 208 | 209 | System.out.println("Commands: list"); 210 | System.out.println("\t--projectId - Project/Agent Id"); 211 | 212 | System.out.println("Commands: create"); 213 | System.out.println("\t--projectId - Project/Agent Id"); 214 | System.out.println("\t - [For create] The display name of the intent."); 215 | System.out.println("\nOptional Commands [For create]:"); 216 | System.out.println("\t--trainingPhrasesParts - Training phrases."); 217 | System.out.println("\t--messageTexts - Message texts for the agent's " 218 | + "response when the intent is detected."); 219 | 220 | System.out.println("Commands: delete"); 221 | System.out.println("\t--projectId - Project/Agent Id"); 222 | System.out.println("\t - [For delete] The id of the intent."); 223 | } 224 | 225 | if (method.equals("list")) { 226 | listIntents(projectId); 227 | } else if (method.equals("create")) { 228 | createIntent(displayName, projectId, trainingPhrasesParts, messageTexts); 229 | } else if (method.equals("delete")) { 230 | deleteIntent(intentId, projectId); 231 | } 232 | } 233 | } 234 | -------------------------------------------------------------------------------- /samples/src/main/java/com/example/dialogflow/KnowledgebaseManagement.java: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2018, Google, Inc. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package com.example.dialogflow; 18 | 19 | import com.google.cloud.dialogflow.v2beta1.KnowledgeBase; 20 | import com.google.cloud.dialogflow.v2beta1.KnowledgeBaseName; 21 | import com.google.cloud.dialogflow.v2beta1.KnowledgeBasesClient; 22 | import com.google.cloud.dialogflow.v2beta1.ProjectName; 23 | 24 | public class KnowledgebaseManagement { 25 | 26 | // [START dialogflow_list_knowledge_base] 27 | /** 28 | * List Knowledge bases 29 | * 30 | * @param projectId Project/agent id. 31 | */ 32 | public static void listKnowledgeBases(String projectId) throws Exception { 33 | // Instantiates a client 34 | try (KnowledgeBasesClient knowledgeBasesClient = KnowledgeBasesClient.create()) { 35 | // Set the entity type name using the projectID (my-project-id) and entityTypeId (KIND_LIST) 36 | ProjectName projectName = ProjectName.of(projectId); 37 | for (KnowledgeBase knowledgeBase : 38 | knowledgeBasesClient.listKnowledgeBases(projectName).iterateAll()) { 39 | System.out.format(" - Display Name: %s\n", knowledgeBase.getDisplayName()); 40 | System.out.format(" - Knowledge ID: %s\n", knowledgeBase.getName()); 41 | } 42 | } 43 | } 44 | // [END dialogflow_list_knowledge_base] 45 | 46 | // [START dialogflow_create_knowledge_base] 47 | /** 48 | * Create a Knowledge base 49 | * 50 | * @param projectId Project/agent id. 51 | * @param displayName Name of the knowledge base. 52 | */ 53 | public static void createKnowledgeBase(String projectId, String displayName) throws Exception { 54 | // Instantiates a client 55 | try (KnowledgeBasesClient knowledgeBasesClient = KnowledgeBasesClient.create()) { 56 | 57 | KnowledgeBase knowledgeBase = KnowledgeBase.newBuilder().setDisplayName(displayName).build(); 58 | ProjectName projectName = ProjectName.of(projectId); 59 | KnowledgeBase response = knowledgeBasesClient.createKnowledgeBase(projectName, knowledgeBase); 60 | System.out.format("Knowledgebase created:\n"); 61 | System.out.format("Display Name: %s \n", response.getDisplayName()); 62 | System.out.format("Knowledge ID: %s \n", response.getName()); 63 | } 64 | } 65 | // [END dialogflow_create_knowledge_base] 66 | 67 | // [START dialogflow_get_knowledge_base] 68 | 69 | /** 70 | * @param knowledgeBaseId Knowledge base id. 71 | * @param projectId Project/agent id. 72 | * @throws Exception 73 | */ 74 | public static void getKnowledgeBase(String projectId, String knowledgeBaseId) throws Exception { 75 | 76 | // Instantiates a client 77 | try (KnowledgeBasesClient knowledgeBasesClient = KnowledgeBasesClient.create()) { 78 | KnowledgeBaseName knowledgeBaseName = KnowledgeBaseName.of(projectId, knowledgeBaseId); 79 | KnowledgeBase response = knowledgeBasesClient.getKnowledgeBase(knowledgeBaseName); 80 | System.out.format("Got Knowledge Base:\n"); 81 | System.out.format(" - Display Name: %s\n", response.getDisplayName()); 82 | System.out.format(" - Knowledge ID: %s\n", response.getName()); 83 | } 84 | } 85 | // [END dialogflow_get_knowledge_base] 86 | // [START dialogflow_delete_knowledge_base] 87 | 88 | /** 89 | * @param knowledgeBaseId Knowledge base id. 90 | * @param projectId Project/agent id. 91 | * @throws Exception 92 | */ 93 | public static void deleteKnowledgeBase(String projectId, String knowledgeBaseId) 94 | throws Exception { 95 | // Instantiates a client 96 | try (KnowledgeBasesClient knowledgeBasesClient = KnowledgeBasesClient.create()) { 97 | KnowledgeBaseName knowledgeBaseName = KnowledgeBaseName.of(projectId, knowledgeBaseId); 98 | knowledgeBasesClient.deleteKnowledgeBase(knowledgeBaseName); 99 | System.out.format("KnowledgeBase has been deleted.\n"); 100 | } 101 | } 102 | // [END dialogflow_delete_knowledge_base] 103 | 104 | // [START run_application] 105 | public static void main(String[] args) throws Exception { 106 | String method = ""; 107 | String displayName = ""; 108 | String knowledgeBaseId = ""; 109 | String projectId = ""; 110 | 111 | try { 112 | method = args[0]; 113 | String command = args[1]; 114 | if (method.equals("list")) { 115 | if (command.equals("--projectId")) { 116 | projectId = args[2]; 117 | } 118 | } else if (method.equals("create")) { 119 | displayName = args[1]; 120 | command = args[2]; 121 | if (command.equals("--projectId")) { 122 | projectId = args[3]; 123 | } 124 | 125 | } else if (method.equals("get")) { 126 | knowledgeBaseId = args[1]; 127 | command = args[2]; 128 | if (command.equals("--projectId")) { 129 | projectId = args[3]; 130 | } 131 | } else if (method.equals("delete")) { 132 | knowledgeBaseId = args[1]; 133 | command = args[2]; 134 | if (command.equals("--projectId")) { 135 | projectId = args[3]; 136 | } 137 | } 138 | 139 | } catch (Exception e) { 140 | System.out.println("Usage:"); 141 | System.out.println( 142 | "mvn exec:java -DKnowledgeManagement " 143 | + "-Dexec.args='list --projectId PROJECT_ID'\n" 144 | + "-Dexec.args='create test_create --projectId PROJECT_ID'\n" 145 | + "-Dexec.args='get KNOWLEDGE_BASE_ID --projectId PROJECT_ID'\n" 146 | + "-Dexec.args='delete KNOWLEDGE_BASE_ID --projectId PROJECT_ID'\n"); 147 | 148 | System.out.println("Commands: list"); 149 | System.out.println("\t--projectId - Project/Agent Id"); 150 | 151 | System.out.println("Commands: create"); 152 | System.out.println("\t - [For create] The display name of the knowledge base."); 153 | System.out.println("\t--projectId - Project/Agent Id"); 154 | 155 | System.out.println("Commands: get"); 156 | System.out.println("\t - [For get] The id of the knowledge base."); 157 | System.out.println("\t--projectId - Project/Agent Id"); 158 | 159 | System.out.println("Commands: delete"); 160 | System.out.println("\t - [For delete] The id of the knowledge base."); 161 | System.out.println("\t--projectId - Project/Agent Id"); 162 | } 163 | 164 | if (method.equals("list")) { 165 | listKnowledgeBases(projectId); 166 | } else if (method.equals("create")) { 167 | createKnowledgeBase(projectId,displayName); 168 | } else if (method.equals("get")) { 169 | getKnowledgeBase(projectId,knowledgeBaseId); 170 | } else if (method.equals("delete")) { 171 | deleteKnowledgeBase(projectId, knowledgeBaseId); 172 | } 173 | } 174 | } 175 | -------------------------------------------------------------------------------- /samples/src/main/java/com/example/dialogflow/SessionEntityTypeManagement.java: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2017, Google, Inc. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package com.example.dialogflow; 18 | 19 | // [START dialogflow_import_libraries] 20 | // Imports the Google Cloud client library 21 | import com.google.cloud.dialogflow.v2.EntityType.Entity; 22 | import com.google.cloud.dialogflow.v2.SessionEntityType; 23 | import com.google.cloud.dialogflow.v2.SessionEntityType.EntityOverrideMode; 24 | import com.google.cloud.dialogflow.v2.SessionEntityTypeName; 25 | import com.google.cloud.dialogflow.v2.SessionEntityTypesClient; 26 | import com.google.cloud.dialogflow.v2.SessionName; 27 | 28 | import java.util.ArrayList; 29 | import java.util.List; 30 | // [END dialogflow_import_libraries] 31 | 32 | /** 33 | * DialogFlow API SessionEntityType sample. 34 | */ 35 | public class SessionEntityTypeManagement { 36 | 37 | /** 38 | * List session entity types 39 | * @param projectId Project/Agent Id. 40 | * @param sessionId Identifier of the DetectIntent session. 41 | */ 42 | public static void listSessionEntityTypes(String projectId, String sessionId) throws Exception { 43 | // Instantiates a client 44 | try (SessionEntityTypesClient sessionEntityTypesClient = SessionEntityTypesClient.create()) { 45 | // Set the session name using the sessionId (UUID) and projectID (my-project-id) 46 | SessionName session = SessionName.of(projectId, sessionId); 47 | 48 | System.out.format("SessionEntityTypes for session %s:\n", session.toString()); 49 | // Performs the list session entity types request 50 | for (SessionEntityType sessionEntityType : 51 | sessionEntityTypesClient.listSessionEntityTypes(session).iterateAll()) { 52 | System.out.format("\tSessionEntityType name: %s\n", sessionEntityType.getName()); 53 | System.out.format("\tNumber of entities: %d\n", sessionEntityType.getEntitiesCount()); 54 | } 55 | } 56 | } 57 | 58 | // [START dialogflow_create_session_entity_type] 59 | /** 60 | * Create an entity type with the given display name 61 | * @param projectId Project/Agent Id. 62 | * @param sessionId Identifier of the DetectIntent session. 63 | * @param entityValues The entity values of the session entity type. 64 | * @param entityTypeDisplayName DISPLAY NAME of the entity type to be overridden in the session. 65 | * @param entityOverrideMode ENTITY_OVERRIDE_MODE_OVERRIDE (default) or 66 | * ENTITY_OVERRIDE_MODE_SUPPLEMENT 67 | */ 68 | public static void createSessionEntityType(String projectId, String sessionId, 69 | List entityValues, String entityTypeDisplayName,int entityOverrideMode) 70 | throws Exception { 71 | // Instantiates a client 72 | try (SessionEntityTypesClient sessionEntityTypesClient = SessionEntityTypesClient.create()) { 73 | // Set the session name using the sessionId (UUID) and projectID (my-project-id) 74 | SessionName session = SessionName.of(projectId, sessionId); 75 | SessionEntityTypeName name = SessionEntityTypeName.of(projectId, sessionId, 76 | entityTypeDisplayName); 77 | 78 | List entities = new ArrayList<>(); 79 | for (String entityValue : entityValues) { 80 | entities.add(Entity.newBuilder() 81 | .setValue(entityValue) 82 | .addSynonyms(entityValue) 83 | .build()); 84 | } 85 | 86 | // Extends or replaces a developer entity type at the user session level (we refer to the 87 | // entity types defined at the agent level as "developer entity types"). 88 | SessionEntityType sessionEntityType = SessionEntityType.newBuilder() 89 | .setName(name.toString()) 90 | .addAllEntities(entities) 91 | .setEntityOverrideMode(EntityOverrideMode.forNumber(entityOverrideMode)) 92 | .build(); 93 | 94 | // Performs the create session entity type request 95 | SessionEntityType response = sessionEntityTypesClient.createSessionEntityType(session, 96 | sessionEntityType); 97 | 98 | System.out.format("SessionEntityType created: %s\n", response); 99 | } 100 | } 101 | // [END dialogflow_create_session_entity_type] 102 | 103 | // [START dialogflow_delete_session_entity_type] 104 | /** 105 | * Delete entity type with the given entity type name 106 | * @param projectId Project/Agent Id. 107 | * @param sessionId Identifier of the DetectIntent session. 108 | * @param entityTypeDisplayName DISPLAY NAME of the entity type to be overridden in the session. 109 | */ 110 | public static void deleteSessionEntityType( String projectId, String sessionId, 111 | String entityTypeDisplayName) throws Exception { 112 | // Instantiates a client 113 | try (SessionEntityTypesClient sessionEntityTypesClient = SessionEntityTypesClient.create()) { 114 | SessionEntityTypeName name = SessionEntityTypeName.of(projectId, sessionId, 115 | entityTypeDisplayName); 116 | 117 | // Performs the delete session entity type request 118 | sessionEntityTypesClient.deleteSessionEntityType(name); 119 | } 120 | } 121 | // [END dialogflow_delete_session_entity_type] 122 | 123 | // [START run_application] 124 | public static void main(String[] args) throws Exception { 125 | String method = ""; 126 | String sessionId = ""; 127 | List entityValues = new ArrayList<>(); 128 | String entityTypeDisplayName = ""; 129 | int entityOverrideMode = 1; 130 | String projectId = ""; 131 | 132 | try { 133 | method = args[0]; 134 | String command = args[1]; 135 | if (command.equals("--projectId")) { 136 | projectId = args[2]; 137 | } 138 | command = args[3]; 139 | if (command.equals("--sessionId")) { 140 | sessionId = args[4]; 141 | } 142 | 143 | if (method.equals("create")) { 144 | command = args[5]; 145 | if (command.equals("--entityTypeDisplayName")) { 146 | entityTypeDisplayName = args[6]; 147 | } 148 | 149 | for (int i = 7; i < args.length; i += 2) { 150 | if (args[i].equals("--entityOverrideMode")) { 151 | entityOverrideMode = Integer.valueOf(args[i + 1]); 152 | } else if (args[i].equals("--entityValues")) { 153 | while ((i + 1) < args.length && !args[(i + 1)].contains("--")) { 154 | entityValues.add(args[++i]); 155 | } 156 | } 157 | } 158 | } else if (method.equals("delete")) { 159 | command = args[5]; 160 | if (command.equals("--entityTypeDisplayName")) { 161 | entityTypeDisplayName = args[6]; 162 | } 163 | } 164 | } catch (Exception e) { 165 | System.out.println("Usage:"); 166 | System.out.println("mvn exec:java -DSessionEntityTypeManagement " 167 | + "-Dexec.args='list --projectId PROJECT_ID --sessionId SESSION_ID'\n"); 168 | 169 | System.out.println("mvn exec:java -DSessionEntityTypeManagement " 170 | + "-Dexec.args='create create --projectId PROJECT_ID --sessionId SESSION_ID " 171 | + "--entityTypeDisplayName room --entityValues C D E F'\n"); 172 | 173 | System.out.println("mvn exec:java -DSessionEntityTypeManagement " 174 | + "-Dexec.args='delete --projectId PROJECT_ID --sessionId SESSION_ID " 175 | + "--entityTypeDisplayName room'\n"); 176 | 177 | System.out.println("Commands: list | create | delete"); 178 | System.out.println("\t--projectId - Project/Agent Id"); 179 | System.out.println("\t--sessionId - Identifier of the DetectIntent session"); 180 | 181 | System.out.println("Commands: create"); 182 | System.out.println("\t--projectId - Project/Agent Id"); 183 | System.out.println("\t--sessionId - Identifier of the DetectIntent session"); 184 | System.out.println("\t--entityTypeDisplayName - " 185 | + "The DISPLAY NAME of the entity type to be overridden in the session."); 186 | System.out.println("\nOptional Commands [For create]:"); 187 | System.out.println("\t--entityOverrideMode - " 188 | + "ENTITY_OVERRIDE_MODE_OVERRIDE (default) or ENTITY_OVERRIDE_MODE_SUPPLEMENT"); 189 | System.out.println("\t--entityValues - " 190 | + "The entity values of the session entity type."); 191 | 192 | System.out.println("Commands: delete"); 193 | System.out.println("\t--projectId - Project/Agent Id"); 194 | System.out.println("\t--sessionId - Identifier of the DetectIntent session"); 195 | System.out.println("\t--entityTypeDisplayName - " 196 | + "The DISPLAY NAME of the entity type to be overridden in the session."); 197 | } 198 | 199 | if (method.equals("list")) { 200 | listSessionEntityTypes(projectId, sessionId); 201 | } else if (method.equals("create")) { 202 | createSessionEntityType(projectId, sessionId, entityValues, entityTypeDisplayName, 203 | entityOverrideMode); 204 | } else if (method.equals("delete")) { 205 | deleteSessionEntityType(projectId, sessionId, entityTypeDisplayName); 206 | } 207 | } 208 | // [END run_application] 209 | } 210 | -------------------------------------------------------------------------------- /samples/src/test/java/com/example/dialogflow/ContextManagementIT.java: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2017, Google, Inc. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package com.example.dialogflow; 18 | 19 | import static com.google.common.truth.Truth.assertThat; 20 | 21 | import org.junit.After; 22 | import org.junit.Before; 23 | import org.junit.Test; 24 | import org.junit.runner.RunWith; 25 | import org.junit.runners.JUnit4; 26 | 27 | import java.io.ByteArrayOutputStream; 28 | import java.io.PrintStream; 29 | import java.util.Arrays; 30 | 31 | /** 32 | * Integration (system) tests for {@link ContextManagement}. 33 | */ 34 | @RunWith(JUnit4.class) 35 | @SuppressWarnings("checkstyle:abbreviationaswordinname") 36 | public class ContextManagementIT { 37 | 38 | private ByteArrayOutputStream bout; 39 | private PrintStream out; 40 | 41 | private DetectIntentTexts detectIntentTexts; 42 | private ContextManagement contextManagement; 43 | private static String PROJECT_ID = System.getenv().get("GOOGLE_CLOUD_PROJECT"); 44 | private static String SESSION_ID = "fake_session_for_testing"; 45 | private static String CONTEXT_ID = "fake_context_for_testing"; 46 | 47 | @Before 48 | public void setUp() { 49 | bout = new ByteArrayOutputStream(); 50 | out = new PrintStream(bout); 51 | System.setOut(out); 52 | detectIntentTexts = new DetectIntentTexts(); 53 | contextManagement = new ContextManagement(); 54 | PROJECT_ID = System.getenv().get("GOOGLE_CLOUD_PROJECT"); 55 | } 56 | 57 | @After 58 | public void tearDown() { 59 | System.setOut(null); 60 | } 61 | 62 | @Test 63 | public void testCreateDeleteContext() throws Exception { 64 | // Calling detect intent to create a session 65 | detectIntentTexts.detectIntentTexts(PROJECT_ID, Arrays.asList("hi"), SESSION_ID, "en-US"); 66 | 67 | // Create the context 68 | contextManagement.createContext(CONTEXT_ID, SESSION_ID, PROJECT_ID, 1); 69 | contextManagement.listContexts(SESSION_ID, PROJECT_ID); 70 | 71 | String got = bout.toString(); 72 | assertThat(got).contains(CONTEXT_ID); 73 | 74 | // Delete the context 75 | bout.reset(); 76 | contextManagement.deleteContext(CONTEXT_ID, SESSION_ID, PROJECT_ID); 77 | contextManagement.listContexts(SESSION_ID, PROJECT_ID); 78 | 79 | got = bout.toString(); 80 | assertThat(got).doesNotContain(CONTEXT_ID); 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /samples/src/test/java/com/example/dialogflow/CreateDeleteEntityIT.java: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2017, Google, Inc. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package com.example.dialogflow; 18 | 19 | import static com.google.common.truth.Truth.assertThat; 20 | 21 | import org.junit.After; 22 | import org.junit.Before; 23 | import org.junit.FixMethodOrder; 24 | import org.junit.Test; 25 | import org.junit.runner.RunWith; 26 | import org.junit.runners.JUnit4; 27 | import org.junit.runners.MethodSorters; 28 | 29 | import java.io.ByteArrayOutputStream; 30 | import java.io.PrintStream; 31 | import java.util.Arrays; 32 | import java.util.List; 33 | 34 | 35 | /** 36 | * Integration (system) tests for {@link EntityManagement} and {@link EntityTypeManagement}. 37 | */ 38 | @RunWith(JUnit4.class) 39 | @FixMethodOrder(MethodSorters.NAME_ASCENDING) 40 | @SuppressWarnings("checkstyle:abbreviationaswordinname") 41 | public class CreateDeleteEntityIT { 42 | private static String ENTITY_TYPE_DISPLAY_NAME = "fake_entity_type_for_testing"; 43 | private static String ENTITY_VALUE_1 = "fake_entity_for_testing_1"; 44 | private static String ENTITY_VALUE_2 = "fake_entity_for_testing_2"; 45 | private static List SYNONYMS = Arrays.asList("fake_synonym_for_testing_1", 46 | "fake_synonym_for_testing_2"); 47 | 48 | private ByteArrayOutputStream bout; 49 | private PrintStream out; 50 | 51 | private EntityManagement entityManagement; 52 | private EntityTypeManagement entityTypeManagement; 53 | private static String PROJECT_ID = System.getenv().get("GOOGLE_CLOUD_PROJECT"); 54 | 55 | @Before 56 | public void setUp() { 57 | bout = new ByteArrayOutputStream(); 58 | out = new PrintStream(bout); 59 | System.setOut(out); 60 | entityManagement = new EntityManagement(); 61 | entityTypeManagement = new EntityTypeManagement(); 62 | } 63 | 64 | 65 | @After 66 | public void tearDown() { 67 | System.setOut(null); 68 | } 69 | 70 | @Test 71 | public void testCreateEntityType() throws Exception { 72 | List entityTypeIds = entityTypeManagement.getEntityTypeIds(ENTITY_TYPE_DISPLAY_NAME, 73 | PROJECT_ID); 74 | 75 | assertThat(entityTypeIds.size()).isEqualTo(0); 76 | 77 | entityTypeManagement.createEntityType(ENTITY_TYPE_DISPLAY_NAME, PROJECT_ID, "KIND_MAP"); 78 | 79 | String got = bout.toString(); 80 | assertThat(got).contains(String.format("display_name: \"%s\"", ENTITY_TYPE_DISPLAY_NAME)); 81 | 82 | entityTypeIds = entityTypeManagement.getEntityTypeIds(ENTITY_TYPE_DISPLAY_NAME, 83 | PROJECT_ID); 84 | 85 | assertThat(entityTypeIds.size()).isEqualTo(1); 86 | } 87 | 88 | @Test 89 | public void testCreateEntityWithCreatedEntityType() throws Exception { 90 | List entityTypeIds = entityTypeManagement.getEntityTypeIds(ENTITY_TYPE_DISPLAY_NAME, 91 | PROJECT_ID); 92 | 93 | entityManagement.createEntity(PROJECT_ID, entityTypeIds.get(0), ENTITY_VALUE_1, 94 | Arrays.asList("")); 95 | entityManagement.createEntity(PROJECT_ID, entityTypeIds.get(0), ENTITY_VALUE_2, SYNONYMS); 96 | 97 | entityManagement.listEntities(PROJECT_ID, entityTypeIds.get(0)); 98 | 99 | String got = bout.toString(); 100 | assertThat(got).contains(String.format("Entity value: %s", ENTITY_VALUE_1)); 101 | assertThat(got).contains(String.format("Entity value: %s", ENTITY_VALUE_2)); 102 | 103 | for (String synonym : SYNONYMS) { 104 | assertThat(got).contains(synonym); 105 | } 106 | } 107 | 108 | @Test 109 | public void testDeleteEntity() throws Exception { 110 | List entityTypeIds = entityTypeManagement.getEntityTypeIds(ENTITY_TYPE_DISPLAY_NAME, 111 | PROJECT_ID); 112 | 113 | entityManagement.deleteEntity(PROJECT_ID, entityTypeIds.get(0), ENTITY_VALUE_1); 114 | entityManagement.deleteEntity(PROJECT_ID, entityTypeIds.get(0), ENTITY_VALUE_2); 115 | 116 | entityManagement.listEntities(PROJECT_ID, entityTypeIds.get(0)); 117 | 118 | String got = bout.toString(); 119 | assertThat(got).isEqualTo(""); 120 | } 121 | 122 | @Test 123 | public void testDeleteEntityType() throws Exception { 124 | List entityTypeIds = entityTypeManagement.getEntityTypeIds(ENTITY_TYPE_DISPLAY_NAME, 125 | PROJECT_ID); 126 | 127 | for (String entityTypeId : entityTypeIds) { 128 | entityTypeManagement.deleteEntityType(entityTypeId, PROJECT_ID); 129 | } 130 | 131 | entityTypeIds = entityTypeManagement.getEntityTypeIds(ENTITY_TYPE_DISPLAY_NAME, PROJECT_ID); 132 | assertThat(entityTypeIds.size()).isEqualTo(0); 133 | } 134 | } 135 | -------------------------------------------------------------------------------- /samples/src/test/java/com/example/dialogflow/DetectIntentAudioIT.java: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2017, Google, Inc. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package com.example.dialogflow; 18 | 19 | import static com.google.common.truth.Truth.assertThat; 20 | 21 | import org.junit.After; 22 | import org.junit.Before; 23 | import org.junit.Test; 24 | import org.junit.runner.RunWith; 25 | import org.junit.runners.JUnit4; 26 | 27 | import java.io.ByteArrayOutputStream; 28 | import java.io.PrintStream; 29 | import java.util.Arrays; 30 | import java.util.List; 31 | 32 | /** 33 | * Integration (system) tests for {@link DetectIntentAudio}. 34 | */ 35 | @RunWith(JUnit4.class) 36 | @SuppressWarnings("checkstyle:abbreviationaswordinname") 37 | public class DetectIntentAudioIT { 38 | 39 | private ByteArrayOutputStream bout; 40 | private PrintStream out; 41 | private DetectIntentAudio detectIntentAudio; 42 | private static String PROJECT_ID = System.getenv().get("GOOGLE_CLOUD_PROJECT"); 43 | private static String SESSION_ID = "fake_session_for_testing"; 44 | private static String LANGUAGE_CODE = "en-US"; 45 | private static List AUDIOS = Arrays.asList( 46 | "resources/book_a_room.wav", 47 | "resources/mountain_view.wav", 48 | "resources/today.wav"); 49 | 50 | @Before 51 | public void setUp() { 52 | bout = new ByteArrayOutputStream(); 53 | out = new PrintStream(bout); 54 | System.setOut(out); 55 | detectIntentAudio = new DetectIntentAudio(); 56 | } 57 | 58 | @After 59 | public void tearDown() { 60 | System.setOut(null); 61 | } 62 | 63 | @Test 64 | public void testDetectIntent() throws Exception { 65 | for (String audioFilePath : AUDIOS) { 66 | detectIntentAudio.detectIntentAudio(PROJECT_ID, audioFilePath, SESSION_ID, LANGUAGE_CODE); 67 | } 68 | 69 | String got = bout.toString(); 70 | assertThat(got).contains("Fulfillment Text: 'What time will the meeting start?'"); 71 | } 72 | 73 | } 74 | -------------------------------------------------------------------------------- /samples/src/test/java/com/example/dialogflow/DetectIntentSentimentAnalysisIT.java: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2018, Google, Inc. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package com.example.dialogflow; 18 | 19 | import static com.google.common.truth.Truth.assertThat; 20 | 21 | import org.junit.After; 22 | import org.junit.Before; 23 | import org.junit.Test; 24 | import org.junit.runner.RunWith; 25 | import org.junit.runners.JUnit4; 26 | 27 | import java.io.ByteArrayOutputStream; 28 | import java.io.PrintStream; 29 | import java.util.Arrays; 30 | import java.util.List; 31 | 32 | /** 33 | * Integration (system) tests for {@link DetectIntentSentimentAnalysis}. 34 | */ 35 | @RunWith(JUnit4.class) 36 | @SuppressWarnings("checkstyle:abbreviationaswordinname") 37 | public class DetectIntentSentimentAnalysisIT { 38 | 39 | private ByteArrayOutputStream bout; 40 | private DetectIntentSentimentAnalysis detectIntentSentimentAnalysis; 41 | private PrintStream out; 42 | private static String PROJECT_ID = System.getenv().get("GOOGLE_CLOUD_PROJECT"); 43 | private static String SESSION_ID = "fake_session_for_testing"; 44 | private static String LANGUAGE_CODE = "en-US"; 45 | private static List TEXTS = Arrays.asList("hello", "book a meeting room", "Mountain View", 46 | "tomorrow", "10 am", "2 hours", "10 people", "A", "yes"); 47 | 48 | @Before 49 | public void setUp() { 50 | bout = new ByteArrayOutputStream(); 51 | out = new PrintStream(bout); 52 | System.setOut(out); 53 | detectIntentSentimentAnalysis = new DetectIntentSentimentAnalysis(); 54 | } 55 | 56 | @After 57 | public void tearDown() { 58 | System.setOut(null); 59 | } 60 | 61 | @Test 62 | public void testDetectIntent() throws Exception { 63 | detectIntentSentimentAnalysis.detectIntentSentimentAnalysis(PROJECT_ID, TEXTS, SESSION_ID, LANGUAGE_CODE); 64 | 65 | String got = bout.toString(); 66 | assertThat(got).contains("Sentiment Score:"); 67 | } 68 | 69 | } -------------------------------------------------------------------------------- /samples/src/test/java/com/example/dialogflow/DetectIntentStreamIT.java: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2017, Google, Inc. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package com.example.dialogflow; 18 | 19 | import static com.google.common.truth.Truth.assertThat; 20 | 21 | import org.junit.After; 22 | import org.junit.Before; 23 | import org.junit.Test; 24 | import org.junit.runner.RunWith; 25 | import org.junit.runners.JUnit4; 26 | 27 | import java.io.ByteArrayOutputStream; 28 | import java.io.PrintStream; 29 | 30 | /** 31 | * Integration (system) tests for {@link DetectIntentStream}. 32 | */ 33 | @RunWith(JUnit4.class) 34 | @SuppressWarnings("checkstyle:abbreviationaswordinname") 35 | public class DetectIntentStreamIT { 36 | 37 | private ByteArrayOutputStream bout; 38 | private PrintStream out; 39 | private static String audioFilePath = "resources/book_a_room.wav"; 40 | private DetectIntentStream detectIntentStream; 41 | private static String PROJECT_ID = System.getenv().get("GOOGLE_CLOUD_PROJECT"); 42 | private static String SESSION_ID = "fake_session_for_testing"; 43 | private static String LANGUAGE_CODE = "en-US"; 44 | 45 | @Before 46 | public void setUp() { 47 | bout = new ByteArrayOutputStream(); 48 | out = new PrintStream(bout); 49 | System.setOut(out); 50 | detectIntentStream = new DetectIntentStream(); 51 | } 52 | 53 | 54 | @After 55 | public void tearDown() { 56 | System.setOut(null); 57 | } 58 | 59 | 60 | @Test 61 | public void testStreamingDetectIntentCallable() throws Throwable { 62 | detectIntentStream.detectIntentStream(PROJECT_ID, audioFilePath, SESSION_ID, LANGUAGE_CODE); 63 | 64 | String got = bout.toString(); 65 | assertThat(got).contains("Intermediate transcript: 'book'"); 66 | assertThat(got).contains("Detected Intent: room.reservation"); 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /samples/src/test/java/com/example/dialogflow/DetectIntentTTSResponsesIT.java: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2018, Google, Inc. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package com.example.dialogflow; 18 | 19 | import static com.google.common.truth.Truth.assertThat; 20 | 21 | import org.junit.After; 22 | import org.junit.Before; 23 | import org.junit.Test; 24 | import org.junit.runner.RunWith; 25 | import org.junit.runners.JUnit4; 26 | 27 | import java.io.ByteArrayOutputStream; 28 | import java.io.PrintStream; 29 | import java.util.Arrays; 30 | import java.util.List; 31 | 32 | /** Integration (system) tests for {@link DetectIntentTTSResponses}. */ 33 | @RunWith(JUnit4.class) 34 | @SuppressWarnings("checkstyle:abbreviationaswordinname") 35 | public class DetectIntentTTSResponsesIT { 36 | 37 | private static String PROJECT_ID = System.getenv().get("GOOGLE_CLOUD_PROJECT"); 38 | private static String SESSION_ID = "fake_session_for_testing"; 39 | private static String LANGUAGE_CODE = "en-US"; 40 | private static List TEXTS = 41 | Arrays.asList( 42 | "hello", 43 | "book a meeting room", 44 | "Mountain View", 45 | "tomorrow", 46 | "10 am", 47 | "2 hours", 48 | "10 people", 49 | "A", 50 | "yes"); 51 | private ByteArrayOutputStream bout; 52 | private DetectIntentTTSResponses detectIntentTTSResponses; 53 | private PrintStream out; 54 | 55 | @Before 56 | public void setUp() { 57 | bout = new ByteArrayOutputStream(); 58 | out = new PrintStream(bout); 59 | System.setOut(out); 60 | detectIntentTTSResponses = new DetectIntentTTSResponses(); 61 | } 62 | 63 | @After 64 | public void tearDown() { 65 | System.setOut(null); 66 | } 67 | 68 | @Test 69 | public void testDetectIntent() throws Exception { 70 | detectIntentTTSResponses.detectIntentWithTexttoSpeech( 71 | PROJECT_ID, TEXTS, SESSION_ID, LANGUAGE_CODE); 72 | 73 | String got = bout.toString(); 74 | assertThat(got).contains("Fulfillment Text: 'All set!'"); 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /samples/src/test/java/com/example/dialogflow/DetectIntentTextsIT.java: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2017, Google, Inc. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package com.example.dialogflow; 18 | 19 | import static com.google.common.truth.Truth.assertThat; 20 | 21 | import org.junit.After; 22 | import org.junit.Before; 23 | import org.junit.Test; 24 | import org.junit.runner.RunWith; 25 | import org.junit.runners.JUnit4; 26 | 27 | import java.io.ByteArrayOutputStream; 28 | import java.io.PrintStream; 29 | import java.util.Arrays; 30 | import java.util.List; 31 | 32 | /** 33 | * Integration (system) tests for {@link DetectIntentTexts}. 34 | */ 35 | @RunWith(JUnit4.class) 36 | @SuppressWarnings("checkstyle:abbreviationaswordinname") 37 | public class DetectIntentTextsIT { 38 | 39 | private ByteArrayOutputStream bout; 40 | private DetectIntentTexts detectIntentTexts; 41 | private PrintStream out; 42 | private static String PROJECT_ID = System.getenv().get("GOOGLE_CLOUD_PROJECT"); 43 | private static String SESSION_ID = "fake_session_for_testing"; 44 | private static String LANGUAGE_CODE = "en-US"; 45 | private static List TEXTS = Arrays.asList("hello", "book a meeting room", "Mountain View", 46 | "tomorrow", "10 am", "2 hours", "10 people", "A", "yes"); 47 | 48 | @Before 49 | public void setUp() { 50 | bout = new ByteArrayOutputStream(); 51 | out = new PrintStream(bout); 52 | System.setOut(out); 53 | detectIntentTexts = new DetectIntentTexts(); 54 | } 55 | 56 | @After 57 | public void tearDown() { 58 | System.setOut(null); 59 | } 60 | 61 | @Test 62 | public void testDetectIntent() throws Exception { 63 | detectIntentTexts.detectIntentTexts(PROJECT_ID, TEXTS, SESSION_ID, LANGUAGE_CODE); 64 | 65 | String got = bout.toString(); 66 | assertThat(got).contains("Fulfillment Text: 'All set!'"); 67 | } 68 | 69 | } 70 | -------------------------------------------------------------------------------- /samples/src/test/java/com/example/dialogflow/DetectIntentWithModelSelectionIT.java: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2018, Google, Inc. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package com.example.dialogflow; 18 | 19 | import static com.google.common.truth.Truth.assertThat; 20 | 21 | import org.junit.After; 22 | import org.junit.Before; 23 | import org.junit.Test; 24 | import org.junit.runner.RunWith; 25 | import org.junit.runners.JUnit4; 26 | 27 | import java.io.ByteArrayOutputStream; 28 | import java.io.PrintStream; 29 | import java.util.Arrays; 30 | import java.util.List; 31 | 32 | /** Integration (system) tests for {@link DetectIntentWithModelSelection}. */ 33 | @RunWith(JUnit4.class) 34 | @SuppressWarnings("checkstyle:abbreviationaswordinname") 35 | public class DetectIntentWithModelSelectionIT { 36 | 37 | private static String PROJECT_ID = System.getenv().get("GOOGLE_CLOUD_PROJECT"); 38 | private static String SESSION_ID = "fake_session_for_testing"; 39 | private static String LANGUAGE_CODE = "en-US"; 40 | private static List AUDIOS = 41 | Arrays.asList( 42 | "resources/book_a_room.wav", "resources/mountain_view.wav", "resources/today.wav"); 43 | private ByteArrayOutputStream bout; 44 | private PrintStream out; 45 | private DetectIntentWithModelSelection detectIntentWithModelSelection; 46 | 47 | @Before 48 | public void setUp() { 49 | bout = new ByteArrayOutputStream(); 50 | out = new PrintStream(bout); 51 | System.setOut(out); 52 | detectIntentWithModelSelection = new DetectIntentWithModelSelection(); 53 | } 54 | 55 | @After 56 | public void tearDown() { 57 | System.setOut(null); 58 | } 59 | 60 | @Test 61 | public void testDetectIntent() throws Exception { 62 | for (String audioFilePath : AUDIOS) { 63 | detectIntentWithModelSelection.detectIntentWithModelSelection( 64 | PROJECT_ID, SESSION_ID, audioFilePath, LANGUAGE_CODE); 65 | } 66 | 67 | String got = bout.toString(); 68 | assertThat(got).contains("Fulfillment Text: 'What time will the meeting start?'"); 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /samples/src/test/java/com/example/dialogflow/IntentManagementIT.java: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2017, Google, Inc. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package com.example.dialogflow; 18 | 19 | import static com.google.common.truth.Truth.assertThat; 20 | 21 | import org.junit.After; 22 | import org.junit.Before; 23 | import org.junit.Test; 24 | import org.junit.runner.RunWith; 25 | import org.junit.runners.JUnit4; 26 | 27 | import java.io.ByteArrayOutputStream; 28 | import java.io.PrintStream; 29 | import java.util.Arrays; 30 | import java.util.List; 31 | 32 | /** 33 | * Integration (system) tests for {@link IntentManagement}. 34 | */ 35 | @RunWith(JUnit4.class) 36 | @SuppressWarnings("checkstyle:abbreviationaswordinname") 37 | public class IntentManagementIT { 38 | private static String INTENT_DISPLAY_NAME = "fake_display_name_for_testing"; 39 | private static List MESSAGE_TEXTS = Arrays.asList( 40 | "fake_message_text_for_testing_1", 41 | "fake_message_text_for_testing_2"); 42 | private static List TRAINING_PHRASE_PARTS = Arrays.asList( 43 | "fake_training_phrase_part_1", 44 | "fake_training_phrase_part_2"); 45 | private ByteArrayOutputStream bout; 46 | private PrintStream out; 47 | private static String PROJECT_ID = System.getenv().get("GOOGLE_CLOUD_PROJECT"); 48 | private IntentManagement intentManagement; 49 | 50 | @Before 51 | public void setUp() { 52 | bout = new ByteArrayOutputStream(); 53 | out = new PrintStream(bout); 54 | System.setOut(out); 55 | intentManagement = new IntentManagement(); 56 | } 57 | 58 | 59 | @After 60 | public void tearDown() { 61 | System.setOut(null); 62 | } 63 | 64 | @Test 65 | public void testCreateIntent() throws Exception { 66 | // Create the intent 67 | intentManagement.createIntent(INTENT_DISPLAY_NAME, PROJECT_ID, TRAINING_PHRASE_PARTS, 68 | MESSAGE_TEXTS); 69 | 70 | List intentIds = intentManagement.getIntentIds(INTENT_DISPLAY_NAME, PROJECT_ID); 71 | 72 | assertThat(intentIds.size()).isEqualTo(1); 73 | 74 | intentManagement.listIntents(PROJECT_ID); 75 | 76 | String got = bout.toString(); 77 | assertThat(got).contains(INTENT_DISPLAY_NAME); 78 | for (String messageText : MESSAGE_TEXTS) { 79 | assertThat(got).contains(messageText); 80 | } 81 | 82 | // Delete the intent 83 | bout.reset(); 84 | intentIds = intentManagement.getIntentIds(INTENT_DISPLAY_NAME, PROJECT_ID); 85 | 86 | for (String intentId : intentIds) { 87 | intentManagement.deleteIntent(intentId, PROJECT_ID); 88 | } 89 | 90 | intentManagement.listIntents(PROJECT_ID); 91 | 92 | got = bout.toString(); 93 | assertThat(got).doesNotContain(INTENT_DISPLAY_NAME); 94 | 95 | intentIds = intentManagement.getIntentIds(INTENT_DISPLAY_NAME, PROJECT_ID); 96 | 97 | assertThat(intentIds.size()).isEqualTo(0); 98 | } 99 | 100 | } 101 | -------------------------------------------------------------------------------- /samples/src/test/java/com/example/dialogflow/KnowledgeBaseIT.java: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2018, Google, Inc. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package com.example.dialogflow; 18 | 19 | import static com.google.common.truth.Truth.assertThat; 20 | 21 | import org.junit.After; 22 | import org.junit.Before; 23 | import org.junit.Test; 24 | import org.junit.runner.RunWith; 25 | import org.junit.runners.JUnit4; 26 | 27 | import java.io.ByteArrayOutputStream; 28 | import java.io.PrintStream; 29 | import java.util.Arrays; 30 | import java.util.List; 31 | 32 | /** 33 | * Integration (system) tests for { DetectIntentKnowledge, KnowledgeManagement, DocumentManagement }. 34 | */ 35 | @RunWith(JUnit4.class) 36 | @SuppressWarnings("checkstyle:abbreviationaswordinname") 37 | public class KnowledgeBaseIT { 38 | 39 | private ByteArrayOutputStream bout; 40 | private DetectIntentKnowledge detectIntentKnowledge; 41 | private KnowledgebaseManagement knowledgebaseManagement; 42 | private DocumentManagement documentManagement; 43 | private PrintStream out; 44 | private static String PROJECT_ID = System.getenv().get("GOOGLE_CLOUD_PROJECT"); 45 | private static String SESSION_ID = "fake_session_for_testing"; 46 | private static String LANGUAGE_CODE = "en-US"; 47 | private static String KNOWLEDGE_BASE_NAME = "fake_knowledge_base_name"; 48 | private static String DOCUMENT_BASE_NAME = "fake_document_name"; 49 | private String knowledgeBaseId = ""; 50 | private String documentId = ""; 51 | 52 | private static List TEXTS = Arrays.asList("Where is my data stored?"); 53 | 54 | @Before 55 | public void setUp() { 56 | bout = new ByteArrayOutputStream(); 57 | out = new PrintStream(bout); 58 | System.setOut(out); 59 | detectIntentKnowledge = new DetectIntentKnowledge(); 60 | knowledgebaseManagement = new KnowledgebaseManagement(); 61 | documentManagement = new DocumentManagement(); 62 | } 63 | 64 | @After 65 | public void tearDown() { 66 | System.setOut(null); 67 | } 68 | 69 | @Test 70 | public void testKnowledgeBase() throws Exception { 71 | // Check the knowledge base does not yet exist 72 | knowledgebaseManagement.listKnowledgeBases(PROJECT_ID); 73 | String got = bout.toString(); 74 | assertThat(got).doesNotContain("Display Name: " + KNOWLEDGE_BASE_NAME); 75 | 76 | // Create a Knowledge Base 77 | knowledgebaseManagement.createKnowledgeBase(PROJECT_ID,KNOWLEDGE_BASE_NAME); 78 | got = bout.toString(); 79 | assertThat(got).contains("Display Name: " + KNOWLEDGE_BASE_NAME); 80 | 81 | // List Knowledge Bases 82 | knowledgebaseManagement.listKnowledgeBases(PROJECT_ID); 83 | got = bout.toString(); 84 | assertThat(got).contains("Display Name: " + KNOWLEDGE_BASE_NAME); 85 | knowledgeBaseId = got.split("/knowledgeBases/")[2].trim(); 86 | 87 | // Get knowledge base 88 | knowledgebaseManagement.getKnowledgeBase(PROJECT_ID,knowledgeBaseId); 89 | got = bout.toString(); 90 | assertThat(got).contains("Display Name: " + KNOWLEDGE_BASE_NAME); 91 | 92 | // Create a Document 93 | documentManagement.createDocument(PROJECT_ID,knowledgeBaseId,DOCUMENT_BASE_NAME,"text/html","FAQ","https://cloud.google.com/storage/docs/faq"); 94 | got = bout.toString(); 95 | assertThat(got).contains("Display Name: " + DOCUMENT_BASE_NAME); 96 | 97 | // List the Document 98 | documentManagement.listDocuments(PROJECT_ID,knowledgeBaseId); 99 | got = bout.toString(); 100 | assertThat(got).contains("Display Name: " + DOCUMENT_BASE_NAME); 101 | documentId = got.split("documents/")[1].split("- MIME Type")[0].trim(); 102 | 103 | // Get the Document 104 | documentManagement.getDocument(PROJECT_ID,knowledgeBaseId,documentId); 105 | got = bout.toString(); 106 | assertThat(got).contains("Display Name: " + DOCUMENT_BASE_NAME); 107 | 108 | // Detect Intent with Knowledge Base 109 | detectIntentKnowledge.detectIntentKnowledge(PROJECT_ID, knowledgeBaseId,SESSION_ID, LANGUAGE_CODE,TEXTS); 110 | got = bout.toString(); 111 | assertThat(got).contains("Knowledge results"); 112 | 113 | // Delete the Document 114 | bout.reset(); 115 | documentManagement.deleteDocument(PROJECT_ID,knowledgeBaseId,documentId); 116 | got = bout.toString(); 117 | assertThat(got).contains("The document has been deleted."); 118 | 119 | // List the Document 120 | documentManagement.listDocuments(PROJECT_ID,knowledgeBaseId); 121 | got = bout.toString(); 122 | assertThat(got).doesNotContain("Display Name: " + DOCUMENT_BASE_NAME); 123 | 124 | // Delete the Knowledge Base 125 | knowledgebaseManagement.deleteKnowledgeBase(PROJECT_ID,knowledgeBaseId); 126 | 127 | // List Knowledge Bases 128 | knowledgebaseManagement.listKnowledgeBases(PROJECT_ID); 129 | got = bout.toString(); 130 | assertThat(got).doesNotContain("Display Name: " + KNOWLEDGE_BASE_NAME); 131 | 132 | } 133 | 134 | } -------------------------------------------------------------------------------- /samples/src/test/java/com/example/dialogflow/SessionEntityTypeIT.java: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2017, Google, Inc. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package com.example.dialogflow; 18 | 19 | import static com.google.common.truth.Truth.assertThat; 20 | 21 | import org.junit.After; 22 | import org.junit.Before; 23 | import org.junit.Test; 24 | import org.junit.runner.RunWith; 25 | import org.junit.runners.JUnit4; 26 | 27 | import java.io.ByteArrayOutputStream; 28 | import java.io.PrintStream; 29 | import java.util.Arrays; 30 | import java.util.List; 31 | 32 | /** 33 | * Integration (system) tests for {@link SessionEntityTypeManagement}. 34 | */ 35 | @RunWith(JUnit4.class) 36 | @SuppressWarnings("checkstyle:abbreviationaswordinname") 37 | public class SessionEntityTypeIT { 38 | private static String SESSION_ID = "fake_session_for_testing"; 39 | private static String ENTITY_TYPE_DISPLAY_NAME = "fake_display_name_for_testing"; 40 | private static List ENTITY_VALUES = Arrays.asList("fake_entity_value_1", 41 | "fake_entity_value_2"); 42 | private static String PROJECT_ID = System.getenv().get("GOOGLE_CLOUD_PROJECT"); 43 | private ByteArrayOutputStream bout; 44 | private PrintStream out; 45 | 46 | private SessionEntityTypeManagement sessionEntityTypeManagement; 47 | private EntityTypeManagement entityTypeManagement; 48 | 49 | @Before 50 | public void setUp() { 51 | bout = new ByteArrayOutputStream(); 52 | out = new PrintStream(bout); 53 | System.setOut(out); 54 | sessionEntityTypeManagement = new SessionEntityTypeManagement(); 55 | entityTypeManagement = new EntityTypeManagement(); 56 | } 57 | 58 | 59 | @After 60 | public void tearDown() { 61 | System.setOut(null); 62 | } 63 | 64 | 65 | @Test 66 | public void testCreateDeleteSessionEntityType() throws Exception { 67 | // Create session entity type 68 | String projectId = System.getenv().get("GOOGLE_CLOUD_PROJECT"); 69 | 70 | entityTypeManagement.createEntityType(ENTITY_TYPE_DISPLAY_NAME, PROJECT_ID, "KIND_MAP"); 71 | 72 | sessionEntityTypeManagement.createSessionEntityType(PROJECT_ID, SESSION_ID, ENTITY_VALUES, 73 | ENTITY_TYPE_DISPLAY_NAME, 1); 74 | 75 | sessionEntityTypeManagement.listSessionEntityTypes(PROJECT_ID, SESSION_ID); 76 | 77 | String got = bout.toString(); 78 | assertThat(got).contains(SESSION_ID); 79 | assertThat(got).contains(ENTITY_TYPE_DISPLAY_NAME); 80 | for (String entityValue : ENTITY_VALUES) { 81 | assertThat(got).contains(entityValue); 82 | } 83 | 84 | // Delete session entity type 85 | bout.reset(); 86 | sessionEntityTypeManagement.deleteSessionEntityType(PROJECT_ID, SESSION_ID, 87 | ENTITY_TYPE_DISPLAY_NAME); 88 | 89 | sessionEntityTypeManagement.listSessionEntityTypes(PROJECT_ID, SESSION_ID); 90 | 91 | got = bout.toString(); 92 | assertThat(got).doesNotContain(ENTITY_TYPE_DISPLAY_NAME); 93 | for (String entityValue : ENTITY_VALUES) { 94 | assertThat(got).doesNotContain(entityValue); 95 | } 96 | 97 | List entityTypesIds = entityTypeManagement.getEntityTypeIds(ENTITY_TYPE_DISPLAY_NAME, 98 | projectId); 99 | 100 | for (String entityTypeId : entityTypesIds) { 101 | entityTypeManagement.deleteEntityType(entityTypeId, projectId); 102 | } 103 | } 104 | } 105 | --------------------------------------------------------------------------------