├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── agent.zip ├── build-aws.gradle ├── build-gcp.gradle ├── build.gradle ├── settings.gradle └── src ├── main ├── java │ └── com │ │ └── example │ │ ├── ActionsAWSHandler.java │ │ ├── ActionsServlet.java │ │ └── MyActionsApp.java ├── resources │ └── resources_en_US.properties └── webapp │ └── WEB-INF │ └── appengine-web.xml └── test ├── java └── com │ └── example │ └── MyActionsAppTest.java └── resources ├── request_welcome.json └── response_welcome.json /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # How to become a contributor and submit your own code 2 | 3 | ## Contributor License Agreements 4 | 5 | We'd love to accept your sample apps and patches! Before we can take them, we 6 | have to jump a couple of legal hurdles. 7 | 8 | Please fill out either the individual or corporate Contributor License Agreement 9 | (CLA). 10 | 11 | * If you are an individual writing original source code and you're sure you 12 | own the intellectual property, then you'll need to sign an [individual CLA](https://developers.google.com/open-source/cla/individual). 13 | * If you work for a company that wants to allow you to contribute your work, 14 | then you'll need to sign a [corporate CLA](https://developers.google.com/open-source/cla/corporate). 15 | 16 | Follow either of the two links above to access the appropriate CLA and 17 | instructions for how to sign and return it. Once we receive it, we'll be able to 18 | accept your pull requests. 19 | 20 | ## Contributing A Patch 21 | 22 | 1. Submit an issue describing your proposed change to the repo in question. 23 | 1. The repo owner will respond to your issue promptly. 24 | 1. If your proposed change is accepted, and you haven't already done so, sign a 25 | Contributor License Agreement (see details above). 26 | 1. Fork the desired repo, develop and test your code changes. 27 | 1. Ensure that your code adheres to the existing style in the sample to which 28 | you are contributing. Refer to the 29 | [Google Cloud Platform Samples Style Guide](https://github.com/GoogleCloudPlatform/Template/wiki/style.html) for the 30 | recommended coding standards for this organization. 31 | 1. Ensure that your code has an appropriate set of unit tests which all pass. 32 | 1. Submit a pull request. -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Actions on Google: Webhook Boilerplate 2 | 3 | Boilerplate to help you get started quickly with the Java client library for Actions on Google. 4 | 5 | *:warning: Warning: Conversational Actions will be deprecated on June 13, 2023. For more information, 6 | see [Conversational Actions Sunset](https://goo.gle/ca-sunset).* 7 | 8 | :warning: This code sample was built using Dialogflow. We now recommend using [Actions Builder or the Actions SDK](https://developers.google.com/assistant/conversational/overview) to develop, test, and deploy Conversational Actions. 9 | 10 | ### Setup Instructions 11 | 12 | #### Action Configuration 13 | 1. From the [Actions on Google Console](https://console.actions.google.com/), New project (this will become your *Project ID*) > **Create Project**. 14 | 1. Scroll down to the **More Options** section, and click on the **Conversational** card. 15 | 1. From the top menu under **Develop** > **Actions** (left nav) > **Add your first action** > **BUILD** (this will bring you to the Dialogflow console) > Select language and time zone > **CREATE**. 16 | 1. In Dialogflow, go to **Settings** ⚙ > **Export and Import** > **Restore from zip**. 17 | + Follow the directions to restore from the `agent.zip` file in this repo. 18 | 19 | #### App Engine Deployment & Webhook Configuration 20 | When a new project is created using the Actions Console, it also creates a Google Cloud project in the background. 21 | 1. Delete ActionsAWSHandler.java 22 | 1. Remove the following line from build.gradle: 23 | + `apply from: 'build-aws.gradle'` 24 | 1. Download & install the [Google Cloud SDK](https://cloud.google.com/sdk/docs/) 25 | 1. Configure the gcloud CLI and set your Google Cloud project to the name of your Actions on Google Project ID, which you can find from the [Actions on Google console](https://console.actions.google.com/) under Settings ⚙ 26 | + `gcloud init` 27 | + `gcloud auth application-default login` 28 | + `gcloud components install app-engine-java` 29 | + `gcloud components update` 30 | 1. Deploy to [App Engine using Gradle](https://cloud.google.com/appengine/docs/flexible/java/using-gradle): 31 | + `gradle appengineDeploy` OR 32 | + From within IntelliJ, open the Gradle tray and run the appEngineDeploy task. 33 | 1. Back in the [Dialogflow console](https://console.dialogflow.com), from the left navigation menu under **Fulfillment** > **Enable Webhook**, set the value of **URL** to `https://.appspot.com` > **Save**. 34 | 35 | #### Build for AWS 36 | 1. Delete ActionsServlet 37 | 1. Remove the following line from build.gradle: 38 | + `apply from: 'build-gcp.gradle'` 39 | 1. Build the AWS Lambda compatible zip file using the buildAWSZip gradle task: `gradle buildAWSZip` 40 | 1. Deploy the zip file found at `build/distributions/myactions.zip` as an AWS Lambda function by following instructions at https://aws.amazon.com/lambda/ 41 | 42 | #### Testing this Sample 43 | + In the [Dialogflow console](https://console.dialogflow.com), from the left navigation menu > **Integrations** > **Integration Settings** under Google Assistant > Enable **Auto-preview changes** > **Test** to open the Actions on Google simulator. **OR** 44 | + Type `Talk to my test app` in the simulator, or say `OK Google, talk to my test app` to Google Assistant on a mobile device associated with your Action's account. 45 | 46 | ### References & Issues 47 | + Questions? Go to [StackOverflow](https://stackoverflow.com/questions/tagged/actions-on-google), [Assistant Developer Community on Reddit](https://www.reddit.com/r/GoogleAssistantDev/) or [Support](https://developers.google.com/assistant/support). 48 | + For bugs, please report an issue on Github. 49 | + Actions on Google [Documentation](https://developers.google.com/assistant) 50 | + [Webhook Boilerplate Template](https://github.com/actions-on-google/dialogflow-webhook-boilerplate-java) for Actions on Google. 51 | + More info about [Gradle & the App Engine Plugin](https://cloud.google.com/appengine/docs/flexible/java/using-gradle). 52 | + More info about deploying [Java apps with App Engine](https://cloud.google.com/appengine/docs/standard/java/quickstart). 53 | 54 | ### Make Contributions 55 | Please read and follow the steps in the [CONTRIBUTING.md](CONTRIBUTING.md). 56 | 57 | ### License 58 | See [LICENSE](LICENSE). 59 | 60 | ### Terms 61 | Your use of this sample is subject to, and by using or downloading the sample files you agree to comply with, the [Google APIs Terms of Service](https://developers.google.com/terms/). 62 | -------------------------------------------------------------------------------- /agent.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/actions-on-google/dialogflow-webhook-boilerplate-java/959b5e9159095e7904ae9d8e9940a64edafadfd9/agent.zip -------------------------------------------------------------------------------- /build-aws.gradle: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 Google LLC 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 | * https://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 | buildscript { 18 | repositories { 19 | mavenCentral() 20 | } 21 | } 22 | 23 | apply plugin: 'java' 24 | 25 | sourceCompatibility = 1.8 26 | 27 | repositories { 28 | mavenCentral() 29 | } 30 | 31 | dependencies { 32 | // AWS - https://mvnrepository.com/artifact/com.amazonaws/aws-lambda-java-core 33 | compile group: 'com.amazonaws', name: 'aws-lambda-java-core', version: '1.2.0' 34 | } 35 | 36 | task buildAWSZip(type: Zip) { 37 | from compileJava 38 | from processResources 39 | into('lib') { 40 | from configurations.runtime 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /build-gcp.gradle: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 Google LLC 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 | * https://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 | buildscript { 17 | repositories { 18 | jcenter() 19 | mavenCentral() 20 | } 21 | dependencies { 22 | classpath 'com.google.cloud.tools:appengine-gradle-plugin:1.+' 23 | classpath 'org.akhikhl.gretty:gretty:+' 24 | } 25 | } 26 | 27 | sourceCompatibility = 1.8 28 | 29 | apply plugin: 'java' 30 | apply plugin: 'war' 31 | apply plugin: com.google.cloud.tools.gradle.appengine.AppEnginePlugin 32 | 33 | repositories { 34 | jcenter() 35 | mavenCentral() 36 | } 37 | 38 | dependencies { 39 | providedCompile group: 'javax.servlet', name: 'javax.servlet-api', version: '3.1.0' 40 | providedCompile group: 'com.google.appengine', name: 'appengine', version: '+' 41 | } 42 | 43 | appengine { 44 | // Deploy configuration 45 | deploy { 46 | stopPreviousVersion = true // default - stop the current version 47 | promote = true // default - & make this the current version 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 Google LLC 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 | * https://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 | apply plugin: 'java' 17 | apply plugin: 'kotlin' 18 | 19 | apply from: 'build-aws.gradle' 20 | apply from: 'build-gcp.gradle' 21 | 22 | buildscript { 23 | ext.kotlin_version = '1.3.11' 24 | 25 | repositories { 26 | mavenCentral() 27 | } 28 | dependencies { 29 | classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" 30 | } 31 | } 32 | 33 | sourceCompatibility = 1.8 34 | 35 | repositories { 36 | mavenCentral() 37 | } 38 | 39 | dependencies { 40 | compile "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" 41 | 42 | compile group: 'com.google.actions', name: 'actions-on-google', version: '1.+' 43 | 44 | compile group: 'com.googlecode.json-simple', name: 'json-simple', version: '1.1.1' 45 | 46 | testCompile group: 'junit', name: 'junit', version: '4.12' 47 | } 48 | 49 | compileKotlin { 50 | kotlinOptions.jvmTarget = "1.8" 51 | } 52 | compileTestKotlin { 53 | kotlinOptions.jvmTarget = "1.8" 54 | } 55 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 Google LLC 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 | * https://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 | rootProject.name = 'myactions' 18 | -------------------------------------------------------------------------------- /src/main/java/com/example/ActionsAWSHandler.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 Google LLC 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 | * https://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; 18 | 19 | import com.amazonaws.services.lambda.runtime.Context; 20 | import com.amazonaws.services.lambda.runtime.LambdaLogger; 21 | import com.amazonaws.services.lambda.runtime.RequestStreamHandler; 22 | import com.google.actions.api.App; 23 | import org.json.simple.JSONObject; 24 | import org.json.simple.parser.JSONParser; 25 | import org.json.simple.parser.ParseException; 26 | 27 | import java.io.*; 28 | 29 | /** 30 | * Handles request received via AWS - API Gateway [proxy integration](https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-lambda-proxy-integrations.html) 31 | * and delegates to your Actions App. 32 | */ 33 | public class ActionsAWSHandler implements RequestStreamHandler { 34 | // Replace this with your webhook. 35 | private final App actionsApp = new MyActionsApp(); 36 | private final JSONParser parser = new JSONParser(); 37 | 38 | @Override 39 | public void handleRequest(InputStream inputStream, 40 | OutputStream outputStream, 41 | Context context) throws IOException { 42 | BufferedReader reader = new BufferedReader( 43 | new InputStreamReader(inputStream)); 44 | JSONObject awsResponse = new JSONObject(); 45 | LambdaLogger logger = context.getLogger(); 46 | try { 47 | JSONObject awsRequest = (JSONObject) parser.parse(reader); 48 | JSONObject headers = (JSONObject) awsRequest.get("headers"); 49 | String body = (String) awsRequest.get("body"); 50 | logger.log("AWS request body = " + body); 51 | 52 | actionsApp.handleRequest(body, headers) 53 | .thenAccept((webhookResponseJson) -> { 54 | logger.log("Generated json = " + webhookResponseJson); 55 | 56 | JSONObject responseHeaders = new JSONObject(); 57 | responseHeaders.put("Content-Type", "application/json"); 58 | 59 | awsResponse.put("statusCode", "200"); 60 | awsResponse.put("headers", responseHeaders); 61 | awsResponse.put("body", webhookResponseJson); 62 | writeResponse(outputStream, awsResponse); 63 | }).exceptionally((throwable -> { 64 | awsResponse.put("statusCode", "500"); 65 | awsResponse.put("exception", throwable); 66 | writeResponse(outputStream, awsResponse); 67 | return null; 68 | })); 69 | 70 | } catch (ParseException e) { 71 | e.printStackTrace(); 72 | } 73 | } 74 | 75 | private void writeResponse(OutputStream outputStream, JSONObject responseJson) { 76 | try { 77 | OutputStreamWriter writer = new OutputStreamWriter(outputStream, "UTF-8"); 78 | writer.write(responseJson.toJSONString()); 79 | writer.close(); 80 | } catch (IOException e) { 81 | e.printStackTrace(); 82 | } 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /src/main/java/com/example/ActionsServlet.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 Google LLC 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 | * https://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; 18 | 19 | import com.google.actions.api.App; 20 | import java.io.IOException; 21 | import java.util.Enumeration; 22 | import java.util.HashMap; 23 | import java.util.Map; 24 | import java.util.concurrent.ExecutionException; 25 | import java.util.stream.Collectors; 26 | import javax.servlet.annotation.WebServlet; 27 | import javax.servlet.http.HttpServlet; 28 | import javax.servlet.http.HttpServletRequest; 29 | import javax.servlet.http.HttpServletResponse; 30 | import org.slf4j.Logger; 31 | import org.slf4j.LoggerFactory; 32 | 33 | /** 34 | * Handles request received via HTTP POST and delegates it to your Actions app. See: [Request 35 | * handling in Google App 36 | * Engine](https://cloud.google.com/appengine/docs/standard/java/how-requests-are-handled). 37 | */ 38 | @WebServlet(name = "actions", value = "/") 39 | public class ActionsServlet extends HttpServlet { 40 | private static final Logger LOG = LoggerFactory.getLogger(ActionsServlet.class); 41 | private final App actionsApp = new MyActionsApp(); 42 | 43 | @Override 44 | protected void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException { 45 | String body = req.getReader().lines().collect(Collectors.joining()); 46 | LOG.info("doPost, body = {}", body); 47 | 48 | try { 49 | String jsonResponse = actionsApp.handleRequest(body, getHeadersMap(req)).get(); 50 | LOG.info("Generated json = {}", jsonResponse); 51 | res.setContentType("application/json"); 52 | writeResponse(res, jsonResponse); 53 | } catch (InterruptedException e) { 54 | handleError(res, e); 55 | } catch (ExecutionException e) { 56 | handleError(res, e); 57 | } 58 | } 59 | 60 | @Override 61 | protected void doGet(HttpServletRequest request, HttpServletResponse response) 62 | throws IOException { 63 | response.setContentType("text/plain"); 64 | response 65 | .getWriter() 66 | .println( 67 | "ActionsServlet is listening but requires valid POST request to respond with Action response."); 68 | } 69 | 70 | private void writeResponse(HttpServletResponse res, String asJson) { 71 | try { 72 | res.getWriter().write(asJson); 73 | } catch (IOException e) { 74 | e.printStackTrace(); 75 | } 76 | } 77 | 78 | private void handleError(HttpServletResponse res, Throwable throwable) { 79 | try { 80 | throwable.printStackTrace(); 81 | LOG.error("Error in App.handleRequest ", throwable); 82 | res.getWriter().write("Error handling the intent - " + throwable.getMessage()); 83 | } catch (IOException e) { 84 | e.printStackTrace(); 85 | } 86 | } 87 | 88 | private Map getHeadersMap(HttpServletRequest request) { 89 | Map map = new HashMap(); 90 | 91 | Enumeration headerNames = request.getHeaderNames(); 92 | while (headerNames.hasMoreElements()) { 93 | String key = (String) headerNames.nextElement(); 94 | String value = request.getHeader(key); 95 | map.put(key, value); 96 | } 97 | return map; 98 | } 99 | 100 | } 101 | -------------------------------------------------------------------------------- /src/main/java/com/example/MyActionsApp.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 Google LLC 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 | * https://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; 18 | 19 | import com.google.actions.api.ActionRequest; 20 | import com.google.actions.api.ActionResponse; 21 | import com.google.actions.api.DialogflowApp; 22 | import com.google.actions.api.ForIntent; 23 | import com.google.actions.api.response.ResponseBuilder; 24 | import com.google.api.services.actions_fulfillment.v2.model.User; 25 | import java.util.ResourceBundle; 26 | import java.util.stream.Collectors; 27 | import org.slf4j.Logger; 28 | import org.slf4j.LoggerFactory; 29 | 30 | /** 31 | * Implements all intent handlers for this Action. Note that your App must extend from DialogflowApp 32 | * if using Dialogflow or ActionsSdkApp for ActionsSDK based Actions. 33 | */ 34 | public class MyActionsApp extends DialogflowApp { 35 | 36 | private static final Logger LOGGER = LoggerFactory.getLogger(MyActionsApp.class); 37 | 38 | @ForIntent("Default Welcome Intent") 39 | public ActionResponse welcome(ActionRequest request) { 40 | LOGGER.info("Welcome intent start."); 41 | ResponseBuilder responseBuilder = getResponseBuilder(request); 42 | ResourceBundle rb = ResourceBundle.getBundle("resources"); 43 | User user = request.getUser(); 44 | 45 | if (user != null && user.getLastSeen() != null) { 46 | responseBuilder.add(rb.getString("welcome_back")); 47 | } else { 48 | responseBuilder.add(rb.getString("welcome")); 49 | } 50 | 51 | LOGGER.info("Welcome intent end."); 52 | return responseBuilder.build(); 53 | } 54 | 55 | @ForIntent("bye") 56 | public ActionResponse bye(ActionRequest request) { 57 | LOGGER.info("Bye intent start."); 58 | ResponseBuilder responseBuilder = getResponseBuilder(request); 59 | ResourceBundle rb = ResourceBundle.getBundle("resources"); 60 | 61 | responseBuilder.add(rb.getString("bye")).endConversation(); 62 | LOGGER.info("Bye intent end."); 63 | return responseBuilder.build(); 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /src/main/resources/resources_en_US.properties: -------------------------------------------------------------------------------- 1 | welcome = Welcome to my app. 2 | welcome_back=Welcome back. How can I help you? 3 | bye=Ok see you later. 4 | cancel=Sure thing. Good bye. 5 | no_input_1=Sorry I didn't catch that. Could you repeat yourself? 6 | no_input_2=What was that? 7 | no_input_3=Okay let's try this again later. -------------------------------------------------------------------------------- /src/main/webapp/WEB-INF/appengine-web.xml: -------------------------------------------------------------------------------- 1 | 2 | 17 | 18 | java8 19 | true 20 | 21 | -------------------------------------------------------------------------------- /src/test/java/com/example/MyActionsAppTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 Google LLC 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 | * https://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; 18 | 19 | import static junit.framework.TestCase.assertEquals; 20 | import static junit.framework.TestCase.assertTrue; 21 | import static org.junit.Assert.assertFalse; 22 | 23 | import com.google.actions.api.ActionRequest; 24 | import com.google.actions.api.ActionResponse; 25 | import com.google.actions.api.test.MockRequestBuilder; 26 | import java.io.IOException; 27 | import java.nio.file.Files; 28 | import java.nio.file.Path; 29 | import java.nio.file.Paths; 30 | import java.util.concurrent.CompletableFuture; 31 | import org.junit.Test; 32 | 33 | public class MyActionsAppTest { 34 | 35 | private static String fromFile(String fileName) throws IOException { 36 | Path absolutePath = Paths.get("src", "test", "resources", fileName); 37 | return new String(Files.readAllBytes(absolutePath)); 38 | } 39 | 40 | @Test 41 | public void testWelcomeUsingRawRequest() throws Exception { 42 | MyActionsApp app = new MyActionsApp(); 43 | String requestBody = fromFile("request_welcome.json"); 44 | String expectedResponse = fromFile("response_welcome.json"); 45 | 46 | CompletableFuture future = app.handleRequest(requestBody, null /* headers */); 47 | 48 | String responseJson = future.get(); 49 | assertEquals(expectedResponse, responseJson); 50 | } 51 | 52 | @Test 53 | public void testWelcomeUsingMockRequestBuilder() { 54 | MyActionsApp app = new MyActionsApp(); 55 | MockRequestBuilder rb = MockRequestBuilder.PreBuilt.welcome("welcome", true); 56 | ActionRequest request = rb.build(); 57 | 58 | ActionResponse response = app.welcome(request); 59 | assertTrue(response.getExpectUserResponse()); 60 | assertEquals(1, response.getRichResponse().getItems().size()); 61 | } 62 | 63 | @Test 64 | public void testBye() { 65 | MyActionsApp app = new MyActionsApp(); 66 | MockRequestBuilder rb = new MockRequestBuilder(); 67 | rb.setIntent("bye"); 68 | rb.setUsesDialogflow(true); 69 | 70 | ActionRequest request = rb.build(); 71 | ActionResponse response = app.bye(request); 72 | 73 | assertFalse(response.getExpectUserResponse()); 74 | assertEquals(1, response.getRichResponse().getItems().size()); 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /src/test/resources/request_welcome.json: -------------------------------------------------------------------------------- 1 | { 2 | "responseId": "abcde", 3 | "queryResult": { 4 | "queryText": "GOOGLE_ASSISTANT_WELCOME", 5 | "parameters": {}, 6 | "allRequiredParamsPresent": true, 7 | "outputContexts": [ 8 | { 9 | "name": "projects/project-id/agent/sessions/session-id/contexts/google_assistant_welcome" 10 | }, 11 | { 12 | "name": "projects/project-id/agent/sessions/session-id/contexts/actions_capability_screen_output" 13 | }, 14 | { 15 | "name": "projects/project-id/agent/sessions/session-id/contexts/actions_capability_audio_output" 16 | }, 17 | { 18 | "name": "projects/project-id/agent/sessions/session-id/contexts/google_assistant_input_type_keyboard" 19 | }, 20 | { 21 | "name": "projects/project-id/agent/sessions/session-id/contexts/actions_capability_media_response_audio" 22 | }, 23 | { 24 | "name": "projects/project-id/agent/sessions/session-id/contexts/actions_capability_web_browser" 25 | } 26 | ], 27 | "intent": { 28 | "name": "projects/project-id/agent/intents/91a2d797-7e16-4db1-9a28-19cdd8b2c729", 29 | "displayName": "Default Welcome Intent" 30 | }, 31 | "intentDetectionConfidence": 1.0, 32 | "languageCode": "en-us" 33 | }, 34 | "originalDetectIntentRequest": { 35 | "source": "google", 36 | "version": "2", 37 | "payload": { 38 | "isInSandbox": true, 39 | "surface": { 40 | "capabilities": [ 41 | { 42 | "name": "actions.capability.WEB_BROWSER" 43 | }, 44 | { 45 | "name": "actions.capability.MEDIA_RESPONSE_AUDIO" 46 | }, 47 | { 48 | "name": "actions.capability.SCREEN_OUTPUT" 49 | }, 50 | { 51 | "name": "actions.capability.AUDIO_OUTPUT" 52 | } 53 | ] 54 | }, 55 | "requestType": "SIMULATOR", 56 | "inputs": [ 57 | { 58 | "rawInputs": [ 59 | { 60 | "query": "Talk to my test app", 61 | "inputType": "KEYBOARD" 62 | } 63 | ], 64 | "intent": "actions.intent.MAIN" 65 | } 66 | ], 67 | "user": { 68 | "userStorage": "{\"data\":{}}", 69 | "lastSeen": "2018-11-14T19:41:20Z", 70 | "locale": "en-US", 71 | "userId": "userid" 72 | }, 73 | "conversation": { 74 | "conversationId": "session-id", 75 | "type": "NEW" 76 | } 77 | } 78 | }, 79 | "session": "projects/project-id/agent/sessions/session-id" 80 | } -------------------------------------------------------------------------------- /src/test/resources/response_welcome.json: -------------------------------------------------------------------------------- 1 | {"fulfillmentText":"Welcome back. How can I help you?","outputContexts":[{"lifespanCount":99,"name":"projects/project-id/agent/sessions/session-id/contexts/_actions_on_google","parameters":{"data":"{}"}}],"payload":{"google":{"expectUserResponse":true,"richResponse":{"items":[{"simpleResponse":{"textToSpeech":"Welcome back. How can I help you?"}}]},"isSsml":false,"systemIntent":{"intent":"actions.intent.TEXT","data":{}},"userStorage":"{\"data\":{}}"}}} --------------------------------------------------------------------------------