├── .gitignore ├── .openshift ├── .leinrc └── action_hooks │ ├── pre_deploy_wildfly │ ├── start │ └── stop ├── LICENSE ├── Procfile ├── README.md ├── app.json ├── doc ├── images │ ├── immutant-runtime.png │ ├── immutant_logo.jpg │ └── tomcat-runtime.png └── overview.org ├── eap-resources └── WEB-INF │ └── jboss-web.xml ├── project.clj ├── resources ├── jbossts-properties.xml ├── public │ ├── css │ │ └── style.css │ ├── index.html │ ├── js │ │ └── app.js │ ├── sse.html │ └── websocket.html ├── server.keystore └── server.truststore └── src └── demo ├── caching.clj ├── core.clj ├── messaging.clj ├── remote_messaging_client.clj ├── scheduling.clj ├── transactions.clj ├── web.clj └── web ├── http_kit_comparison.clj └── sse.clj /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | /lib 3 | /classes 4 | /checkouts 5 | /.descriptors 6 | pom.xml 7 | pom.xml.asc 8 | *.jar 9 | *.class 10 | .lein-deps-sum 11 | .lein-failures 12 | .lein-plugins 13 | .lein-repl-history 14 | /.nrepl-port 15 | wildfly-* 16 | /.lein-env 17 | /hornetq-data/ 18 | -------------------------------------------------------------------------------- /.openshift/.leinrc: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | export LEIN_HOME="${OPENSHIFT_DATA_DIR}/.lein" 3 | export LEIN_JVM_OPTS="-Duser.home=${LEIN_HOME}" 4 | export JVM_OPTS="-Dhornetq.netty.port=15000 -Dhornetq.netty.host=${OPENSHIFT_DIY_IP}" 5 | export DEMO_WEB_HOST=${OPENSHIFT_DIY_IP} 6 | export DEMO_WEB_PORT=${OPENSHIFT_DIY_PORT} 7 | 8 | if [ ! -d ${LEIN_HOME} ]; then 9 | echo "Installing Leiningen" 10 | cd ${OPENSHIFT_DATA_DIR} 11 | wget https://raw.github.com/technomancy/leiningen/stable/bin/lein 12 | if [ -f lein ]; then 13 | chmod +x lein 14 | mkdir -p $LEIN_HOME 15 | fi 16 | fi 17 | -------------------------------------------------------------------------------- /.openshift/action_hooks/pre_deploy_wildfly: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | source ${OPENSHIFT_REPO_DIR}/.openshift/.leinrc 3 | 4 | cd ${OPENSHIFT_REPO_DIR} 5 | mkdir -p deployments 6 | ${OPENSHIFT_DATA_DIR}/lein do clean, immutant war -o deployments -n ROOT 7 | -------------------------------------------------------------------------------- /.openshift/action_hooks/start: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | source ${OPENSHIFT_REPO_DIR}/.openshift/.leinrc 3 | 4 | cd ${OPENSHIFT_REPO_DIR} 5 | nohup ${OPENSHIFT_DATA_DIR}/lein trampoline run >${OPENSHIFT_LOG_DIR}/server.log 2>&1 & 6 | -------------------------------------------------------------------------------- /.openshift/action_hooks/stop: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | pid=`ps -ef | grep lein | grep -v grep | awk '{ print $2 }'` 3 | if [[ $pid != "" ]]; then 4 | kill $pid 5 | fi 6 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /Procfile: -------------------------------------------------------------------------------- 1 | web: java $JVM_OPTS -jar target/demo-standalone.jar host 0.0.0.0 port $PORT ssl-port nil 2 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Immutant Feature Demo 2 | 3 | An app showing trivial examples of all the Immutant libraries. Most 4 | log something to stdout, but the `demo.web` examples are available at 5 | . 6 | 7 | You can view a running example here: 8 | . 9 | 10 | You need at least Java 8 and Leiningen 2.4.0 11 | 12 | ### SSL and HTTP/2 13 | 14 | By default, the web demo fires up only one HTTP listener on port 8080. 15 | But if you set the `ssl-port` option, it'll also fire up an HTTPS 16 | listener with a self-signed certificate. You can even enable HTTP 2.0 17 | on that port by setting the `http2?` option. Doing so requires a 18 | version of 19 | [ALPN](http://www.eclipse.org/jetty/documentation/current/alpn-chapter.html) 20 | to be available on the *bootclasspath*. We rely on 21 | [a convenient Java agent](https://github.com/trustin/jetty-alpn-agent) 22 | to load one appropriate for your JVM. This agent is invoked, and the 23 | above options are set when the `:http2` profile defined in 24 | `project.clj` is enabled, like so: 25 | 26 | lein with-profile http2 run 27 | 28 | You can run the app in several ways: 29 | 30 | * [With lein run](#with-lein-run) 31 | * [At a repl](#at-a-repl) 32 | * [From a jar](#from-a-jar) 33 | * [In WildFly](#in-wildfly) 34 | * [In a cluster](#in-a-wildfly-cluster) 35 | * [On Heroku](#on-heroku) 36 | * [On OpenShift](#on-openshift) 37 | * [In a WildFly cluster](#in-a-wildfly-cluster-on-openshift) 38 | 39 | ## With lein run 40 | 41 | The value of `:main` in `project.clj` is `demo.core`, which runs 42 | `-main` for all of the demo namespaces. 43 | 44 | lein run 45 | 46 | You can use the -m option to run specific namespaces, e.g. 47 | 48 | lein run -m demo.web 49 | 50 | And you can run an HTTP/2.0 listener on port 9999 like this: 51 | 52 | lein with-profile http2 run -m demo.web ssl-port 9999 53 | 54 | ## At a repl 55 | 56 | You can fire up a repl and invoke each namespace directly 57 | 58 | lein repl 59 | 60 | Once at a prompt, try `(demo.web/-main)` 61 | 62 | Or, for an HTTP/2.0 listener, try this: 63 | 64 | `(demo.web/-main "ssl-port" 9999 "http2?" true)` 65 | 66 | You'll note in the `demo.web/-main` function that the option keys are 67 | expected to be strings so that command line arguments can override 68 | them. 69 | 70 | ## From a jar 71 | 72 | Create an uberjar and run it 73 | 74 | lein uberjar 75 | java -jar target/demo-standalone.jar 76 | 77 | To create an HTTP/2.0 listener from the uberjar, we'll need to do some 78 | work. Because we're no longer running the app from Leiningen, our 79 | `:http2` profile does us no good, so we'll need to manually invoke the 80 | ALPN Java agent (described above). We'll also need to pass the 81 | necessary `ssl-port` and `http2?` command line options. Once you 82 | locate the agent jar in your local Maven repo, you may test HTTP/2 83 | like so: 84 | 85 | java -javaagent:{/path/to/jetty-alpn-agent.jar} -jar target/demo-standalone.jar ssl-port 8443 http2? true 86 | 87 | This assumes you've activated the `:http2` profile at some point. If 88 | you haven't, the agent jar won't be in your repo. To fetch it, try: 89 | 90 | lein with-profile http2 check 91 | 92 | ## In WildFly 93 | 94 | [WildFly](http://wildfly.org) is installed by downloading and 95 | unpacking an archive. For our purposes, we'll drop it in the project 96 | directory. For a list of available versions, see 97 | 98 | 99 | VERSION=10.0.0.Final 100 | 101 | # Install WildFly 102 | wget http://download.jboss.org/wildfly/$VERSION/wildfly-$VERSION.zip 103 | unzip wildfly-$VERSION.zip 104 | 105 | # Create the war file and deploy it to WildFly 106 | lein immutant war -o wildfly-$VERSION 107 | 108 | # Fire up WildFly 109 | wildfly-$VERSION/bin/standalone.sh -c standalone-full.xml 110 | 111 | Note the web examples will be deployed with a context path of `/demo` 112 | on WildFly so go to to see the web 113 | examples. Alternatively, to mount the app at the root context, 114 | , rename the war file beneath 115 | `wildfly-$VERSION/standalone/deployments/` to `ROOT.war`. 116 | 117 | ### In a WildFly cluster 118 | 119 | We'll simulate a cluster by "installing" another WildFly instance: 120 | 121 | cp -R wildfly-$VERSION wildfly-too 122 | rm -rf wildfly-too/standalone/data/ 123 | 124 | Because we already deployed the war file, it gets copied over, too. 125 | And to avoid spurious errors, we remove the `standalone/data` 126 | directory where WildFly keeps some runtime state. 127 | 128 | Now we'll start our first instance: 129 | 130 | wildfly-$VERSION/bin/standalone.sh -c standalone-full-ha.xml -Djboss.node.name=one -Djboss.messaging.cluster.password=demo 131 | 132 | Note the following: 133 | 134 | * We use the `standalone-full-ha.xml` file in which clustering is 135 | configured 136 | * Since both of our peers will be on the same host, we need to 137 | give each node a unique name 138 | * The cluster requires a password 139 | 140 | In another shell, we fire up the second instance with similar options 141 | plus a system property to avoid port conflicts, since we're on the 142 | same host. 143 | 144 | wildfly-too/bin/standalone.sh -c standalone-full-ha.xml -Djboss.node.name=two -Djboss.messaging.cluster.password=demo -Djboss.socket.binding.port-offset=100 145 | 146 | You can correlate the output from both peers to the code beneath 147 | `src/demo` to observe HA singleton jobs, load-balanced messaging, and 148 | distributed caching. And you can observe session replication by 149 | reloading the following pages in your browser: 150 | 151 | * 152 | * 153 | 154 | ## On Heroku 155 | 156 | Press this button: 157 | 158 | [![Deploy to Heroku](https://www.herokucdn.com/deploy/button.png)](https://heroku.com/deploy) 159 | 160 | Or do it manually. [Heroku](http://heroku.com) requires a `Procfile` in the project 161 | root to bootstrap the app. With this in place, we simply create the heroku repo 162 | and push: 163 | 164 | heroku create 165 | git push heroku master 166 | 167 | To see the log output: 168 | 169 | heroku logs --tail 170 | 171 | And to open the app in the browser: 172 | 173 | heroku open 174 | 175 | ## On OpenShift 176 | 177 | The app includes `start` and `stop` *action hooks* beneath the 178 | `.openshift/` directory that enable it to be deployed on 179 | [OpenShift](http://openshift.com) using the 180 | [DIY cartridge](https://developers.openshift.com/en/diy-overview.html). 181 | 182 | We'll call our application `demo`: 183 | 184 | rhc app-create demo diy --from-code https://github.com/immutant/feature-demo 185 | 186 | To see the log output: 187 | 188 | cd demo 189 | rhc tail 190 | 191 | Once the app is up, visit 192 | `http://demo-.rhcloud.com:8000/`. The port, 8000, is 193 | optional for all but the WebSocket example, because OpenShift only 194 | supports WebSockets on port 8000. 195 | 196 | ### In a WildFly cluster on OpenShift 197 | 198 | We can use the 199 | [WildFly cartridge](https://developers.openshift.com/en/wildfly-overview.html) 200 | to create a 201 | [scaled application](https://developers.openshift.com/en/overview-platform-features.html#scaling) 202 | named `wf`. The `pre_deploy_wildfly` action hook will create our war 203 | file in a directory monitored by the app server. 204 | 205 | rhc app-create wf wildfly --scaling --gear-size medium --from-code https://github.com/immutant/feature-demo 206 | 207 | Note we set the `--scaling` option and a medium `--gear-size`. It will 208 | take a few minutes for the command to complete. Once it does, monitor 209 | the log output: 210 | 211 | cd wf 212 | rhc tail 213 | 214 | View the web examples at `http://wf-.rhcloud.com:8000/` 215 | 216 | Try scaling the app up to 2 gears: 217 | 218 | rhc cartridge-scale wildfly 2 219 | 220 | View the gears for your app to obtain their ssh URL's: 221 | 222 | rhc app-show --gears 223 | 224 | Login to a gear to monitor/control it: 225 | 226 | rhc ssh 227 | help 228 | gear restart 229 | tail_all 230 | -------------------------------------------------------------------------------- /app.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "Immutant Feature Demo", 3 | "description": "A template for getting started with the popular Immutant framework.", 4 | "website": "http://immutant.org", 5 | "success_url": "/index.html", 6 | "addons": ["heroku-postgresql"], 7 | "image": "heroku/clojure" 8 | } 9 | -------------------------------------------------------------------------------- /doc/images/immutant-runtime.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/immutant/feature-demo/151fb330601421a23a1bdfd71f724afcdba0900c/doc/images/immutant-runtime.png -------------------------------------------------------------------------------- /doc/images/immutant_logo.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/immutant/feature-demo/151fb330601421a23a1bdfd71f724afcdba0900c/doc/images/immutant_logo.jpg -------------------------------------------------------------------------------- /doc/images/tomcat-runtime.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/immutant/feature-demo/151fb330601421a23a1bdfd71f724afcdba0900c/doc/images/tomcat-runtime.png -------------------------------------------------------------------------------- /doc/overview.org: -------------------------------------------------------------------------------- 1 | [[file:images/immutant_logo.jpg]] 2 | 3 | * What is Immutant? 4 | 5 | A collection of libraries that can be embedded within any Clojure 6 | application. Optionally, the application can be deployed to a stock 7 | [[http://wildfly.org][WildFly]] application server. 8 | 9 | * The [[https://github.com/immutant/lein-immutant/][lein-immutant]] plugin 10 | 11 | Only required if deploying your app to WildFly. 12 | 13 | ** Tasks 14 | 15 | - lein immutant war 16 | 17 | * Using outside of WildFly 18 | 19 | Set a =:main= in =project.clj=, and start with =lein run=. 20 | 21 | * Immutant API's 22 | 23 | Functions whose side effects invoke JBoss services 24 | 25 | ** immutant.web 26 | 27 | - app segmentation via virtual host and/or context path 28 | - automatic session replication in a cluster 29 | - auto-reloading in dev mode 30 | - static resources served via [[http://ring-clojure.github.io/ring/ring.middleware.resource.html#var-wrap-resource][ring.middleware.resource/wrap-resource]] 31 | - :ring config, e.g. :handler, :init, :destroy, 32 | stacktraces?, :auto-reload?, :reload-paths 33 | - simple websockets 34 | 35 | examples: [[../src/demo/web.clj][demo/web.clj]] and [[../src/demo/websocket.clj][demo/websocket.clj]] 36 | 37 | ** immutant.scheduling 38 | 39 | - schedules specified by maps created with helper functions 40 | - non-singleton by default (runs on every one node in cluster) 41 | - not durable 42 | 43 | examples: [[../src/demo/scheduling.clj][demo/scheduling.clj]] 44 | 45 | *** Parameters 46 | 47 | | :at | java.util.Date, millis since epoch, or a military time string "HHmm" | 48 | | :in | start in millis from now, period alias or period spec | 49 | | :every | delay interval in millis, period alias or period spec | 50 | | :repeat | # of repeats after initial firing; with :every | 51 | | :until | java.util.Date, millis since epoch, or "HHmm"; with :every | 52 | | :cron | a Quartz cron spec, described below | 53 | 54 | *** cron specs 55 | 56 | dash for spans, comma for multiples, division for rates 57 | 58 | | seconds | 0-59 | | 59 | | minutes | 0-59 | | 60 | | hours | 0-23 | | 61 | | dom | 1-31 | ? | 62 | | month | 1-12 or JAN-DEC | | 63 | | dow | 1-7 or SUN-SAT | ? | 64 | | year | 1970-2099 | optional | 65 | 66 | 67 | 68 | 69 | ** immutant.messaging 70 | 71 | - allows publishing and listening to queues/topics using HornetQ 72 | - supports point-to-point, request-response messaging 73 | 74 | examples: [[../src/demo/messaging.clj][demo/messaging.clj]] and [[../src/demo/remote_messaging_client.clj][demo/remote_messaging_client.clj]] 75 | 76 | ** immutant.caching 77 | 78 | - Infinispan transactional data grid 79 | - flexible clustering: replicated, invalidated, distributed 80 | - strong consistency by default, but trades C for A when P 81 | - eviction, expiration, persistence, conditional writes 82 | - implements core.cache/CacheProtocol 83 | - can be used with core.memoize/PluggableMemoization 84 | - can be shared with ruby apps in an app server 85 | - functional alternative: [[https://projectodd.ci.cloudbees.com/job/immutant2-incremental/lastSuccessfulBuild/artifact/target/apidocs/immutant.caching.html#var-swap-in.21][immutant.caching/swap-in!]] 86 | 87 | examples: [[../src/demo/caching.clj][demo/caching.clj]] 88 | -------------------------------------------------------------------------------- /eap-resources/WEB-INF/jboss-web.xml: -------------------------------------------------------------------------------- 1 | 2 | true 3 | 4 | -------------------------------------------------------------------------------- /project.clj: -------------------------------------------------------------------------------- 1 | (defproject demo "0.2.0-SNAPSHOT" 2 | :description "Demo of Immutant 2.x libraries" 3 | :url "http://github.com/immutant/feature-demo" 4 | :license {:name "Eclipse Public License" 5 | :url "http://www.eclipse.org/legal/epl-v10.html"} 6 | :dependencies [[org.clojure/clojure "1.8.0"] 7 | [org.immutant/immutant "2.1.8"] 8 | [compojure "1.4.0"] 9 | [ring/ring-devel "1.3.1"] 10 | [org.clojure/core.memoize "0.5.6"] 11 | [clj-time "0.9.0"] 12 | [cheshire "5.4.0"] 13 | [environ "1.0.0"] 14 | [org.clojure/java.jdbc "0.3.6"] 15 | [com.h2database/h2 "1.3.176"]] 16 | :repositories [["Immutant incremental builds" 17 | "http://downloads.immutant.org/incremental/"]] 18 | :plugins [[lein-immutant "2.1.0"] 19 | [lein-environ "1.0.1"]] 20 | :main demo.core 21 | :uberjar-name "demo-standalone.jar" 22 | :min-lein-version "2.4.0" 23 | :jvm-opts ["-Dhornetq.data.dir=target/hornetq-data" 24 | "-Dcom.arjuna.ats.arjuna.objectstore.objectStoreDir=target/ObjectStore"] 25 | :aliases {"msg-client" ["run" "-m" "demo.remote-messaging-client"]} 26 | :profiles {:uberjar {:aot [demo.core]} 27 | :eap {:exclusions [org.hornetq/hornetq-jms-server org.hornetq/hornetq-server 28 | org.jboss.narayana.jta/narayana-jta] 29 | :dependencies [[org.hornetq/hornetq-jms-server "2.3.25.Final"] 30 | [org.hornetq/hornetq-server "2.3.25.Final"] 31 | [org.jboss.jbossts.jta/narayana-jta "4.17.29.Final"]] 32 | :immutant {:war {:resource-paths ["eap-resources"]}}} 33 | :http2 {:java-agents [[org.mortbay.jetty.alpn/jetty-alpn-agent "2.0.3"]] 34 | :env {:ssl-port 8443, :http2? true}}}) 35 | -------------------------------------------------------------------------------- /resources/jbossts-properties.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 1 5 | target/ObjectStore 6 | 7 | -------------------------------------------------------------------------------- /resources/public/css/style.css: -------------------------------------------------------------------------------- 1 | html { 2 | font-family: Helvetica, Arial, sans-serif; 3 | font-size: 100%; 4 | } 5 | 6 | .opened { 7 | color: green; 8 | } 9 | 10 | .closed { 11 | color: gray; 12 | } 13 | 14 | .error { 15 | color: red; 16 | } 17 | 18 | .received { 19 | color: blue; 20 | } 21 | 22 | .sent { 23 | color: green; 24 | } 25 | 26 | button:hover { 27 | opacity: 0.75; 28 | cursor: pointer; 29 | } 30 | -------------------------------------------------------------------------------- /resources/public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Feature Demo 5 | 6 | 7 | 8 |

Feature Demo

9 | 10 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /resources/public/js/app.js: -------------------------------------------------------------------------------- 1 | 2 | window.onload = function() { 3 | 4 | // Page elements 5 | var input = document.getElementById('input'); 6 | var openBtn = document.getElementById('open'); 7 | var sendBtn = document.getElementById('send'); 8 | var closeBtn = document.getElementById('close'); 9 | var messages = document.getElementById('messages'); 10 | 11 | // Our websocket 12 | var socket; 13 | 14 | function output(style, text){ 15 | messages.innerHTML += "
" + text + ""; 16 | } 17 | 18 | // Open 19 | openBtn.onclick = function(e) { 20 | e.preventDefault(); 21 | if (socket !== undefined) { 22 | output("error", "Already connected"); 23 | return; 24 | } 25 | 26 | var uri = location.protocol.replace(/^http/, "ws") + "//" + location.host + location.pathname; 27 | uri = uri.substring(0, uri.lastIndexOf('/')) + "/reverser"; 28 | socket = new WebSocket(uri); 29 | 30 | socket.onerror = function(error) { 31 | output("error", error); 32 | }; 33 | 34 | socket.onopen = function(event) { 35 | output("opened", "Connected to " + event.currentTarget.url); 36 | }; 37 | 38 | socket.onmessage = function(event) { 39 | var message = event.data; 40 | output("received", "<<< " + message); 41 | }; 42 | 43 | socket.onclose = function(event) { 44 | output("closed", "Disconnected: " + event.code + " " + event.reason); 45 | socket = undefined; 46 | }; 47 | }; 48 | 49 | // Send 50 | sendBtn.onclick = function(e) { 51 | if (socket == undefined) { 52 | output("error", 'Not connected'); 53 | return; 54 | } 55 | var text = document.getElementById("input").value; 56 | socket.send(text); 57 | output("sent", ">>> " + text); 58 | }; 59 | 60 | // Close 61 | closeBtn.onclick = function(e) { 62 | if (socket == undefined) { 63 | output('error', 'Not connected'); 64 | return; 65 | } 66 | socket.close(1000, "Close button clicked"); 67 | }; 68 | 69 | }; 70 | -------------------------------------------------------------------------------- /resources/public/sse.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 21 | 22 |

Server-Sent Events

23 |
24 | 25 |
26 |
27 |
28 | 29 | 30 | -------------------------------------------------------------------------------- /resources/public/websocket.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | WebSocket Demo 5 | 6 | 7 | 8 | 9 | 10 |

WebSocket Demo

11 | 12 |
13 | 14 |
15 | 16 |
17 | 18 | 19 | 20 |
21 | 22 |
23 | 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /resources/server.keystore: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/immutant/feature-demo/151fb330601421a23a1bdfd71f724afcdba0900c/resources/server.keystore -------------------------------------------------------------------------------- /resources/server.truststore: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/immutant/feature-demo/151fb330601421a23a1bdfd71f724afcdba0900c/resources/server.truststore -------------------------------------------------------------------------------- /src/demo/caching.clj: -------------------------------------------------------------------------------- 1 | (ns demo.caching 2 | (:require [immutant.caching :as c] 3 | [immutant.caching.core-memoize :as cmemo] 4 | [immutant.scheduling :as sch])) 5 | 6 | ;; Caches implement org.infinispan.Cache and 7 | ;; java.util.concurrent.ConcurrentMap 8 | 9 | (comment writing 10 | "Various ways of putting entries in a cache" 11 | 12 | (def foo (c/cache "foo")) 13 | 14 | ;; The swap-in! function atomically updates cache entries 15 | ;; by applying a function to the current value or nil, if the key is 16 | ;; missing. The function should be side-effect free. 17 | 18 | (c/swap-in! foo :a (fnil inc 0)) ;=> 1 19 | (c/swap-in! foo :b (constantly "foo")) ;=> "foo" 20 | (c/swap-in! foo :a inc) ;=> 2 21 | 22 | ;; Internally, swap-in! uses the ConcurrentMap methods, 23 | ;; replace, i.e. "compare and set", and putIfAbsent, to provide a 24 | ;; consistent view of the cache to callers. Of course, you can 25 | ;; invoke these and other methods directly using plain ol' Java 26 | ;; interop... 27 | 28 | ;; Put an entry in the cache 29 | (.put foo :a 1) 30 | 31 | ;; Add all the entries in the map to the cache 32 | (.putAll foo {:b 2, :c 3}) 33 | 34 | ;; Put it in only if key is not already present 35 | (.putIfAbsent foo :b 6) ;=> 2 36 | (.putIfAbsent foo :d 4) ;=> nil 37 | 38 | ;; Put it in only if key is already present 39 | (.replace foo :e 5) ;=> nil 40 | (.replace foo :b 6) ;=> 2 41 | 42 | ;; Replace for specific key and value (compare-and-set) 43 | (.replace foo :b 2 0) ;=> false 44 | (.replace foo :b 6 0) ;=> true 45 | ) 46 | 47 | (comment reading 48 | "Caches are just Maps, so core clojure functions work fine" 49 | 50 | (def bar (c/cache "bar")) 51 | (.putAll bar {:a 1, :b {:c 3, :d 4}}) 52 | 53 | ;; Use get to obtain associated values 54 | (get bar :a) ;=> 1 55 | (get bar :x) ;=> nil 56 | (get bar :x 42) ;=> 42 57 | 58 | ;; Keywords look up their value 59 | (:a bar) ;=> 1 60 | (:x bar 42) ;=> 42 61 | 62 | ;; Nested structures work as you would expect 63 | (get-in bar [:b :c]) ;=> 3 64 | 65 | ;; Use find to return entries 66 | (find bar :a) ;=> [:a 1] 67 | 68 | ;; Use contains? to check membership 69 | (contains? bar :a) ;=> true 70 | (contains? bar :x) ;=> false 71 | ) 72 | 73 | (comment removing 74 | "Expiration, eviction, and explicit removal" 75 | 76 | (def baz (c/cache "baz", 77 | :ttl [5 :minutes], :idle [1 :minute] ; expiration 78 | :max-entries 3, :eviction :lru)) ; eviction 79 | (.putAll baz {:a 1 :b 2 :c 3}) 80 | 81 | ;; Eviction 82 | (:a baz) ;=> 1 83 | (select-keys baz [:b :c]) ;=> {:c 3, :b 2} 84 | (.put baz :d 4) 85 | (:a baz) ;=> nil 86 | 87 | ;; You can easily override the cache's expiration settings, 88 | ;; time-to-live and/or max idle time, for all subsequent writes 89 | (let [c (c/with-expiration baz 90 | :ttl [1 :hour] 91 | :idle [20 :minutes])] 92 | (.put c :a 1) 93 | (c/swap-in! c :a dec) 94 | (.putAll c {:b 2, :c 3}) 95 | (.putIfAbsent c :f 6) 96 | (.replace c :f 5)) 97 | 98 | ;; Removing a missing key is harmless 99 | (.remove baz :missing) ;=> nil 100 | 101 | ;; Removing an existing key returns its value 102 | (.remove baz :b) ;=> 2 103 | 104 | ;; If value is passed, both must match for remove to succeed 105 | (.remove baz :c 2) ;=> false 106 | (.remove baz :c 3) ;=> true 107 | 108 | ;; Clear all entries 109 | (.clear baz) 110 | ) 111 | 112 | (comment encoding 113 | "Cache entries are not encoded by default, but may be decorated with 114 | a codec. Provided codecs include :edn, :json, and :fressian. The 115 | latter two require additional dependencies: 'cheshire' and 116 | 'org.clojure/data.fressian', respectively." 117 | (def ham (c/cache "ham")) 118 | (def encoded (c/with-codec ham :edn)) 119 | 120 | (.put encoded :a {:b 42}) 121 | (:a encoded) ;=> {:b 42} 122 | 123 | ;; Access via non-encoded caches still possible 124 | (get ham :a) ;=> nil 125 | (get ham ":a") ;=> "{:b 42}" 126 | 127 | ;; Infinispan caches don't allow null keys or values 128 | (try 129 | (.put ham nil :a) ;=> Null keys are not supported! 130 | (.put ham :b nil) ;=> Null values are not supported! 131 | (catch NullPointerException _ "ERROR!")) 132 | 133 | ;; But nil keys and values are fine in an encoded cache 134 | (.put encoded nil :a) 135 | (.put encoded :b nil) 136 | (get encoded nil) ;=> :a 137 | (:b encoded) ;=> nil 138 | (contains? encoded :b) ;=> true 139 | (contains? ham "nil") ;=> true 140 | ) 141 | 142 | (comment memoization 143 | "Caches will implement clojure.core.memoize/PluggableMemoization 144 | when you require immutant.caching.core-memoize, but it's up to you 145 | to ensure core.memoize is on the classpath" 146 | 147 | (defn slow-fn [& _] 148 | (Thread/sleep 5000) 149 | 42) 150 | 151 | ;; Other than the function to be memoized, arguments are the same as 152 | ;; for the cache function. 153 | (def memoized-fn (cmemo/memo slow-fn "memo", :ttl [5 :minutes])) 154 | 155 | ;; Invoking the memoized function fills the cache with the result 156 | ;; from the slow function the first time it is called. 157 | (memoized-fn 1 2 3) ;=> 42 158 | 159 | ;; Subsequent invocations with the same parameters return the result 160 | ;; from the cache, avoiding the overhead of the slow function 161 | (memoized-fn 1 2 3) ;=> 42 162 | 163 | ;; It's possible to manipulate the cache backing the memoized 164 | ;; function by referring to its name 165 | (def c (c/cache "memo")) 166 | (get c [1 2 3]) ;=> 42 167 | ) 168 | 169 | (defn -main [& args] 170 | "Schedule a counter" 171 | (let [c (c/cache "counter") 172 | f #(println "Updating count to" 173 | (c/swap-in! c :count (fnil inc 0)))] 174 | (sch/schedule f 175 | :id "counter" 176 | :every [10 :seconds] 177 | :singleton false))) 178 | -------------------------------------------------------------------------------- /src/demo/core.clj: -------------------------------------------------------------------------------- 1 | (ns demo.core 2 | (:require demo.web 3 | demo.scheduling 4 | demo.messaging 5 | demo.caching 6 | demo.transactions) 7 | (:gen-class)) 8 | 9 | (defn -main [& args] 10 | (apply demo.web/-main args) 11 | (apply demo.messaging/-main args) 12 | (apply demo.scheduling/-main args) 13 | (apply demo.caching/-main args) 14 | (apply demo.transactions/-main args)) 15 | -------------------------------------------------------------------------------- /src/demo/messaging.clj: -------------------------------------------------------------------------------- 1 | (ns demo.messaging 2 | (:require [immutant.messaging :as msg])) 3 | 4 | (defn listener 5 | "A simple message listener" 6 | [m] 7 | (println "listener received" (pr-str m))) 8 | 9 | (defn -main [& _] 10 | 11 | ;; msg/queue creates a queue in HornetQ if it does not already exist 12 | ;; returns a reference to the queue 13 | (msg/queue "my-queue") 14 | 15 | ;; registers a fn to be called each time a message comes in 16 | (msg/listen (msg/queue "my-queue") listener) 17 | 18 | ;; sends 10 messages to the queue 19 | (dotimes [n 10] 20 | (msg/publish (msg/queue "my-queue") {:message n})) 21 | 22 | ;; default encoding is :edn. Other options are: :edn, :fressian, :json, :none 23 | ;; :json requires cheshire, :fressian requires data.fressian 24 | (msg/publish (msg/queue "my-queue") {:message :hi} :encoding :json) 25 | 26 | ;; using synchronous messaging (request/respond) 27 | (msg/queue "sync-queue") 28 | 29 | ;; registers a fn as a responder - a listener who's return value 30 | ;; is sent to the requester 31 | (msg/respond (msg/queue "sync-queue") inc) 32 | 33 | (dotimes [n 5] 34 | ;; request returns a j.u.c.Future 35 | (println "response is:" 36 | @(msg/request (msg/queue "sync-queue") n))) 37 | ) 38 | -------------------------------------------------------------------------------- /src/demo/remote_messaging_client.clj: -------------------------------------------------------------------------------- 1 | (ns demo.remote-messaging-client 2 | (:require [immutant.messaging :as msg] 3 | [clojure.string :as str] 4 | [immutant.util :as util]) 5 | (:gen-class)) 6 | 7 | (defn -main 8 | "Connects to a 'remote' HornetQ running on localhost:5445 and delivers 9 | the message to the given destination. The first argument is the queue 10 | name, the rest of the arguments are considered the message. Example: 11 | 12 | lein msg-client my-queue hi there friends" 13 | [queue-name & message] 14 | (with-open [context (msg/context :host "localhost" :port (util/messaging-remoting-port))] 15 | (let [queue (msg/queue queue-name :context context) 16 | message (str/join " " message)] 17 | (println (format "Sending '%s' to queue %s" 18 | message queue-name)) 19 | (msg/publish queue message)))) 20 | -------------------------------------------------------------------------------- /src/demo/scheduling.clj: -------------------------------------------------------------------------------- 1 | (ns demo.scheduling 2 | (:require [immutant.scheduling :refer (every at in until limit cron singleton) :as sch] 3 | [immutant.util :as util] 4 | immutant.scheduling.joda 5 | clj-time.core 6 | clj-time.periodic) 7 | (:import java.util.Date)) 8 | 9 | ;; scheduling specs are just maps. we provide optional helpers for 10 | ;; generating thoes maps 11 | (def every-5s 12 | (or 13 | {:every (or 5000 [5 :seconds])} 14 | (every 5 :seconds))) 15 | 16 | ;; :at can be a Date, a time as a string, or millis since epoch 17 | (def daily 18 | (-> (at (or (Date.) "1830" 1395439646983)) 19 | (every :day))) 20 | 21 | ;; helpers optionally take a map as the first arg, so compose 22 | (def in-5m-until-5pm 23 | (-> (in 5 :minutes) 24 | (every 2 :hours, 30 :minutes) 25 | (until "1700"))) 26 | 27 | ;; cron-style strings are also supported 28 | (def nine-am 29 | (cron "0 0 9 * * ?")) 30 | 31 | (def every-5s-cron 32 | (cron "*/5 * * * * ?")) 33 | 34 | (def every-10ms-in-500ms-4-times 35 | (-> (in 500) 36 | (every 10) 37 | (limit 4))) 38 | 39 | ;; you can use clj-time periods if using clj-time 40 | (defn every-3s-lazy-seq [] 41 | (let [at (clj-time.core/plus (clj-time.core/now) (clj-time.core/seconds 1)) 42 | every (clj-time.core/seconds 3)] 43 | (clj-time.periodic/periodic-seq at every))) 44 | 45 | (comment 46 | 47 | ;; scheduling a simple job, using bound-fn to capture *out* for the repl 48 | (def every-2-job 49 | (sch/schedule (bound-fn [] 50 | (println "called")) 51 | (every 2 :seconds))) 52 | 53 | ;; the return value of the schedule call can be used to stop it 54 | (sch/stop every-2-job) 55 | 56 | ;; schedule a job from a clj-time sequence 57 | (def seq-job 58 | (immutant.scheduling.joda/schedule-seq #(println "a sequence") 59 | (every-3s-lazy-seq))) 60 | 61 | (sch/stop seq-job) 62 | 63 | ) 64 | 65 | (defn -main [& _] 66 | 67 | ;; start a couple of jobs, along with a job to stop them in 20 seconds 68 | (let [beep (sch/schedule #(println "beep") every-5s) 69 | ;; schedule a clj-time sequence 70 | boop (immutant.scheduling.joda/schedule-seq #(println "boop") (every-3s-lazy-seq))] 71 | (sch/schedule 72 | (fn [] 73 | (println "unscheduling beep & boop") 74 | (sch/stop beep) 75 | (sch/stop boop)) 76 | (in 20 :seconds))) 77 | 78 | ;; start singleton and non-singleton jobs to demo cluster failover 79 | (when (util/in-container?) 80 | 81 | ;; singleton jobs require an id 82 | (sch/schedule #(println "I run on ONE node") 83 | (-> (singleton :a-unique-id-for-the-singleton) 84 | (every 10 :seconds))) 85 | 86 | (sch/schedule #(println "I run on EVERY node") 87 | (every 9 :seconds)))) 88 | -------------------------------------------------------------------------------- /src/demo/transactions.clj: -------------------------------------------------------------------------------- 1 | (ns demo.transactions 2 | (:require [immutant.transactions.scope :as tx] 3 | [immutant.messaging :as msg] 4 | [immutant.caching :as csh] 5 | [clojure.java.jdbc :as sql])) 6 | 7 | (def cache (delay (csh/cache (str *ns*) :transactional? true))) 8 | (def queue (delay (msg/queue (str *ns*)))) 9 | (def db {:connection-uri "jdbc:h2:mem:demo;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE"}) 10 | 11 | (defn unit-of-work [m] 12 | (tx/not-supported 13 | (csh/swap-in! @cache :attempts (fnil inc 0))) 14 | (csh/swap-in! @cache :count (fnil inc 0)) 15 | (msg/publish @queue m) 16 | (sql/insert! db :things m)) 17 | 18 | (defn dump [] 19 | (println "tx:queue =>" (msg/receive @queue :timeout -1)) 20 | (println "tx:cache =>" (into {} @cache)) 21 | (println "tx:db =>" (sql/query db ["select * from things"]))) 22 | 23 | (defn -main [& _] 24 | (sql/db-do-commands db 25 | (sql/create-table-ddl :things [:name "varchar(50)"])) 26 | 27 | (tx/required (unit-of-work {:name "t-swizzle"})) 28 | (dump) 29 | 30 | (try 31 | (tx/required (unit-of-work {:kanye "this should fail"})) 32 | (catch Throwable e (println e))) 33 | (dump)) 34 | -------------------------------------------------------------------------------- /src/demo/web.clj: -------------------------------------------------------------------------------- 1 | (ns demo.web 2 | (:require [immutant.web :as web] 3 | [immutant.web.async :as async] 4 | [immutant.web.middleware :as mw] 5 | [clojure.java.io :as io] 6 | [demo.web.sse :as sse] 7 | [demo.web.http-kit-comparison :as hk] 8 | [compojure.route :as route] 9 | [compojure.core :refer (ANY GET defroutes)] 10 | [ring.util.response :refer (response redirect content-type)] 11 | [clojure.pprint :refer (pprint)] 12 | [environ.core :refer (env)])) 13 | 14 | (defn echo 15 | "Echos the request back as a string." 16 | [request] 17 | (-> (response (with-out-str (pprint request))) 18 | (content-type "text/plain"))) 19 | 20 | (defn counter 21 | "An example manipulating session state from 22 | https://github.com/ring-clojure/ring/wiki/Sessions" 23 | [{session :session}] 24 | (let [count (:count session 0) 25 | session (assoc session :count (inc count))] 26 | (println "counter =>" count) 27 | (-> (response (str "You accessed this page " count " times\n")) 28 | (assoc :session session)))) 29 | 30 | (defn reverser 31 | "An example WebSocket app" 32 | [request] 33 | (async/as-channel request 34 | {:on-open (fn [channel] 35 | (async/send! channel "Ready to reverse your messages!")) 36 | :on-message (fn [channel m] 37 | (async/send! channel (apply str (reverse m)))) 38 | :on-close (fn [channel {:keys [code reason]}] 39 | (println "close code:" code "reason:" reason))})) 40 | 41 | 42 | (defroutes routes 43 | (GET "/" {c :context} (redirect (str c "/index.html"))) 44 | (GET "/counter" [] counter) 45 | (GET "/reverser" [] reverser) 46 | (GET "/sse" [] sse/countdown) 47 | (GET "/http-kit" [] hk/async-handler) 48 | (route/resources "/") 49 | (ANY "*" [] echo)) 50 | 51 | (defn -main [& {:as args}] 52 | (web/run 53 | (-> routes 54 | (immutant.web.middleware/wrap-session 55 | {:timeout 20})) 56 | (merge 57 | {"host" (env :demo-web-host) 58 | "port" (env :demo-web-port 8080) 59 | "ssl-port" (env :ssl-port) 60 | "http2?" (env :http2?) 61 | :keystore (io/resource "server.keystore") 62 | :key-password "password" 63 | :truststore (io/resource "server.truststore") 64 | :trust-password "password"} 65 | args))) 66 | -------------------------------------------------------------------------------- /src/demo/web/http_kit_comparison.clj: -------------------------------------------------------------------------------- 1 | (ns demo.web.http-kit-comparison 2 | "Show API differences between Immutant and HTTP Kit" 3 | (:require [immutant.web :as web] 4 | [immutant.web.async :as async])) 5 | 6 | #_(defn async-handler 7 | "For comparison, the actual http-kit example" 8 | [ring-request] 9 | ;; unified API for WebSocket and HTTP long polling/streaming 10 | (with-channel ring-request channel ; get the channel 11 | (if (websocket? channel) ; if you want to distinguish them 12 | (on-receive channel (fn [data] ; two way communication 13 | (send! channel data))) 14 | (send! channel {:status 200 15 | :headers {"Content-Type" "text/plain"} 16 | :body "Long polling?"})))) 17 | 18 | (defn async-handler 19 | "Immutant version of http-kit example showing websocket degrade 20 | 21 | Differences: 22 | - Channel passed as callback param instead of macro param 23 | - send! provides :on-success and :on-error callbacks 24 | - Channel not closed after send, by default 25 | - All ring body types supported 26 | - Automatic chunking of large (>16K) content" 27 | [ring-request] 28 | (async/as-channel ring-request 29 | {:on-message (fn [channel data] 30 | (async/send! channel data)) 31 | :on-open (fn [channel] 32 | (when-not (:websocket? ring-request) 33 | (async/send! channel {:status 200 34 | :headers {"Content-Type" "text/plain"} 35 | :body "Long polling?"} 36 | :close? true)))})) 37 | 38 | -------------------------------------------------------------------------------- /src/demo/web/sse.clj: -------------------------------------------------------------------------------- 1 | (ns demo.web.sse 2 | "Demonstrate Server Sent Events" 3 | (:require [immutant.web.sse :as sse])) 4 | 5 | (defn countdown 6 | "Countdown from 5 every half-second" 7 | [request] 8 | (sse/as-channel request 9 | {:on-open (fn [ch] 10 | (doseq [x (range 5 0 -1)] 11 | (sse/send! ch x) 12 | (Thread/sleep 500)) 13 | ;; Signal the client to call EventSource.close(), and 14 | ;; close our end after the send 15 | (sse/send! ch 16 | {:event "close", :data "bye!"} 17 | :close? true))})) 18 | 19 | --------------------------------------------------------------------------------