├── LICENSE ├── README.adoc ├── readme_images ├── ow_action_delete_result.png ├── ow_action_update_result.png ├── ow_action_with_activation_id.png ├── ow_deployed_success_1.png ├── ow_deployed_success_2.png ├── ow_install_catalog.png └── ow_wsk_cli_setup.png └── solutions ├── getstarted ├── greeter.js ├── msgaction.js └── msgaction.py ├── hello-openwhisk ├── dependency-reduced-pom.xml ├── pom.xml └── src │ ├── main │ └── java │ │ └── com │ │ └── example │ │ └── FunctionApp.java │ └── test │ └── java │ └── com │ └── example │ └── FunctionAppTest.java ├── hello-web ├── dependency-reduced-pom.xml ├── pom.xml └── src │ ├── main │ └── java │ │ └── com │ │ └── example │ │ └── FunctionApp.java │ └── test │ └── java │ └── com │ └── example │ └── FunctionAppTest.java ├── integration ├── slackapp-command │ └── main.js └── slackapp-event-handler │ ├── pom.xml │ └── src │ ├── main │ └── java │ │ └── com │ │ └── redhat │ │ └── developers │ │ └── openwhisk │ │ └── FunctionApp.java │ └── test │ └── java │ └── com │ └── redhat │ └── developers │ └── openwhisk │ └── DemoMain.java └── sequence-demo ├── sorter ├── dependency-reduced-pom.xml ├── pom.xml └── src │ ├── main │ └── java │ │ └── com │ │ └── example │ │ └── FunctionApp.java │ └── test │ └── java │ └── com │ └── example │ └── FunctionAppTest.java ├── splitter ├── dependency-reduced-pom.xml ├── pom.xml └── src │ ├── main │ └── java │ │ └── com │ │ └── example │ │ └── FunctionApp.java │ └── test │ └── java │ └── com │ └── example │ └── FunctionAppTest.java └── uppercase ├── dependency-reduced-pom.xml ├── pom.xml └── src ├── main └── java │ └── com │ └── example │ └── FunctionApp.java └── test └── java └── com └── example └── FunctionAppTest.java /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. 202 | -------------------------------------------------------------------------------- /README.adoc: -------------------------------------------------------------------------------- 1 | = Function as a Service(FaaS) Tutorial 2 | // Settings: 3 | :idprefix: 4 | :idseparator: - 5 | ifndef::env-github[] 6 | :icons: font 7 | endif::[] 8 | ifdef::env-github,env-browser[] 9 | :toc: preamble 10 | :toclevels: 5 11 | endif::[] 12 | ifdef::env-github[] 13 | :status: 14 | :outfilesuffix: .adoc 15 | :!toc-title: 16 | :caution-caption: :fire: 17 | :important-caption: :exclamation: 18 | :note-caption: :paperclip: 19 | :tip-caption: :bulb: 20 | :warning-caption: :warning: 21 | endif::[] 22 | 23 | (C) 2018 https://developers.redhat.com[Red Hat Developer Experience Team] 24 | 25 | //Aliases 26 | :conum-guard-sh: # 27 | ifndef::icons[:conum-guard-sh: # #] 28 | 29 | :conum-guard-java: // 30 | ifndef::icons[:conum-guard-java: // //] 31 | 32 | // URIs: 33 | :uri-minishift: https://docs.openshift.org/latest/minishift/getting-started/installing.html 34 | :uri-openwhisk-cli: https://github.com/apache/incubator-openwhisk-cli/releases/ 35 | :uri-openwhisk-openshift: https://github.com/projectodd/openwhisk-openshift 36 | :uri-openwhisk-repo: https://github.com/apache/incubator-openwhisk 37 | :uri-repo: https://github.com/redhat-developer-demos/faas-java-tutorial 38 | :uri-repo-file-prefix: {uri-repo}/blob/master/ 39 | :uri-repo-tree-prefix: {uri-repo}/tree/master/ 40 | :uri-openwhisk-docs-prefix: {uri-openwhisk-repo}/blob/master/docs 41 | ifdef::env-github[] 42 | :uri-repo-file-prefix: link: 43 | :uri-repo-tree-prefix: link: 44 | endif::[] 45 | == Overview 46 | 47 | This tutorial walks you through on how to build a Java functions on a Function as a Service(FaaS) platform 48 | https://openwhisk.apache.org/[Apache OpenWhisk]. 49 | 50 | == Prerequisites 51 | 52 | You will need in this tutorial 53 | 54 | === Tools 55 | * {uri-minishift}[minishift] 56 | * https://www.docker.com/docker-mac[docker] 57 | * https://kubernetes.io/docs/tasks/tools/install-kubectl/#install-kubectl-binary-via-curl[kubectl] 58 | * oc (eval $(minishift oc-env)) 59 | * https://maven.apache.org[Apache Maven] 60 | * stern (brew install stern) 61 | * {uri-openwhisk-cli}[OpenWhisk CLI] 62 | * curl, gunzip, tar are built-in to MacOS or part of your bash shell 63 | * git (everybody needs the git CLI) 64 | * Java 8 65 | 66 | === Setup minishift 67 | Local development and testing can be done using https://github.com/minishift/minishift[minishift]. Minishift is a tool that helps you run 68 | OpenShift locally by running a single-node OpenShift cluster inside a VM. Details on minishift and installation procedures can be found 69 | https://docs.openshift.org/latest/minishift/getting-started/index.html[here]. 70 | 71 | ==== Minishift Profile Setup 72 | 73 | [source,sh,subs=attributes+] 74 | ---- 75 | 76 | #!/bin/bash 77 | 78 | # Don't foget to add the location of minishift executable to PATH 79 | 80 | minishift profile set faas-tutorial 81 | minishift config set memory 8GB 82 | minishift config set cpus 3 83 | minishift config set image-caching true 84 | minishift addon enable admin-user 85 | minishift addon enable anyuid {conum-guard-sh} # <1> 86 | 87 | minishift start 88 | 89 | minishift ssh -- sudo ip link set docker0 promisc on {conum-guard-sh} # <2> 90 | ---- 91 | 92 | <1> Some images that are in Apache OpenWhisk Docker hub requires __anyuid__ SCC in OpenShift 93 | <2> This is needed for pods to communicate with each other within the cluster (TODO: need to add more clear details here) 94 | 95 | [IMPORTANT] 96 | ==== 97 | `minishift ssh -- sudo ip link set docker0 promisc on` command needs to be execute each and every time minishift restarted 98 | ==== 99 | 100 | If your minishift is running OpenShift 3.9.0, you'll need to fix 101 | another bug: 102 | ---- 103 | minishift openshift config set --patch \ 104 | '{"admissionConfig": 105 | {"pluginConfig": 106 | {"openshift.io/ImagePolicy": 107 | {"configuration": 108 | {"apiVersion": "v1", 109 | "kind": "ImagePolicyConfig", 110 | "resolveImages": "AttemptRewrite"}}}}}' 111 | 112 | ---- 113 | 114 | === Setup environment 115 | 116 | [source,sh,subs=attributes+] 117 | ---- 118 | #!/bin/bash 119 | 120 | eval $(minishift oc-env) && eval $(minishift docker-env) 121 | oc login $(minishift ip):8443 -u admin -p admin 122 | ---- 123 | 124 | === Setup OpenWhisk 125 | 126 | The project {uri-openwhisk-openshift}[OpenWhisk on OpenShift] provides the OpenShift templates required to deploy Apache OpenWhisk. 127 | 128 | [source,sh,subs=attributes+] 129 | ---- 130 | oc new-project faas {conum-guard-sh} # <1> 131 | oc project -q {conum-guard-sh} # <2> 132 | oc process -f https://git.io/openwhisk-template | oc create -f - {conum-guard-sh} # <3> 133 | oc adm policy add-role-to-user admin developer -n faas {conum-guard-sh} # <4> 134 | ---- 135 | 136 | <1> Its always better to group certain class of applications, create a new OpenShift project called `faas` to deploy all OpenWhisk applications 137 | <2> Make sure we are in right project 138 | <3> Deploy OpenWhisk applications to `openwhisk` project 139 | <4> (**Optional**) Add `developer` user as admin to `faas` project so as to allow you to login with developer user and access `faas` project 140 | 141 | [NOTE] 142 | ==== 143 | You need to wait for sometime to have all the required OpenWhisk pods come up and the FaaS is ready for some load. You can watch the 144 | status using watch -n 5 'oc logs -f controller-0 -n faas | grep "invoker status changed"' 145 | ==== 146 | 147 | ==== Verify Deployment 148 | 149 | Launch OpenShift console via `minishift console`. Navigate to the `faas` project by clicking the name in the upper right corner. A 150 | successful deployment will look like: 151 | 152 | image::readme_images/ow_deployed_success_1.png[OpenWhisk Pods] 153 | image::readme_images/ow_deployed_success_2.png[OpenWhisk Pods] 154 | 155 | [[configure-wsk]] 156 | ==== Configure WSK CLI 157 | 158 | Download {uri-openwhisk-cli}[OpenWhisk CLI] and add it your PATH. Verify your path using the command 159 | `wsk --help` 160 | 161 | The {uri-openwhisk-cli}[OpenWhisk CLI] needs to be configured to know where the OpenWhisk is located 162 | and the authorization that could be used to invoke `wsk` commands. Run the following command to have that setup: 163 | 164 | [source,sh,subs=attributes+] 165 | ---- 166 | #!/bin/bash 167 | 168 | AUTH_SECRET=$(oc get secret whisk.auth -o yaml | grep "system:" | awk '{print $2}' | base64 --decode) 169 | wsk property set --auth $AUTH_SECRET --apihost $(oc get route/openwhisk --template="{{.spec.host}}") 170 | ---- 171 | 172 | Successful setup of WSK CLI will show output like: 173 | 174 | image::readme_images/ow_wsk_cli_setup.png[WSK CLI] 175 | 176 | In this case the OpenWhisk API Host is pointing to the local minishift nip.io address 177 | 178 | To verify if wsk CLI is configured properly run `wsk -i action list`. This will list some actions which are installed as part of the 179 | OpenWhisk setup. If you see empty result, please see <> 180 | 181 | [TIP] 182 | ==== 183 | The `nginx` in OpenWhisk deployment uses a self-signed certificate. To avoid certificate errors when using `wsk`, you need to add `wsk -i` 184 | to each of your `wsk` commands. For convenience, you can add an alias to your profile with `alias wsk='wsk -i $@'`. 185 | ==== 186 | 187 | === Setup your Development environment 188 | 189 | Clone the complete project from `git clone {uri-repo}`, we will refer to this location as $PROJECT_HOME through out the document 190 | for convenience. 191 | 192 | == What is an Action ? 193 | 194 | **Actions** are stateless code snippets that run on the OpenWhisk platform. They are analogous to methods in Java idioms. OpenWhisk 195 | **Actions** are thread-safe meaning at a given point of time only one invocation happens. 196 | 197 | Fore more details refer the official documentation {uri-openwhisk-docs-prefix}/actions.md[here]. 198 | 199 | === Your first Action 200 | 201 | Let's quickly create a simple function in JavaScript to see it all working: 202 | 203 | [source,sh,subs=attributes+] 204 | ---- 205 | mkdir -p getstarted 206 | cd $PROJECT_HOME/getstarted 207 | ---- 208 | 209 | Create a file called `$PROJECT_HOME/getstarted/greeter.js` and add the following content to it: 210 | 211 | [source,js,subs=attributes+] 212 | ---- 213 | function main() { 214 | return {payload: 'Welcome to OpenWhisk on OpenShift'}; 215 | } 216 | ---- 217 | 218 | Create an action called **greeter**: 219 | 220 | [source,sh,subs=attributes+] 221 | ---- 222 | wsk -i action update greeter greeter.js 223 | ---- 224 | 225 | Lets invoke the action using command: 226 | 227 | [source,sh,subs=attributes+] 228 | ---- 229 | wsk -i action invoke greeter --result 230 | ---- 231 | 232 | The action invoke should respond with the following JSON: 233 | 234 | [source,json,subs=attributes+] 235 | ---- 236 | { 237 | "payload": "Welcome to OpenWhisk on OpenShift" 238 | } 239 | ---- 240 | 241 | == Java Actions 242 | 243 | === Install Maven Archetype 244 | 245 | Maven Archetype can be used to generate the template Java Action project, as of writing this tutorial the archetype is not maven central 246 | hence it need to install it locally, 247 | 248 | [source,sh,subs=attributes+] 249 | ---- 250 | git clone https://github.com/apache/incubator-openwhisk-devtools 251 | cd incubator-openwhisk-devtools/java-action-archetype 252 | mvn -DskipTests clean install 253 | cd $PROJECT_HOME 254 | ---- 255 | 256 | === Your first Java Action 257 | 258 | Let's now create the first Java Action a simple "hello world" kind of function, have it deployed to OpenWhisk and finally 259 | invoke to see the result. This section will also details the complete Create-Update-Delete cycle of Java **Actions** on OpenWhisk. 260 | 261 | [NOTE] 262 | ==== 263 | For easier jar names all the examples will be using maven ``. If you generating new project following the instructions 264 | just be sure to update the default `` in `pom.xml` to `${artifactId}` to make the command instructions in subsequent section 265 | work without any changes. 266 | ==== 267 | 268 | ==== Create Java Action 269 | 270 | [source,sh,subs=attributes+] 271 | ---- 272 | cd $PROJECT_HOME 273 | mvn archetype:generate \ 274 | -DarchetypeGroupId=org.apache.openwhisk.java \ 275 | -DarchetypeArtifactId=java-action-archetype \ 276 | -DarchetypeVersion=1.0-SNAPSHOT \ 277 | -DgroupId=com.example \ 278 | -DartifactId=hello-openwhisk \ 279 | -Dversion=1.0-SNAPSHOT \ 280 | -DinteractiveMode=false 281 | ---- 282 | 283 | ==== Build 284 | [source,sh,subs=attributes+] 285 | ---- 286 | cd hello-openwhisk 287 | mvn clean package 288 | ---- 289 | 290 | ==== Deploy to OpenWhisk 291 | 292 | ===== Create 293 | 294 | [source,sh,subs=attributes+] 295 | ---- 296 | wsk -i action create hello-openwhisk target/hello-openwhisk.jar --main com.example.FunctionApp 297 | ---- 298 | 299 | [[action-invocation]] 300 | ==== Invoke and Verify the result 301 | 302 | [[sync-invocation]] 303 | ===== Synchronously 304 | 305 | [source,sh,subs=attributes+] 306 | ---- 307 | wsk -i action invoke hello-openwhisk --result 308 | ---- 309 | 310 | As all the OpenWhisk actions are asynchronous, we need to add `--result` to get the result shown on the console. 311 | 312 | Successful execution of the command will show the following output: 313 | 314 | 315 | [[action-response]] 316 | [source,json,subs=attributes+] 317 | ---- 318 | {"greetings": "Hello! Welcome to OpenWhisk" } 319 | ---- 320 | 321 | [[async-invocation]] 322 | ===== Asynchronously 323 | 324 | [source,sh,subs=attributes+] 325 | ---- 326 | wsk -i action invoke hello-openwhisk 327 | ---- 328 | 329 | A successful action invoke will return an **activation id** : 330 | 331 | image::readme_images/ow_action_with_activation_id.png[Action with Activation ID] 332 | 333 | We can then use the to **activation id** check the response using `wsk` CLI: 334 | 335 | [source,sh,subs=attributes+] 336 | ---- 337 | wsk -i activation result 338 | ---- 339 | 340 | e.g. 341 | 342 | [source,sh,subs=attributes+] 343 | ---- 344 | wsk -i activation result ffb2966350904356b29663509043566e 345 | ---- 346 | 347 | Successful execution of the command will show the same output like <>. 348 | 349 | ===== Update 350 | 351 | Update the FunctionApp class response with the String: 352 | 353 | [source,java,subs=attributes+] 354 | ---- 355 | response.addProperty("greetings", "Hello! Welcome to OpenWhisk on OpenShift"); 356 | ---- 357 | 358 | Update the FunctionAppTest Test class to match the same String: 359 | 360 | [source,java,subs=attributes+] 361 | ---- 362 | assertEquals("Hello! Welcome to OpenWhisk on OpenShift", greetings); 363 | ---- 364 | 365 | [source,java,subs=attributes+] 366 | ---- 367 | cd $PROJECT_HOME/hello-openwhisk 368 | mvn clean package 369 | wsk -i action update hello-openwhisk target/hello-openwhisk.jar --main com.example.FunctionApp 370 | ---- 371 | 372 | Successful update should show a output like: 373 | 374 | image::readme_images/ow_action_update_result.png[] 375 | 376 | Repeating the <> steps should result in the updated response ("... on OpenShift") like: 377 | [source,json,subs=attributes+] 378 | ---- 379 | { 380 | "greetings": "Hello! Welcome to OpenWhisk on OpenShift" 381 | } 382 | ---- 383 | 384 | ===== Delete 385 | 386 | [source,sh,subs=attributes+] 387 | ---- 388 | wsk -i action delete hello-openwhisk 389 | ---- 390 | 391 | A successful delete should show output like: 392 | 393 | image::readme_images/ow_action_delete_result.png[] 394 | 395 | === Web Action 396 | 397 | **WebActions** allow the OpenWhisk action to be invoked via HTTP verbs like GET, POST, PUT etc. The **WebActions** can be enabled for 398 | any **Action** using the parameter `--web=true` during the creation of the action using {uri-openwhisk-cli}[WSK CLI]. 399 | 400 | [source,sh,subs=attributes+] 401 | ---- 402 | cd $PROJECT_HOME 403 | mvn archetype:generate \ 404 | -DarchetypeGroupId=org.apache.openwhisk.java \ 405 | -DarchetypeArtifactId=java-action-archetype \ 406 | -DarchetypeVersion=1.0-SNAPSHOT \ 407 | -DgroupId=com.example \ 408 | -DartifactId=hello-web \ 409 | -Dversion=1.0-SNAPSHOT \ 410 | -DinteractiveMode=false 411 | ---- 412 | 413 | Update the FunctionApp class response to show application's arguments: 414 | [source,java,subs=attributes+] 415 | ---- 416 | response.add("response", args); 417 | ---- 418 | 419 | Update the FunctionAppTest testFunction method with code: 420 | [source,java,subs=attributes+] 421 | ---- 422 | @Test 423 | public void testFunction() { 424 | JsonObject args = new JsonObject(); 425 | args.addProperty("name", "test"); 426 | JsonObject response = FunctionApp.main(args); 427 | assertNotNull(response); 428 | String actual = response.get("response").getAsJsonObject().get("name").getAsString(); 429 | assertEquals("test", actual); 430 | } 431 | ---- 432 | 433 | ==== Build 434 | [source,sh,subs=attributes+] 435 | ---- 436 | cd hello-web 437 | mvn clean package 438 | ---- 439 | 440 | ==== Deploy to OpenWhisk 441 | [source,sh,subs=attributes+] 442 | ---- 443 | wsk -i action update --web=true hello-web target/hello-web.jar --main com.example.FunctionApp 444 | ---- 445 | 446 | ==== Invoke and Verify the result 447 | 448 | [source,sh,subs=attributes+] 449 | ---- 450 | WEB_URL=`wsk -i action get hello-web --url | awk 'FNR==2{print $1".json"}'` {conum-guard-sh} # <1> 451 | AUTH=`oc get secret whisk.auth -n faas -o yaml | grep "system:" | awk '{print $2}'` {conum-guard-sh} # <2> 452 | ---- 453 | <1> Get the HTTP URL for invoking the action, the returned URL will have `.json` suffix to allow the WSK to set the right `Content-Type` and `Accept` 454 | headers 455 | <2> Some resources requires authentication, for those requests its required to add `Authorization` header with value as `$AUTH` 456 | 457 | [source,sh,subs=attributes+] 458 | ---- 459 | curl -k $WEB_URL 460 | ---- 461 | 462 | You can also access the url via browser using address held in variable $WEB_URL. 463 | 464 | [NOTE] 465 | ===== 466 | 467 | The following section shows some example requests and their expected responses 468 | 469 | **Without any request data** 470 | 471 | [source,json,subs=attributes+] 472 | ----- 473 | { 474 | "response": { 475 | "__ow_method": "get", 476 | "__ow_headers": { 477 | "x-forwarded-port": "443", 478 | "accept": "*/*", 479 | "forwarded": "for=192.168.64.1;host=openwhisk-faas.192.168.64.67.nip.io;proto=https", 480 | "user-agent": "curl/7.54.0", 481 | "x-forwarded-proto": "https", 482 | "host": "controller.faas.svc.cluster.local:8080", 483 | "x-forwarded-host": "openwhisk-faas.192.168.64.67.nip.io", 484 | "x-forwarded-for": "192.168.64.1" 485 | }, 486 | "__ow_path": "" 487 | } 488 | } 489 | ----- 490 | 491 | **With any JSON request data** 492 | 493 | [source,sh,subs=attributes+] 494 | ---- 495 | curl -k -X POST -H 'Content-Type: application/json' -d '{"name": "test"}' $WEB_URL.json 496 | ---- 497 | 498 | [source,json,subs=attributes+] 499 | ---- 500 | { 501 | "response": { 502 | "__ow_method": "post", 503 | "__ow_headers": { 504 | "x-forwarded-port": "443", 505 | "accept": "*/*", 506 | "forwarded": "for=192.168.64.1;host=openwhisk-faas.192.168.64.67.nip.io;proto=https", 507 | "user-agent": "curl/7.54.0", 508 | "x-forwarded-proto": "https", 509 | "host": "controller.faas.svc.cluster.local:8080", 510 | "content-type": "application/json", 511 | "x-forwarded-host": "openwhisk-faas.192.168.64.67.nip.io", 512 | "x-forwarded-for": "192.168.64.1" 513 | }, 514 | "__ow_path": "", 515 | "name": "test" 516 | } 517 | } 518 | ---- 519 | 520 | **With request data and an invalid content type** 521 | 522 | [source,sh,subs=attributes+] 523 | ---- 524 | curl -k -X POST -H 'Content-Type: application/something' -d '{"name": "test"}' $WEB_URL.json 525 | ---- 526 | 527 | Invoke via curl like above , with request data you will see the response like: 528 | 529 | [source,json,subs=attributes+] 530 | ---- 531 | { 532 | "response": { 533 | "__ow_method": "post", 534 | "__ow_headers": { 535 | "x-forwarded-port": "443", 536 | "accept": "*/*", 537 | "forwarded": "for=192.168.64.1;host=openwhisk-faas.192.168.64.67.nip.io;proto=https", 538 | "user-agent": "curl/7.54.0", 539 | "x-forwarded-proto": "https", 540 | "host": "controller.faas.svc.cluster.local:8080", 541 | "content-type": "application/something", 542 | "x-forwarded-host": "openwhisk-faas.192.168.64.67.nip.io", 543 | "x-forwarded-for": "192.168.64.1" 544 | }, 545 | "__ow_path": "", 546 | "__ow_body": "eyJuYW1lIjogInRlc3QifQ==" //<1> 547 | } 548 | } 549 | ---- 550 | <1> for unknown content-type the request body will be sent as base64 encoded string 551 | ===== 552 | 553 | === Chaining Actions 554 | 555 | Apache OpenWhisk allows chaining of actions which are called in the same sequence as they are defined. We will now create 556 | a simple sequence of actions which will split, convert to uppercase, and sort a comma separated string. 557 | 558 | All the three projects can be co-located in same directory for clarity and easy building: 559 | 560 | [source,sh,subs=attributes+] 561 | ----- 562 | cd .. 563 | mkdir -p sequence-demo 564 | cd sequence-demo 565 | wsk -i package create redhat-developers-demo {conum-guard-sh} <1> 566 | ----- 567 | 568 | <1> Create a new package to hold our actions, this gives a better clarity on which actions we add to our sequence. For more details 569 | refer to the {uri-openwhisk-docs-prefix}/packages.md[Packages] documentation. 570 | 571 | ==== Create Split Action 572 | 573 | This Action will receive a comma separated string as a parameter and return a array of Strings as a response. 574 | 575 | [source,sh,subs=attributes+] 576 | ---- 577 | cd $PROJECT_HOME/sequence-demo 578 | mvn archetype:generate \ 579 | -DarchetypeGroupId=org.apache.openwhisk.java \ 580 | -DarchetypeArtifactId=java-action-archetype \ 581 | -DarchetypeVersion=1.0-SNAPSHOT \ 582 | -DgroupId=com.example \ 583 | -DartifactId=splitter \ 584 | -Dversion=1.0-SNAPSHOT \ 585 | -DinteractiveMode=false 586 | ---- 587 | 588 | Update the FunctionApp class with this code: 589 | [source,java,subs=attributes+] 590 | ---- 591 | public static JsonObject main(JsonObject args) { 592 | JsonObject response = new JsonObject(); 593 | String text = null; 594 | if (args.has("text")) { 595 | text = args.getAsJsonPrimitive("text").getAsString(); 596 | } 597 | String[] results = new String[] { text }; 598 | if (text != null && text.indexOf(",") != -1) { 599 | results = text.split(","); 600 | } 601 | JsonArray splitStrings = new JsonArray(); 602 | for (String var : results) { 603 | splitStrings.add(var); 604 | } 605 | response.add("result", splitStrings); 606 | return response; 607 | } 608 | ---- 609 | 610 | Update the FunctionAppTest testFunction method with code: 611 | [source,java,subs=attributes+] 612 | ---- 613 | @Test 614 | public void testFunction() { 615 | JsonObject args = new JsonObject(); 616 | args.addProperty("text", "apple,orange,banana"); 617 | JsonObject response = FunctionApp.main(args); 618 | assertNotNull(response); 619 | JsonArray results = response.getAsJsonArray("result"); 620 | assertNotNull(results); 621 | assertEquals(3, results.size()); 622 | List actuals = new ArrayList<>(); 623 | results.forEach(j -> actuals.add(j.getAsString())); 624 | assertTrue(actuals.contains("apple")); 625 | assertTrue(actuals.contains("orange")); 626 | assertTrue(actuals.contains("banana")); 627 | } 628 | ---- 629 | 630 | ===== Build Splitter Action 631 | [source,sh,subs=attributes+] 632 | ---- 633 | cd splitter 634 | mvn clean package 635 | wsk -i action update redhat-developers-demo/splitter target/splitter.jar --main com.example.FunctionApp 636 | ---- 637 | 638 | ==== Create Uppercase Action 639 | 640 | This Action will take the array of Strings from previous step (Splitter Action) and convert the strings to upper case 641 | 642 | [source,sh,subs=attributes+] 643 | ---- 644 | cd .. 645 | mvn archetype:generate \ 646 | -DarchetypeGroupId=org.apache.openwhisk.java \ 647 | -DarchetypeArtifactId=java-action-archetype \ 648 | -DarchetypeVersion=1.0-SNAPSHOT \ 649 | -DgroupId=com.example \ 650 | -DartifactId=uppercase \ 651 | -Dversion=1.0-SNAPSHOT \ 652 | -DinteractiveMode=false 653 | ---- 654 | 655 | Update the FunctionApp class with this code: 656 | [source,java,subs=attributes+] 657 | ---- 658 | public static JsonObject main(JsonObject args) { 659 | JsonObject response = new JsonObject(); 660 | JsonArray upperArray = new JsonArray(); 661 | if (args.has("result")) { {conum-guard-java} // <1> 662 | args.getAsJsonArray("result").forEach(e -> upperArray.add(e.getAsString().toUpperCase())); 663 | } 664 | response.add("result", upperArray); 665 | return response; 666 | } 667 | ---- 668 | 669 | <1> The function expects the previous action in sequence to send the parameter with JSON attribute called `result` 670 | 671 | Update the FunctionAppTest testFunction method with code: 672 | [source,java,subs=attributes+] 673 | ---- 674 | @Test 675 | public void testFunction() { 676 | JsonObject args = new JsonObject(); 677 | JsonArray splitStrings = new JsonArray(); 678 | splitStrings.add("apple"); 679 | splitStrings.add("orange"); 680 | splitStrings.add("banana"); 681 | args.add("result", splitStrings); 682 | JsonObject response = FunctionApp.main(args); 683 | assertNotNull(response); 684 | JsonArray results = response.getAsJsonArray("result"); 685 | assertNotNull(results); 686 | assertEquals(3, results.size()); 687 | List actuals = new ArrayList<>(); 688 | results.forEach(j -> actuals.add(j.getAsString())); 689 | assertTrue(actuals.contains("APPLE")); 690 | assertTrue(actuals.contains("ORANGE")); 691 | assertTrue(actuals.contains("BANANA")); 692 | } 693 | ---- 694 | 695 | ===== Build Uppercase Action 696 | [source,sh,subs=attributes+] 697 | ---- 698 | cd uppercase 699 | mvn clean package 700 | wsk -i action update redhat-developers-demo/uppercase target/uppercase.jar --main com.example.FunctionApp 701 | ---- 702 | 703 | ==== Create Sort Action 704 | 705 | This Action will take the array of Strings from previous step (Upppercase Action) and sort them 706 | 707 | [source,sh,subs=attributes+] 708 | ---- 709 | cd .. 710 | mvn archetype:generate \ 711 | -DarchetypeGroupId=org.apache.openwhisk.java \ 712 | -DarchetypeArtifactId=java-action-archetype \ 713 | -DarchetypeVersion=1.0-SNAPSHOT \ 714 | -DgroupId=com.example \ 715 | -DartifactId=sorter \ 716 | -Dversion=1.0-SNAPSHOT \ 717 | -DinteractiveMode=false 718 | ---- 719 | 720 | Update the FunctionApp class with this code: 721 | [source,java,subs=attributes+] 722 | ---- 723 | public static JsonObject main(JsonObject args) { 724 | JsonObject response = new JsonObject(); 725 | List upperStrings = new ArrayList<>(); 726 | if (args.has("result")) { 727 | args.getAsJsonArray("result").forEach(e -> upperStrings.add(e.getAsString())); 728 | } 729 | 730 | JsonArray sortedArray = new JsonArray(); 731 | upperStrings.stream().sorted(Comparator.naturalOrder()).forEach(s -> sortedArray.add(s)); 732 | 733 | response.add("result", sortedArray); 734 | return response; 735 | } 736 | ---- 737 | 738 | Update the FunctionAppTest testFunction method with code: 739 | [source,java,subs=attributes+] 740 | ---- 741 | @Test 742 | public void testFunction() { 743 | JsonObject args = new JsonObject(); 744 | JsonArray splitStrings = new JsonArray(); 745 | splitStrings.add("APPLE"); 746 | splitStrings.add("ORANGE"); 747 | splitStrings.add("BANANA"); 748 | args.add("result", splitStrings); 749 | JsonObject response = FunctionApp.main(args); 750 | assertNotNull(response); 751 | JsonArray results = response.getAsJsonArray("result"); 752 | assertNotNull(results); 753 | assertEquals(3, results.size()); 754 | List actuals = new ArrayList<>(); 755 | results.forEach(j -> actuals.add(j.getAsString())); 756 | assertTrue(actuals.get(0).equals("APPLE")); 757 | assertTrue(actuals.get(1).equals("BANANA")); 758 | assertTrue(actuals.get(2).equals("ORANGE")); 759 | } 760 | 761 | ---- 762 | 763 | ===== Build Sorter Action 764 | [source,sh,subs=attributes+] 765 | ---- 766 | cd sorter 767 | mvn clean package 768 | wsk -i action update redhat-developers-demo/sorter target/sorter.jar --main com.example.FunctionApp 769 | ---- 770 | 771 | ==== Create an Action Sequence 772 | 773 | Having created all the three actions, lets now create OpenWhisk that calls all three function split,uppercase and sort in sequence. 774 | 775 | [source,sh,subs=attributes+] 776 | ---- 777 | cd .. 778 | wsk -i action update redhat-developers-demo/splitUpperAndSort --sequence redhat-developers-demo/splitter,redhat-developers-demo/uppercase,redhat-developers-demo/sorter 779 | ---- 780 | 781 | ====== Invoke and Verify 782 | 783 | [source,sh,subs=attributes+] 784 | ---- 785 | wsk -i action invoke redhat-developers-demo/splitUpperAndSort --param text "zebra,cat,antelope" --result 786 | ---- 787 | 788 | The above action invoke should result in response like: 789 | [source,sh,subs=attributes+] 790 | ---- 791 | { 792 | "result": [ 793 | "ANTELOPE", 794 | "CAT", 795 | "ZEBRA" 796 | ] 797 | } 798 | ---- 799 | 800 | === Advanced 801 | 802 | Check 803 | 804 | == Troubleshooting 805 | [[install-catalog]] 806 | === Reinstall default Catalog 807 | 808 | If you are on a low bandwidth sometimes the default catalog will not be populated, run the following commands to have them installed 809 | [source,sh,subs=attributes+] 810 | ---- 811 | #!/bin/bash 812 | 813 | oc delete job install-catalog <1> 814 | 815 | cat < 848 | ---- 849 | 850 | <1> Delete the old job 851 | <2> Run the install-catalog job again 852 | 853 | Now when you run `wsk -i action list` you should see output like: 854 | 855 | image::readme_images/ow_install_catalog.png[Install Catalog] 856 | 857 | [[tips-and-tricks]] 858 | == Tips and Tricks 859 | 860 | [TIP] 861 | ==== 862 | * If you are going to use a lot of `wsk` then its worth aliasing wsk with `alias wsk='wsk -i $@'` to avoid SSL errors and skip adding `-i` 863 | for every command. 864 | * For detailed JSON output form `wsk` commands prefix `-v`. This is a great command option for troubleshooting. 865 | * Its safe to use `wsk -i update [resource]` when creating OpenWhisk resources like **Actions**, **Packages** etc., as this command 866 | will act like `create` for new resources and `update` for existing resources. 867 | * `wsk -i [resource command ] --summary` provides detailed information about a specific resource e.g. wsk -i action get foo --summary 868 | * `wsk -i activation poll`, a very useful command when we want to debug some error or see the exception stack traces during a function execution. The simple example of this could be that we star this command on one terminal and fire the action on another to see poll window showing exceptions/errors/stacktraces if any during execution. 869 | ==== 870 | 871 | [[references]] 872 | == References 873 | 874 | * {uri-openwhisk-openshift}[Apache OpenWhisk on OpenShift] 875 | * {uri-openwhisk-docs-prefix}/actions.md[OpenWhisk Actions] 876 | * {uri-openwhisk-docs-prefix}/cli.md[Setup OpenWhisk CLI] 877 | * {uri-openwhisk-docs-prefix}/packages.md[Packages] 878 | * {uri-openwhisk-docs-prefix}/webactions.md[Web Action] 879 | -------------------------------------------------------------------------------- /readme_images/ow_action_delete_result.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/redhat-developer-demos/faas-tutorial/258fd3f70a4ba2937e23e631e8581cc8d8ea291c/readme_images/ow_action_delete_result.png -------------------------------------------------------------------------------- /readme_images/ow_action_update_result.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/redhat-developer-demos/faas-tutorial/258fd3f70a4ba2937e23e631e8581cc8d8ea291c/readme_images/ow_action_update_result.png -------------------------------------------------------------------------------- /readme_images/ow_action_with_activation_id.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/redhat-developer-demos/faas-tutorial/258fd3f70a4ba2937e23e631e8581cc8d8ea291c/readme_images/ow_action_with_activation_id.png -------------------------------------------------------------------------------- /readme_images/ow_deployed_success_1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/redhat-developer-demos/faas-tutorial/258fd3f70a4ba2937e23e631e8581cc8d8ea291c/readme_images/ow_deployed_success_1.png -------------------------------------------------------------------------------- /readme_images/ow_deployed_success_2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/redhat-developer-demos/faas-tutorial/258fd3f70a4ba2937e23e631e8581cc8d8ea291c/readme_images/ow_deployed_success_2.png -------------------------------------------------------------------------------- /readme_images/ow_install_catalog.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/redhat-developer-demos/faas-tutorial/258fd3f70a4ba2937e23e631e8581cc8d8ea291c/readme_images/ow_install_catalog.png -------------------------------------------------------------------------------- /readme_images/ow_wsk_cli_setup.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/redhat-developer-demos/faas-tutorial/258fd3f70a4ba2937e23e631e8581cc8d8ea291c/readme_images/ow_wsk_cli_setup.png -------------------------------------------------------------------------------- /solutions/getstarted/greeter.js: -------------------------------------------------------------------------------- 1 | function main() { 2 | return {payload: 'Welcome to OpenWhisk on OpenShift'}; 3 | } -------------------------------------------------------------------------------- /solutions/getstarted/msgaction.js: -------------------------------------------------------------------------------- 1 | function main(params) { 2 | console.log("JS msgaction args: %j", params); 3 | Object.keys(params["body"]).forEach(function(key) { 4 | console.log("%s: %j", key, params["body"][key]) 5 | }); 6 | return { payload: 'JavaScript on OpenWhisk on OpenShift ' + params.body.text}; 7 | } 8 | -------------------------------------------------------------------------------- /solutions/getstarted/msgaction.py: -------------------------------------------------------------------------------- 1 | def main(params): 2 | print "Py msgaction params: " + str(params) 3 | for key in params["body"]: 4 | print key, params["body"][key] 5 | return { "payload" : 6 | "Python on OpenWhisk on OpenShift " + str(params["body"]["text"])} -------------------------------------------------------------------------------- /solutions/hello-openwhisk/dependency-reduced-pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4.0.0 4 | com.example 5 | hello-openwhisk 6 | 1.0-SNAPSHOT 7 | https://openwhisk.apache.org/ 8 | 9 | hello-openwhisk 10 | 11 | 12 | maven-shade-plugin 13 | 3.1.0 14 | 15 | 16 | package 17 | 18 | shade 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | junit 28 | junit 29 | 4.12 30 | test 31 | 32 | 33 | hamcrest-core 34 | org.hamcrest 35 | 36 | 37 | 38 | 39 | 40 | 1.8 41 | 2.8.2 42 | 1.8 43 | UTF-8 44 | 45 | 46 | 47 | -------------------------------------------------------------------------------- /solutions/hello-openwhisk/pom.xml: -------------------------------------------------------------------------------- 1 | 4 | 4.0.0 5 | com.example 6 | hello-openwhisk 7 | 1.0-SNAPSHOT 8 | https://openwhisk.apache.org/ 9 | 10 | UTF-8 11 | 1.8 12 | 1.8 13 | 2.8.2 14 | 15 | 16 | 17 | com.google.code.gson 18 | gson 19 | ${gson.version} 20 | 21 | 22 | junit 23 | junit 24 | 4.12 25 | test 26 | 27 | 28 | 29 | hello-openwhisk 30 | 31 | 32 | 33 | org.apache.maven.plugins 34 | maven-shade-plugin 35 | 3.1.0 36 | 37 | 38 | package 39 | 40 | shade 41 | 42 | 43 | 44 | 45 | 46 | 47 | -------------------------------------------------------------------------------- /solutions/hello-openwhisk/src/main/java/com/example/FunctionApp.java: -------------------------------------------------------------------------------- 1 | package com.example; 2 | 3 | /* 4 | * Licensed to the Apache Software Foundation (ASF) under one or more 5 | * contributor license agreements. See the NOTICE file distributed with 6 | * this work for additional information regarding copyright ownership. 7 | * The ASF licenses this file to You under the Apache License, Version 2.0 8 | * (the "License"); you may not use this file except in compliance with 9 | * the License. You may obtain a copy of the License at 10 | * 11 | * http://www.apache.org/licenses/LICENSE-2.0 12 | * 13 | * Unless required by applicable law or agreed to in writing, software 14 | * distributed under the License is distributed on an "AS IS" BASIS, 15 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | * See the License for the specific language governing permissions and 17 | * limitations under the License. 18 | */ 19 | 20 | import com.google.gson.JsonObject; 21 | 22 | /** 23 | * Hello FunctionApp 24 | */ 25 | public class FunctionApp { 26 | public static JsonObject main(JsonObject args) { 27 | JsonObject response = new JsonObject(); 28 | response.addProperty("greetings", "Hello! Welcome to OpenWhisk on OpenShift"); 29 | return response; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /solutions/hello-openwhisk/src/test/java/com/example/FunctionAppTest.java: -------------------------------------------------------------------------------- 1 | package com.example; 2 | 3 | /* 4 | * Licensed to the Apache Software Foundation (ASF) under one or more 5 | * contributor license agreements. See the NOTICE file distributed with 6 | * this work for additional information regarding copyright ownership. 7 | * The ASF licenses this file to You under the Apache License, Version 2.0 8 | * (the "License"); you may not use this file except in compliance with 9 | * the License. You may obtain a copy of the License at 10 | * 11 | * http://www.apache.org/licenses/LICENSE-2.0 12 | * 13 | * Unless required by applicable law or agreed to in writing, software 14 | * distributed under the License is distributed on an "AS IS" BASIS, 15 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | * See the License for the specific language governing permissions and 17 | * limitations under the License. 18 | */ 19 | 20 | import com.google.gson.JsonObject; 21 | import org.junit.Test; 22 | 23 | import static org.junit.Assert.assertEquals; 24 | import static org.junit.Assert.assertNotNull; 25 | 26 | /** 27 | * Unit test for simple function. 28 | */ 29 | public class FunctionAppTest { 30 | @Test 31 | public void testFunction() { 32 | JsonObject args = new JsonObject(); 33 | JsonObject response = FunctionApp.main(args); 34 | assertNotNull(response); 35 | String greetings = response.getAsJsonPrimitive("greetings").getAsString(); 36 | assertNotNull(greetings); 37 | assertEquals("Hello! Welcome to OpenWhisk on OpenShift", greetings); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /solutions/hello-web/dependency-reduced-pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4.0.0 4 | com.example 5 | hello-web 6 | 1.0-SNAPSHOT 7 | https://openwhisk.apache.org/ 8 | 9 | hello-web 10 | 11 | 12 | maven-shade-plugin 13 | 3.1.0 14 | 15 | 16 | package 17 | 18 | shade 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | junit 28 | junit 29 | 4.12 30 | test 31 | 32 | 33 | hamcrest-core 34 | org.hamcrest 35 | 36 | 37 | 38 | 39 | 40 | 1.8 41 | 2.8.2 42 | 1.8 43 | UTF-8 44 | 45 | 46 | 47 | -------------------------------------------------------------------------------- /solutions/hello-web/pom.xml: -------------------------------------------------------------------------------- 1 | 4 | 4.0.0 5 | com.example 6 | hello-web 7 | 1.0-SNAPSHOT 8 | https://openwhisk.apache.org/ 9 | 10 | UTF-8 11 | 1.8 12 | 1.8 13 | 2.8.2 14 | 15 | 16 | 17 | com.google.code.gson 18 | gson 19 | ${gson.version} 20 | 21 | 22 | junit 23 | junit 24 | 4.12 25 | test 26 | 27 | 28 | 29 | hello-web 30 | 31 | 32 | 33 | org.apache.maven.plugins 34 | maven-shade-plugin 35 | 3.1.0 36 | 37 | 38 | package 39 | 40 | shade 41 | 42 | 43 | 44 | 45 | 46 | 47 | -------------------------------------------------------------------------------- /solutions/hello-web/src/main/java/com/example/FunctionApp.java: -------------------------------------------------------------------------------- 1 | package com.example; 2 | 3 | /* 4 | * Licensed to the Apache Software Foundation (ASF) under one or more 5 | * contributor license agreements. See the NOTICE file distributed with 6 | * this work for additional information regarding copyright ownership. 7 | * The ASF licenses this file to You under the Apache License, Version 2.0 8 | * (the "License"); you may not use this file except in compliance with 9 | * the License. You may obtain a copy of the License at 10 | * 11 | * http://www.apache.org/licenses/LICENSE-2.0 12 | * 13 | * Unless required by applicable law or agreed to in writing, software 14 | * distributed under the License is distributed on an "AS IS" BASIS, 15 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | * See the License for the specific language governing permissions and 17 | * limitations under the License. 18 | */ 19 | 20 | import com.google.gson.JsonObject; 21 | 22 | /** 23 | * Hello FunctionApp 24 | */ 25 | public class FunctionApp { 26 | public static JsonObject main(JsonObject args) { 27 | JsonObject response = new JsonObject(); 28 | response.add("response", args); 29 | return response; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /solutions/hello-web/src/test/java/com/example/FunctionAppTest.java: -------------------------------------------------------------------------------- 1 | package com.example; 2 | 3 | /* 4 | * Licensed to the Apache Software Foundation (ASF) under one or more 5 | * contributor license agreements. See the NOTICE file distributed with 6 | * this work for additional information regarding copyright ownership. 7 | * The ASF licenses this file to You under the Apache License, Version 2.0 8 | * (the "License"); you may not use this file except in compliance with 9 | * the License. You may obtain a copy of the License at 10 | * 11 | * http://www.apache.org/licenses/LICENSE-2.0 12 | * 13 | * Unless required by applicable law or agreed to in writing, software 14 | * distributed under the License is distributed on an "AS IS" BASIS, 15 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | * See the License for the specific language governing permissions and 17 | * limitations under the License. 18 | */ 19 | 20 | import com.google.gson.JsonObject; 21 | import org.junit.Test; 22 | 23 | import static org.junit.Assert.assertEquals; 24 | import static org.junit.Assert.assertNotNull; 25 | 26 | /** 27 | * Unit test for simple function. 28 | */ 29 | public class FunctionAppTest { 30 | @Test 31 | public void testFunction() { 32 | JsonObject args = new JsonObject(); 33 | args.addProperty("name", "test"); 34 | JsonObject response = FunctionApp.main(args); 35 | assertNotNull(response); 36 | String actual = response.get("response").getAsJsonObject().get("name").getAsString(); 37 | assertEquals("test", actual); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /solutions/integration/slackapp-command/main.js: -------------------------------------------------------------------------------- 1 | function main(args) { 2 | console.log('Processing Slack Command :' + args); 3 | 4 | if (args.token != args.slackVerificationToken) { 5 | return { 6 | statusCode: 401 7 | } 8 | } 9 | 10 | var command = { 11 | user_id: args.user_id, 12 | response_url: args.response_url, 13 | text: args.text 14 | } 15 | 16 | var siteRegEx = /^site\??/g; 17 | var evanRegEx = /^evangelists\??/g; 18 | 19 | if (command.text.match(siteRegEx)) { 20 | return { 21 | "text": "developers.redhat.com" 22 | }; 23 | } else if (command.text.match(evanRegEx)) { 24 | return { 25 | "attachments": [ 26 | { 27 | "author_name": "Burr Sutter", 28 | "author_link": "https://twitter.com/burrsutter", 29 | "color": "good" 30 | }, 31 | { 32 | "author_name": "Don Schenck", 33 | "author_link": "https://twitter.com/donschenck", 34 | "color": "#439FE0" 35 | }, 36 | { 37 | "author_name": "Edson Yanaga", 38 | "author_link": "https://twitter.com/yanaga", 39 | "color": "#638FF0" 40 | }, 41 | { 42 | "author_name": "Rafael Benevides", 43 | "author_link": "https://twitter.com/rafabene", 44 | "color": "#433EF0" 45 | }, 46 | { 47 | "author_name": "Kamesh Sampath", 48 | "author_link": "https://twitter.com/kamesh_sampath", 49 | "color": "danger" 50 | } 51 | ] 52 | } 53 | } else { 54 | return { 55 | "text": "Learn more.Code more.Share more" 56 | } 57 | } 58 | 59 | } -------------------------------------------------------------------------------- /solutions/integration/slackapp-event-handler/pom.xml: -------------------------------------------------------------------------------- 1 | 5 | 4.0.0 6 | com.redhat.developers.openwhisk 7 | slackapp-event-handler 8 | 1.0-SNAPSHOT 9 | https://openwhisk.apache.org/ 10 | 11 | UTF-8 12 | 1.8 13 | 1.8 14 | 2.8.2 15 | 16 | 17 | 18 | com.google.code.gson 19 | gson 20 | ${gson.version} 21 | 22 | 23 | com.squareup.okhttp3 24 | okhttp 25 | 3.10.0 26 | 27 | 28 | 29 | ${artifactId} 30 | 31 | 32 | 33 | org.apache.maven.plugins 34 | maven-shade-plugin 35 | 3.1.0 36 | 37 | 38 | package 39 | 40 | shade 41 | 42 | 43 | 44 | 45 | 46 | 47 | -------------------------------------------------------------------------------- /solutions/integration/slackapp-event-handler/src/main/java/com/redhat/developers/openwhisk/FunctionApp.java: -------------------------------------------------------------------------------- 1 | package com.redhat.developers.openwhisk; 2 | 3 | import java.io.IOException; 4 | import java.util.Hashtable; 5 | 6 | import com.google.gson.JsonObject; 7 | import com.google.gson.JsonParser; 8 | 9 | import okhttp3.Call; 10 | import okhttp3.Callback; 11 | import okhttp3.FormBody; 12 | import okhttp3.HttpUrl; 13 | import okhttp3.OkHttpClient; 14 | import okhttp3.Request; 15 | import okhttp3.RequestBody; 16 | import okhttp3.Response; 17 | 18 | /* 19 | * Licensed to the Apache Software Foundation (ASF) under one or more 20 | * contributor license agreements. See the NOTICE file distributed with 21 | * this work for additional information regarding copyright ownership. 22 | * The ASF licenses this file to You under the Apache License, Version 2.0 23 | * (the "License"); you may not use this file except in compliance with 24 | * the License. You may obtain a copy of the License at 25 | * 26 | * http://www.apache.org/licenses/LICENSE-2.0 27 | * 28 | * Unless required by applicable law or agreed to in writing, software 29 | * distributed under the License is distributed on an "AS IS" BASIS, 30 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 31 | * See the License for the specific language governing permissions and 32 | * limitations under the License. 33 | */ 34 | 35 | /** 36 | * TODO 37 | */ 38 | public class FunctionApp { 39 | 40 | private static final Hashtable MEMDB = new Hashtable<>(); 41 | private static final HttpUrl SLACK_API_URL = HttpUrl.parse("https://slack.com/api/"); 42 | private static final String REPONSE_TEXT = "Hey %s, you said %s "; 43 | 44 | public static JsonObject main(JsonObject args) { 45 | //System.out.println("Processing Bot from Slack: " + args); 46 | 47 | JsonObject response = new JsonObject(); 48 | String token = null; 49 | 50 | if (args.has("token")) { 51 | token = args.getAsJsonPrimitive("token").getAsString(); 52 | } else { 53 | JsonObject headers = new JsonObject(); 54 | headers.addProperty("Content-Type", "application/json"); 55 | response.add("headers", headers); 56 | response.addProperty("statusCode", "401"); 57 | return response; 58 | } 59 | 60 | //Request parameters 61 | final String requestMethod = args.getAsJsonPrimitive("__ow_method").getAsString(); 62 | final String slackVerificationToken = args.has("slackVerificationToken") 63 | ? args.getAsJsonPrimitive("slackVerificationToken").getAsString() 64 | : null; 65 | final String requestType = args.has("type") ? args.getAsJsonPrimitive("type").getAsString() : null; 66 | final String challenge = args.has("challenge") ? args.getAsJsonPrimitive("challenge").getAsString() : null; 67 | 68 | if ("post".equals(requestMethod) && "url_verification".equals(requestType) 69 | && (token != null && token.equals(slackVerificationToken)) && challenge != null) { 70 | //System.out.println("Handling Verification Request"); 71 | JsonObject headers = new JsonObject(); 72 | headers.addProperty("Content-Type", "application/json"); 73 | response.add("headers", headers); 74 | JsonObject body = new JsonObject(); 75 | body.addProperty("challenge", challenge); 76 | response.add("body", body); 77 | //System.out.println("Sent Challenge Response :" + response); 78 | return response; 79 | } 80 | 81 | JsonObject owHeaders = args.getAsJsonObject("__ow_headers"); 82 | 83 | //Handling Timeout Retries - for slow network 84 | if (owHeaders.has("x-slack-retry-reason")) { 85 | String reason = owHeaders.getAsJsonPrimitive("x-slack-retry-reason").getAsString(); 86 | //System.out.println("Retry Reason:" + reason); 87 | if ("http_timeout".equalsIgnoreCase(reason)) { 88 | JsonObject r = new JsonObject(); 89 | //System.out.println("Handling Event Retries"); 90 | JsonObject headers = new JsonObject(); 91 | r.addProperty("Content-Type", "application/json"); 92 | r.add("headers", headers); 93 | r.addProperty("statusCode", 200); 94 | return r; 95 | } 96 | } 97 | 98 | //Handle the event 99 | //System.out.println("Handling Event from Slack: " + args); 100 | 101 | final OkHttpClient okHttpClient = new OkHttpClient.Builder().build(); 102 | 103 | JsonObject headers = new JsonObject(); 104 | headers.addProperty("Content-Type", "application/json"); 105 | response.add("headers", headers); 106 | response.addProperty("statusCode", "200"); 107 | 108 | JsonObject event = args.getAsJsonObject("event"); 109 | 110 | final String eventType = event.has("type") ? event.getAsJsonPrimitive("type").getAsString() : null; 111 | final String botUserOAuthToken = args.has("botUserOAuthToken") 112 | ? args.getAsJsonPrimitive("botUserOAuthToken").getAsString() 113 | : null; 114 | final String user = event.has("user") ? event.getAsJsonPrimitive("user").getAsString() : null; 115 | 116 | if ("message".equals(eventType) && user != null) { 117 | RequestBody userRequest = new FormBody.Builder().add("token", botUserOAuthToken).add("user", user).build(); 118 | Request request = new Request.Builder().url(SLACK_API_URL + "/users.info").post(userRequest).build(); 119 | okHttpClient.newCall(request).enqueue(new Callback() { 120 | @Override 121 | public void onResponse(Call call, Response r) throws IOException { 122 | try { 123 | if (r.isSuccessful()) { 124 | JsonObject responseObj = new JsonParser().parse(r.body().string()).getAsJsonObject(); 125 | JsonObject userObj = responseObj.get("user").getAsJsonObject(); 126 | postMessage(response, okHttpClient, event, botUserOAuthToken, user, userObj); 127 | } 128 | } catch (Exception e) { 129 | e.printStackTrace(); 130 | } 131 | } 132 | 133 | @Override 134 | public void onFailure(Call call, IOException e) { 135 | e.printStackTrace(); 136 | } 137 | }); 138 | 139 | } 140 | 141 | return response; 142 | } 143 | 144 | /** 145 | * 146 | */ 147 | private static void postMessage(JsonObject response, OkHttpClient okHttpClient, JsonObject event, 148 | String botUserOAuthToken, String user, JsonObject userObj) throws IOException { 149 | 150 | final String channel = event.has("channel") ? event.getAsJsonPrimitive("channel").getAsString() : null; 151 | final String text = event.has("text") ? event.getAsJsonPrimitive("text").getAsString() : "No Message!!"; 152 | 153 | final String userName = userObj.has("real_name") ? userObj.getAsJsonPrimitive("real_name").getAsString() 154 | : "Anonymous"; 155 | 156 | RequestBody messageRequest = new FormBody.Builder().add("token", botUserOAuthToken).add("channel", channel) 157 | .add("text", String.format(REPONSE_TEXT, userName, text)).build(); 158 | 159 | Request request = new Request.Builder().url(SLACK_API_URL + "/chat.postMessage").post(messageRequest).build(); 160 | 161 | Call call = okHttpClient.newCall(request); 162 | Response r = call.execute(); 163 | if (r.isSuccessful()) { 164 | response.addProperty("status", r.message()); 165 | response.addProperty("message", "Message sent successfully to user :" + userName); 166 | } else { 167 | response.addProperty("status", r.message()); 168 | response.addProperty("message", "Unable to post Message to user :" + user + ", Reason:" + r.message()); 169 | } 170 | } 171 | } 172 | -------------------------------------------------------------------------------- /solutions/integration/slackapp-event-handler/src/test/java/com/redhat/developers/openwhisk/DemoMain.java: -------------------------------------------------------------------------------- 1 | package com.redhat.developers.openwhisk; 2 | 3 | import com.google.gson.JsonObject; 4 | import com.google.gson.JsonParser; 5 | import okhttp3.*; 6 | 7 | import java.io.IOException; 8 | import java.util.Hashtable; 9 | 10 | public class DemoMain { 11 | 12 | 13 | private static final Hashtable MEMDB = new Hashtable<>(); 14 | private static final HttpUrl SLACK_API_URL = HttpUrl.parse("https://slack.com/api"); 15 | private static final String REPONSE_TEXT = "Hey %s, you said %s "; 16 | 17 | public static void main(String[] args) { 18 | 19 | OkHttpClient okHttpClient = new OkHttpClient.Builder().build(); 20 | 21 | String botUserOAuthToken = "xoxb-347428117411-kOv2agZFhRDiDqUhoKjuRBH2"; 22 | String user = "U9SKXM8QN"; 23 | 24 | RequestBody requestBody = new FormBody.Builder() 25 | .add("token", botUserOAuthToken) 26 | .add("user", user) 27 | .build(); 28 | 29 | Request request = new Request.Builder() 30 | .url(SLACK_API_URL + "/users.info") 31 | .post(requestBody) 32 | .build(); 33 | 34 | Call call = okHttpClient.newCall(request); 35 | 36 | try { 37 | Response r = call.execute(); 38 | String str = r.body().string(); 39 | JsonObject responseObj = new JsonParser().parse(str).getAsJsonObject(); 40 | JsonObject userObj = responseObj.get("user").getAsJsonObject(); 41 | 42 | final String userName = userObj.has("real_name") ? 43 | userObj.getAsJsonPrimitive("real_name").getAsString() : "Anonymous"; 44 | 45 | RequestBody messageRequest = new FormBody.Builder() 46 | .add("token", botUserOAuthToken) 47 | .add("channel", "DA7FKK29G") 48 | .add("text", String.format(REPONSE_TEXT, userName, "From DemoMain")) 49 | .build(); 50 | 51 | request = new Request.Builder() 52 | .url(SLACK_API_URL + "/chat.postMessage") 53 | .post(messageRequest) 54 | .build(); 55 | 56 | call = okHttpClient.newCall(request); 57 | r = call.execute(); 58 | 59 | if (r.isSuccessful()) { 60 | System.out.println("Successfull!"); 61 | } else { 62 | System.err.println("Failed:" + r.message()); 63 | } 64 | } catch (Exception e) { 65 | e.printStackTrace(); 66 | } 67 | 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /solutions/sequence-demo/sorter/dependency-reduced-pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4.0.0 4 | com.example 5 | sorter 6 | 1.0-SNAPSHOT 7 | https://openwhisk.apache.org/ 8 | 9 | sorter 10 | 11 | 12 | maven-shade-plugin 13 | 3.1.0 14 | 15 | 16 | package 17 | 18 | shade 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | junit 28 | junit 29 | 4.12 30 | test 31 | 32 | 33 | hamcrest-core 34 | org.hamcrest 35 | 36 | 37 | 38 | 39 | 40 | 2.8.2 41 | 1.8 42 | UTF-8 43 | 1.8 44 | 45 | 46 | 47 | -------------------------------------------------------------------------------- /solutions/sequence-demo/sorter/pom.xml: -------------------------------------------------------------------------------- 1 | 4 | 4.0.0 5 | com.example 6 | sorter 7 | 1.0-SNAPSHOT 8 | https://openwhisk.apache.org/ 9 | 10 | UTF-8 11 | 1.8 12 | 1.8 13 | 2.8.2 14 | 15 | 16 | 17 | com.google.code.gson 18 | gson 19 | ${gson.version} 20 | 21 | 22 | junit 23 | junit 24 | 4.12 25 | test 26 | 27 | 28 | 29 | sorter 30 | 31 | 32 | 33 | org.apache.maven.plugins 34 | maven-shade-plugin 35 | 3.1.0 36 | 37 | 38 | package 39 | 40 | shade 41 | 42 | 43 | 44 | 45 | 46 | 47 | -------------------------------------------------------------------------------- /solutions/sequence-demo/sorter/src/main/java/com/example/FunctionApp.java: -------------------------------------------------------------------------------- 1 | package com.example; 2 | 3 | /* 4 | * Licensed to the Apache Software Foundation (ASF) under one or more 5 | * contributor license agreements. See the NOTICE file distributed with 6 | * this work for additional information regarding copyright ownership. 7 | * The ASF licenses this file to You under the Apache License, Version 2.0 8 | * (the "License"); you may not use this file except in compliance with 9 | * the License. You may obtain a copy of the License at 10 | * 11 | * http://www.apache.org/licenses/LICENSE-2.0 12 | * 13 | * Unless required by applicable law or agreed to in writing, software 14 | * distributed under the License is distributed on an "AS IS" BASIS, 15 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | * See the License for the specific language governing permissions and 17 | * limitations under the License. 18 | */ 19 | 20 | import com.google.gson.JsonArray; 21 | import com.google.gson.JsonObject; 22 | 23 | import java.util.ArrayList; 24 | import java.util.Comparator; 25 | import java.util.List; 26 | 27 | /** 28 | * Hello FunctionApp 29 | */ 30 | public class FunctionApp { 31 | public static JsonObject main(JsonObject args) { 32 | JsonObject response = new JsonObject(); 33 | List upperStrings = new ArrayList<>(); 34 | if (args.has("result")) { 35 | args.getAsJsonArray("result").forEach(e -> upperStrings.add(e.getAsString())); 36 | } 37 | 38 | JsonArray sortedArray = new JsonArray(); 39 | upperStrings.stream().sorted(Comparator.naturalOrder()).forEach(s -> sortedArray.add(s)); 40 | 41 | response.add("result", sortedArray); 42 | return response; 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /solutions/sequence-demo/sorter/src/test/java/com/example/FunctionAppTest.java: -------------------------------------------------------------------------------- 1 | package com.example; 2 | 3 | /* 4 | * Licensed to the Apache Software Foundation (ASF) under one or more 5 | * contributor license agreements. See the NOTICE file distributed with 6 | * this work for additional information regarding copyright ownership. 7 | * The ASF licenses this file to You under the Apache License, Version 2.0 8 | * (the "License"); you may not use this file except in compliance with 9 | * the License. You may obtain a copy of the License at 10 | * 11 | * http://www.apache.org/licenses/LICENSE-2.0 12 | * 13 | * Unless required by applicable law or agreed to in writing, software 14 | * distributed under the License is distributed on an "AS IS" BASIS, 15 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | * See the License for the specific language governing permissions and 17 | * limitations under the License. 18 | */ 19 | 20 | import static org.junit.Assert.*; 21 | 22 | import com.google.gson.JsonArray; 23 | import com.google.gson.JsonObject; 24 | 25 | import org.junit.Test; 26 | 27 | import java.util.ArrayList; 28 | import java.util.List; 29 | 30 | /** 31 | * Unit test for simple function. 32 | */ 33 | public class FunctionAppTest { 34 | @Test 35 | public void testFunction() { 36 | JsonObject args = new JsonObject(); 37 | JsonArray splitStrings = new JsonArray(); 38 | splitStrings.add("APPLE"); 39 | splitStrings.add("ORANGE"); 40 | splitStrings.add("BANANA"); 41 | args.add("result", splitStrings); 42 | JsonObject response = FunctionApp.main(args); 43 | assertNotNull(response); 44 | JsonArray results = response.getAsJsonArray("result"); 45 | assertNotNull(results); 46 | assertEquals(3, results.size()); 47 | List actuals = new ArrayList<>(); 48 | results.forEach(j -> actuals.add(j.getAsString())); 49 | assertTrue(actuals.get(0).equals("APPLE")); 50 | assertTrue(actuals.get(1).equals("BANANA")); 51 | assertTrue(actuals.get(2).equals("ORANGE")); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /solutions/sequence-demo/splitter/dependency-reduced-pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4.0.0 4 | com.example 5 | splitter 6 | 1.0-SNAPSHOT 7 | https://openwhisk.apache.org/ 8 | 9 | splitter 10 | 11 | 12 | maven-shade-plugin 13 | 3.1.0 14 | 15 | 16 | package 17 | 18 | shade 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | junit 28 | junit 29 | 4.12 30 | test 31 | 32 | 33 | hamcrest-core 34 | org.hamcrest 35 | 36 | 37 | 38 | 39 | 40 | 2.8.2 41 | 1.8 42 | UTF-8 43 | 1.8 44 | 45 | 46 | 47 | -------------------------------------------------------------------------------- /solutions/sequence-demo/splitter/pom.xml: -------------------------------------------------------------------------------- 1 | 4 | 4.0.0 5 | com.example 6 | splitter 7 | 1.0-SNAPSHOT 8 | https://openwhisk.apache.org/ 9 | 10 | UTF-8 11 | 1.8 12 | 1.8 13 | 2.8.2 14 | 15 | 16 | 17 | com.google.code.gson 18 | gson 19 | ${gson.version} 20 | 21 | 22 | junit 23 | junit 24 | 4.12 25 | test 26 | 27 | 28 | 29 | splitter 30 | 31 | 32 | 33 | org.apache.maven.plugins 34 | maven-shade-plugin 35 | 3.1.0 36 | 37 | 38 | package 39 | 40 | shade 41 | 42 | 43 | 44 | 45 | 46 | 47 | -------------------------------------------------------------------------------- /solutions/sequence-demo/splitter/src/main/java/com/example/FunctionApp.java: -------------------------------------------------------------------------------- 1 | package com.example; 2 | 3 | /* 4 | * Licensed to the Apache Software Foundation (ASF) under one or more 5 | * contributor license agreements. See the NOTICE file distributed with 6 | * this work for additional information regarding copyright ownership. 7 | * The ASF licenses this file to You under the Apache License, Version 2.0 8 | * (the "License"); you may not use this file except in compliance with 9 | * the License. You may obtain a copy of the License at 10 | * 11 | * http://www.apache.org/licenses/LICENSE-2.0 12 | * 13 | * Unless required by applicable law or agreed to in writing, software 14 | * distributed under the License is distributed on an "AS IS" BASIS, 15 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | * See the License for the specific language governing permissions and 17 | * limitations under the License. 18 | */ 19 | 20 | import com.google.gson.JsonArray; 21 | import com.google.gson.JsonObject; 22 | 23 | /** 24 | * Hello FunctionApp 25 | */ 26 | public class FunctionApp { 27 | public static JsonObject main(JsonObject args) { 28 | JsonObject response = new JsonObject(); 29 | String text = null; 30 | if (args.has("text")) { 31 | text = args.getAsJsonPrimitive("text").getAsString(); 32 | } 33 | String[] results = new String[] { text }; 34 | if (text != null && text.indexOf(",") != -1) { 35 | results = text.split(","); 36 | } 37 | JsonArray splitStrings = new JsonArray(); 38 | for (String var : results) { 39 | splitStrings.add(var); 40 | } 41 | response.add("result", splitStrings); 42 | return response; 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /solutions/sequence-demo/splitter/src/test/java/com/example/FunctionAppTest.java: -------------------------------------------------------------------------------- 1 | package com.example; 2 | 3 | /* 4 | * Licensed to the Apache Software Foundation (ASF) under one or more 5 | * contributor license agreements. See the NOTICE file distributed with 6 | * this work for additional information regarding copyright ownership. 7 | * The ASF licenses this file to You under the Apache License, Version 2.0 8 | * (the "License"); you may not use this file except in compliance with 9 | * the License. You may obtain a copy of the License at 10 | * 11 | * http://www.apache.org/licenses/LICENSE-2.0 12 | * 13 | * Unless required by applicable law or agreed to in writing, software 14 | * distributed under the License is distributed on an "AS IS" BASIS, 15 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | * See the License for the specific language governing permissions and 17 | * limitations under the License. 18 | */ 19 | 20 | import static org.junit.Assert.*; 21 | 22 | import com.google.gson.JsonArray; 23 | import com.google.gson.JsonObject; 24 | 25 | import org.junit.Test; 26 | 27 | import java.util.ArrayList; 28 | import java.util.List; 29 | 30 | /** 31 | * Unit test for simple function. 32 | */ 33 | public class FunctionAppTest { 34 | @Test 35 | public void testFunction() { 36 | JsonObject args = new JsonObject(); 37 | args.addProperty("text", "apple,orange,banana"); 38 | JsonObject response = FunctionApp.main(args); 39 | assertNotNull(response); 40 | JsonArray results = response.getAsJsonArray("result"); 41 | assertNotNull(results); 42 | assertEquals(3, results.size()); 43 | List actuals = new ArrayList<>(); 44 | results.forEach(j -> actuals.add(j.getAsString())); 45 | assertTrue(actuals.contains("apple")); 46 | assertTrue(actuals.contains("orange")); 47 | assertTrue(actuals.contains("banana")); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /solutions/sequence-demo/uppercase/dependency-reduced-pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4.0.0 4 | com.example 5 | uppercase 6 | 1.0-SNAPSHOT 7 | https://openwhisk.apache.org/ 8 | 9 | uppercase 10 | 11 | 12 | maven-shade-plugin 13 | 3.1.0 14 | 15 | 16 | package 17 | 18 | shade 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | junit 28 | junit 29 | 4.12 30 | test 31 | 32 | 33 | hamcrest-core 34 | org.hamcrest 35 | 36 | 37 | 38 | 39 | 40 | 2.8.2 41 | 1.8 42 | UTF-8 43 | 1.8 44 | 45 | 46 | 47 | -------------------------------------------------------------------------------- /solutions/sequence-demo/uppercase/pom.xml: -------------------------------------------------------------------------------- 1 | 4 | 4.0.0 5 | com.example 6 | uppercase 7 | 1.0-SNAPSHOT 8 | https://openwhisk.apache.org/ 9 | 10 | UTF-8 11 | 1.8 12 | 1.8 13 | 2.8.2 14 | 15 | 16 | 17 | com.google.code.gson 18 | gson 19 | ${gson.version} 20 | 21 | 22 | junit 23 | junit 24 | 4.12 25 | test 26 | 27 | 28 | 29 | uppercase 30 | 31 | 32 | 33 | org.apache.maven.plugins 34 | maven-shade-plugin 35 | 3.1.0 36 | 37 | 38 | package 39 | 40 | shade 41 | 42 | 43 | 44 | 45 | 46 | 47 | -------------------------------------------------------------------------------- /solutions/sequence-demo/uppercase/src/main/java/com/example/FunctionApp.java: -------------------------------------------------------------------------------- 1 | package com.example; 2 | 3 | /* 4 | * Licensed to the Apache Software Foundation (ASF) under one or more 5 | * contributor license agreements. See the NOTICE file distributed with 6 | * this work for additional information regarding copyright ownership. 7 | * The ASF licenses this file to You under the Apache License, Version 2.0 8 | * (the "License"); you may not use this file except in compliance with 9 | * the License. You may obtain a copy of the License at 10 | * 11 | * http://www.apache.org/licenses/LICENSE-2.0 12 | * 13 | * Unless required by applicable law or agreed to in writing, software 14 | * distributed under the License is distributed on an "AS IS" BASIS, 15 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | * See the License for the specific language governing permissions and 17 | * limitations under the License. 18 | */ 19 | 20 | import com.google.gson.JsonArray; 21 | import com.google.gson.JsonObject; 22 | 23 | /** 24 | * Hello FunctionApp 25 | */ 26 | public class FunctionApp { 27 | public static JsonObject main(JsonObject args) { 28 | JsonObject response = new JsonObject(); 29 | JsonArray upperArray = new JsonArray(); 30 | if (args.has("result")) { 31 | args.getAsJsonArray("result").forEach(e -> upperArray.add(e.getAsString().toUpperCase())); 32 | } 33 | response.add("result", upperArray); 34 | return response; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /solutions/sequence-demo/uppercase/src/test/java/com/example/FunctionAppTest.java: -------------------------------------------------------------------------------- 1 | package com.example; 2 | 3 | /* 4 | * Licensed to the Apache Software Foundation (ASF) under one or more 5 | * contributor license agreements. See the NOTICE file distributed with 6 | * this work for additional information regarding copyright ownership. 7 | * The ASF licenses this file to You under the Apache License, Version 2.0 8 | * (the "License"); you may not use this file except in compliance with 9 | * the License. You may obtain a copy of the License at 10 | * 11 | * http://www.apache.org/licenses/LICENSE-2.0 12 | * 13 | * Unless required by applicable law or agreed to in writing, software 14 | * distributed under the License is distributed on an "AS IS" BASIS, 15 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | * See the License for the specific language governing permissions and 17 | * limitations under the License. 18 | */ 19 | 20 | import com.google.gson.JsonArray; 21 | import com.google.gson.JsonObject; 22 | import org.junit.Test; 23 | 24 | import java.util.ArrayList; 25 | import java.util.List; 26 | 27 | import static org.junit.Assert.assertEquals; 28 | import static org.junit.Assert.assertNotNull; 29 | import static org.junit.Assert.assertTrue; 30 | 31 | /** 32 | * Unit test for simple function. 33 | */ 34 | public class FunctionAppTest { 35 | @Test 36 | public void testFunction() { 37 | JsonObject args = new JsonObject(); 38 | JsonArray splitStrings = new JsonArray(); 39 | splitStrings.add("apple"); 40 | splitStrings.add("orange"); 41 | splitStrings.add("banana"); 42 | args.add("result", splitStrings); 43 | JsonObject response = FunctionApp.main(args); 44 | assertNotNull(response); 45 | JsonArray results = response.getAsJsonArray("result"); 46 | assertNotNull(results); 47 | assertEquals(3, results.size()); 48 | List actuals = new ArrayList<>(); 49 | results.forEach(j -> actuals.add(j.getAsString())); 50 | assertTrue(actuals.contains("APPLE")); 51 | assertTrue(actuals.contains("ORANGE")); 52 | assertTrue(actuals.contains("BANANA")); 53 | } 54 | } 55 | --------------------------------------------------------------------------------