forked from playframework/play-samples
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge remote-tracking branch 'play-java-websocket-example/2.6.x' into…
… 2.6.x * play-java-websocket-example/2.6.x: (83 commits) Nest play-java-websocket-example Updated with template-control on 2019-02-13T20:25:39.721Z (playframework#100) Upgrade branch 2.6.x using TemplateControl (playframework#96) Upgrade branch 2.6.x using TemplateControl (playframework#94) Upgrade branch 2.6.x using TemplateControl (playframework#93) Updated with template-control on 2019-01-08T14:44:42.192Z (playframework#90) Updated with template-control on 2019-01-04T17:13:23.935Z (playframework#85) Upgrade branch 2.6.x using TemplateControl (playframework#84) Upgrade branch 2.6.x using TemplateControl (playframework#81) Updated with template-control on 2018-09-11T20:14:50.523Z (playframework#79) Updated with template-control on 2018-08-20T20:37:13.896Z (playframework#78) Updated with template-control on 2018-07-19T01:58:55.842Z (playframework#76) Updated with template-control on 2018-07-16T18:38:45.656Z (playframework#75) Upgrade branch 2.6.x using TemplateControl (playframework#74) Updated with template-control on 2018-05-27T23:54:09.712Z (playframework#73) Updated with template-control on 2018-04-06T19:34:58.514Z (playframework#71) Updated with template-control on 2018-03-02T18:56:28.527Z (playframework#70) Upgrade branch 2.6.x using TemplateControl (playframework#69) Fix cross build to sbt 1.1.0 (playframework#68) Upgrade branch 2.6.x using TemplateControl (playframework#67) ...
- Loading branch information
Showing
42 changed files
with
1,858 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,10 @@ | ||
logs | ||
target | ||
build | ||
/.idea | ||
/.idea_modules | ||
/.classpath | ||
/.project | ||
/.gradle | ||
/.settings | ||
/RUNNING_PID |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,27 @@ | ||
pull_request_rules: | ||
- name: automatic merge on CI success require review | ||
conditions: | ||
- status-success=Travis CI - Pull Request | ||
- "#approved-reviews-by>=1" | ||
- "#changes-requested-reviews-by=0" | ||
- label!=block-merge | ||
actions: | ||
merge: | ||
method: squash | ||
strict: smart | ||
|
||
- name: automatic merge on CI success for TemplateControl | ||
conditions: | ||
- status-success=Travis CI - Pull Request | ||
- label=merge-when-green | ||
- label!=block-merge | ||
actions: | ||
merge: | ||
method: squash | ||
strict: smart | ||
|
||
- name: delete branch after merge | ||
conditions: | ||
- merged | ||
actions: | ||
delete_head_branch: {} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,50 @@ | ||
language: scala | ||
scala: | ||
- 2.12.8 | ||
|
||
before_install: | ||
- curl -sL https://github.com/shyiko/jabba/raw/master/install.sh | bash && . ~/.jabba/jabba.sh | ||
|
||
env: | ||
global: | ||
- JABBA_HOME=$HOME/.jabba | ||
matrix: | ||
# There is no concise way to specify multi-dimensional build matrix: | ||
# https://github.com/travis-ci/travis-ci/issues/1519 | ||
- SCRIPT=scripts/test-sbt [email protected] | ||
- SCRIPT=scripts/test-sbt [email protected] | ||
- SCRIPT=scripts/test-gradle [email protected] | ||
- SCRIPT=scripts/test-gradle [email protected] | ||
|
||
# Exclude some combinations from build matrix. See: | ||
# https://docs.travis-ci.com/user/customizing-the-build/#Build-Matrix | ||
matrix: | ||
fast_finish: true | ||
allow_failures: | ||
# Current release of Gradle still does not supports Play 2.7.x releases | ||
# As soon as there is a release of Gradle that fixes that, we can then | ||
# remove this allowed failure. | ||
- env: SCRIPT=scripts/test-gradle [email protected] | ||
- env: SCRIPT=scripts/test-gradle [email protected] | ||
# Java 11 is still not fully supported. It is good that we are already | ||
# testing our sample applications to better discover possible problems | ||
# but we can allow failures here too. | ||
- env: SCRIPT=scripts/test-sbt [email protected] | ||
|
||
install: | ||
- $JABBA_HOME/bin/jabba install $TRAVIS_JDK | ||
- unset _JAVA_OPTIONS | ||
- export JAVA_HOME="$JABBA_HOME/jdk/$TRAVIS_JDK" && export PATH="$JAVA_HOME/bin:$PATH" && java -Xmx32m -version | ||
|
||
script: | ||
- $SCRIPT | ||
|
||
before_cache: | ||
- find $HOME/.ivy2 -name "ivydata-*.properties" -delete | ||
- find $HOME/.sbt -name "*.lock" -delete | ||
|
||
cache: | ||
directories: | ||
- "$HOME/.ivy2/cache" | ||
- "$HOME/.gradle/caches" | ||
- "$HOME/.jabba/jdk" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,116 @@ | ||
CC0 1.0 Universal | ||
|
||
Statement of Purpose | ||
|
||
The laws of most jurisdictions throughout the world automatically confer | ||
exclusive Copyright and Related Rights (defined below) upon the creator and | ||
subsequent owner(s) (each and all, an "owner") of an original work of | ||
authorship and/or a database (each, a "Work"). | ||
|
||
Certain owners wish to permanently relinquish those rights to a Work for the | ||
purpose of contributing to a commons of creative, cultural and scientific | ||
works ("Commons") that the public can reliably and without fear of later | ||
claims of infringement build upon, modify, incorporate in other works, reuse | ||
and redistribute as freely as possible in any form whatsoever and for any | ||
purposes, including without limitation commercial purposes. These owners may | ||
contribute to the Commons to promote the ideal of a free culture and the | ||
further production of creative, cultural and scientific works, or to gain | ||
reputation or greater distribution for their Work in part through the use and | ||
efforts of others. | ||
|
||
For these and/or other purposes and motivations, and without any expectation | ||
of additional consideration or compensation, the person associating CC0 with a | ||
Work (the "Affirmer"), to the extent that he or she is an owner of Copyright | ||
and Related Rights in the Work, voluntarily elects to apply CC0 to the Work | ||
and publicly distribute the Work under its terms, with knowledge of his or her | ||
Copyright and Related Rights in the Work and the meaning and intended legal | ||
effect of CC0 on those rights. | ||
|
||
1. Copyright and Related Rights. A Work made available under CC0 may be | ||
protected by copyright and related or neighboring rights ("Copyright and | ||
Related Rights"). Copyright and Related Rights include, but are not limited | ||
to, the following: | ||
|
||
i. the right to reproduce, adapt, distribute, perform, display, communicate, | ||
and translate a Work; | ||
|
||
ii. moral rights retained by the original author(s) and/or performer(s); | ||
|
||
iii. publicity and privacy rights pertaining to a person's image or likeness | ||
depicted in a Work; | ||
|
||
iv. rights protecting against unfair competition in regards to a Work, | ||
subject to the limitations in paragraph 4(a), below; | ||
|
||
v. rights protecting the extraction, dissemination, use and reuse of data in | ||
a Work; | ||
|
||
vi. database rights (such as those arising under Directive 96/9/EC of the | ||
European Parliament and of the Council of 11 March 1996 on the legal | ||
protection of databases, and under any national implementation thereof, | ||
including any amended or successor version of such directive); and | ||
|
||
vii. other similar, equivalent or corresponding rights throughout the world | ||
based on applicable law or treaty, and any national implementations thereof. | ||
|
||
2. Waiver. To the greatest extent permitted by, but not in contravention of, | ||
applicable law, Affirmer hereby overtly, fully, permanently, irrevocably and | ||
unconditionally waives, abandons, and surrenders all of Affirmer's Copyright | ||
and Related Rights and associated claims and causes of action, whether now | ||
known or unknown (including existing as well as future claims and causes of | ||
action), in the Work (i) in all territories worldwide, (ii) for the maximum | ||
duration provided by applicable law or treaty (including future time | ||
extensions), (iii) in any current or future medium and for any number of | ||
copies, and (iv) for any purpose whatsoever, including without limitation | ||
commercial, advertising or promotional purposes (the "Waiver"). Affirmer makes | ||
the Waiver for the benefit of each member of the public at large and to the | ||
detriment of Affirmer's heirs and successors, fully intending that such Waiver | ||
shall not be subject to revocation, rescission, cancellation, termination, or | ||
any other legal or equitable action to disrupt the quiet enjoyment of the Work | ||
by the public as contemplated by Affirmer's express Statement of Purpose. | ||
|
||
3. Public License Fallback. Should any part of the Waiver for any reason be | ||
judged legally invalid or ineffective under applicable law, then the Waiver | ||
shall be preserved to the maximum extent permitted taking into account | ||
Affirmer's express Statement of Purpose. In addition, to the extent the Waiver | ||
is so judged Affirmer hereby grants to each affected person a royalty-free, | ||
non transferable, non sublicensable, non exclusive, irrevocable and | ||
unconditional license to exercise Affirmer's Copyright and Related Rights in | ||
the Work (i) in all territories worldwide, (ii) for the maximum duration | ||
provided by applicable law or treaty (including future time extensions), (iii) | ||
in any current or future medium and for any number of copies, and (iv) for any | ||
purpose whatsoever, including without limitation commercial, advertising or | ||
promotional purposes (the "License"). The License shall be deemed effective as | ||
of the date CC0 was applied by Affirmer to the Work. Should any part of the | ||
License for any reason be judged legally invalid or ineffective under | ||
applicable law, such partial invalidity or ineffectiveness shall not | ||
invalidate the remainder of the License, and in such case Affirmer hereby | ||
affirms that he or she will not (i) exercise any of his or her remaining | ||
Copyright and Related Rights in the Work or (ii) assert any associated claims | ||
and causes of action with respect to the Work, in either case contrary to | ||
Affirmer's express Statement of Purpose. | ||
|
||
4. Limitations and Disclaimers. | ||
|
||
a. No trademark or patent rights held by Affirmer are waived, abandoned, | ||
surrendered, licensed or otherwise affected by this document. | ||
|
||
b. Affirmer offers the Work as-is and makes no representations or warranties | ||
of any kind concerning the Work, express, implied, statutory or otherwise, | ||
including without limitation warranties of title, merchantability, fitness | ||
for a particular purpose, non infringement, or the absence of latent or | ||
other defects, accuracy, or the present or absence of errors, whether or not | ||
discoverable, all to the greatest extent permissible under applicable law. | ||
|
||
c. Affirmer disclaims responsibility for clearing rights of other persons | ||
that may apply to the Work or any use thereof, including without limitation | ||
any person's Copyright and Related Rights in the Work. Further, Affirmer | ||
disclaims responsibility for obtaining any necessary consents, permissions | ||
or other rights required for any use of the Work. | ||
|
||
d. Affirmer understands and acknowledges that Creative Commons is not a | ||
party to this document and has no duty or obligation with respect to this | ||
CC0 or use of the Work. | ||
|
||
For more information, please see | ||
<http://creativecommons.org/publicdomain/zero/1.0/> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,8 @@ | ||
Written by Lightbend <[email protected]> | ||
|
||
To the extent possible under law, the author(s) have dedicated all copyright and | ||
related and neighboring rights to this software to the public domain worldwide. | ||
This software is distributed without any warranty. | ||
|
||
You should have received a copy of the CC0 Public Domain Dedication along with | ||
this software. If not, see <http://creativecommons.org/publicdomain/zero/1.0/>. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,85 @@ | ||
# play-websocket-java-example | ||
|
||
[](https://travis-ci.org/playframework/play-java-websocket-example) [](https://github.com/playframework/play-websocket-java/issues) [](https://github.com/playframework/play-websocket-java/network) [](https://github.com/playframework/play-websocket-java/stargazers) | ||
|
||
This is an example Play application that shows how to use Play's Websocket API in Java, by showing a series of stock tickers updated using WebSocket. | ||
|
||
The Websocket API is built on Akka Streams, and so is async, non-blocking, and backpressure aware. Using Akka Streams also means that interacting with Akka Actors is simple. | ||
|
||
There are also tests showing how Junit and Akka Testkit are used to test actors and flows. | ||
|
||
## Reactive Push | ||
|
||
This application uses a WebSocket to push data to the browser in real-time. To create a WebSocket connection in Play, first a route must be defined in the `routes` file. Here is the route which will be used to setup the WebSocket connection: | ||
|
||
```routes | ||
GET /ws controllers.Application.ws | ||
``` | ||
|
||
The `ws` method in the HomeController.java controller handles the request and does the protocol upgrade to the WebSocket connection. The `UserActor` stores the handle to the WebSocket connection. | ||
|
||
Once the `UserActor` is created, the default stocks (defined in `application.conf`) are added to the user's list of watched stocks. | ||
|
||
Each stock symbol has its own `StockActor` defined in StockActor.java. This actor holds the last 50 prices for the stock. Using a `FetchHistory` message the whole history can be retrieved. A `FetchLatest` message will generate a new price. Every `StockActor` sends itself a `FetchLatest` message every 75 milliseconds. Once a new price is generated it is added to the history and then a message is sent to each `UserActor` that is watching the stock. The `UserActor` then serializes the data as JSON and pushes it to the client using the WebSocket. | ||
|
||
Underneath the covers, resources (threads) are only allocated to the Actors and WebSockets when they are needed. This is why Reactive Push is scalable with Play and Akka. | ||
|
||
## Reactive UI - Real-time Chart | ||
|
||
On the client-side, a Reactive UI updates the stock charts every time a message is received. The `index.scala.html` file produces the web page at <http://localhost:9000> and loads the JavaScript and CSS needed render the page and setup the UI. | ||
|
||
The JavaScript for the page is compiled from the index.coffee file which is written in CoffeeScript (an elegant way to write JavaScript). Using jQuery, a page ready handler sets up the WebSocket connection and sets up functions which will be called when the server sends a message to the client through the WebSocket: | ||
|
||
```coffee | ||
$ -> | ||
ws = new WebSocket $("body").data("ws-url") | ||
ws.onmessage = (event) -> | ||
message = JSON.parse event.data | ||
``` | ||
|
||
The message is parsed and depending on whether the message contains the stock history or a stock update, a stock chart is either created or updated. The charts are created using the **Flot** JavaScript charting library. Using CoffeeScript, jQuery, and Flot makes it easy to build Reactive UI in the browser that can receive WebSocket push events and update the UI in real-time. | ||
|
||
## Reactive Requests | ||
|
||
When a web server gets a request, it allocates a thread to handle the request and produce a response. In a typical model the thread is allocated for the entire duration of the request and response, even if the web request is waiting for some other resource. A Reactive Request is a typical web request and response, but handled in an asynchronous and non-blocking way on the server. This means that when the thread for a web request is not actively being used, it can be released and reused for something else. | ||
|
||
In the Reactive Stocks application the service which determines the stock sentiments is a Reactive Request. The route is defined in the `routes` file: | ||
|
||
```routes | ||
GET /sentiment/:symbol controllers.StockSentiment.get(symbol) | ||
``` | ||
|
||
A `GET` request to `/sentiment/GOOG` will call `get("GOOG")` on the StockSentiment.java controller. That method begins with: | ||
|
||
```scala | ||
def get(symbol: String): Action[AnyContent] = Action.async { | ||
``` | ||
|
||
The `async` block indicates that the controller will return a `Future[Result]` which is a handle to something that will produce a `Result` in the future. The `Future` provides a way to do asynchronous handling but doesn't necessarily have to be non-blocking. Often times web requests need to talk to other systems (databases, web services, etc). If a thread can't be deallocated while waiting for those other systems to respond, then it is blocking. | ||
|
||
In this case a request is made to Twitter and then for each tweet, another request is made to a sentiment service. All of these requests, including the request from the browser, are all handled as Reactive Requests so that the entire pipeline is Reactive (asynchronous and non-blocking). This is called Reactive Composition. | ||
|
||
## Reactive Composition | ||
|
||
Combining multiple Reactive Requests together is Reactive Composition. The StockSentiment controller does Reactive Composition since it receives a request, makes a request to Twitter for tweets about a stock, and then for each tweet it makes a request to a sentiment service. All of these requests are Reactive Requests. None use threads when they are waiting for a response. Scala's **for comprehensions** make it very easy and elegant to do Reactive Composition. The basic structure is: | ||
|
||
```scala | ||
for { | ||
tweets <- tweetsFuture | ||
sentiments <- Future.sequence(futuresForTweetSentiment(tweets)) | ||
} yield Ok(sentiments) | ||
``` | ||
|
||
Because the web client library in Play, `WS`, is asynchronous and non-blocking, all of the requests needed to get a stock's sentiments are Reactive Requests. Combined together these Reactive Requests are Reactive Composition. | ||
|
||
## Reactive UI - Sentiments | ||
|
||
The client-side of Reactive Requests and Reactive Composition is no different than the non-Reactive model. The browser makes an Ajax request to the server and then calls a JavaScript function when it receives a response. In the Reactive Stocks application, when a stock chart is flipped over it makes the request for the stock's sentiments. That is done using jQuery's `ajax` method in the index.coffee file. When the request returns data the `success` handler updates the UI. | ||
|
||
## Further Learning | ||
|
||
For more information, please see the documentation for Websockets and Akka Streams: | ||
|
||
* <https://www.playframework.com/documentation/latest/JavaWebSockets> | ||
* <http://doc.akka.io/docs/akka/current/java/stream/stream-flows-and-basics.html#stream-materialization> | ||
* <http://doc.akka.io/docs/akka/current/java/stream/stream-integrations.html#integrating-with-actors> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,13 @@ | ||
import actors.*; | ||
import com.google.inject.AbstractModule; | ||
import play.libs.akka.AkkaGuiceSupport; | ||
|
||
@SuppressWarnings("unused") | ||
public class Module extends AbstractModule implements AkkaGuiceSupport { | ||
@Override | ||
protected void configure() { | ||
bindActor(StocksActor.class, "stocksActor"); | ||
bindActor(UserParentActor.class, "userParentActor"); | ||
bindActorFactory(UserActor.class, UserActor.Factory.class); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,45 @@ | ||
package actors; | ||
|
||
import stocks.Stock; | ||
|
||
import java.util.Set; | ||
|
||
import static java.util.Objects.requireNonNull; | ||
|
||
public final class Messages { | ||
|
||
public static final class WatchStocks { | ||
final Set<String> symbols; | ||
|
||
public WatchStocks(Set<String> symbols) { | ||
this.symbols = requireNonNull(symbols); | ||
} | ||
|
||
@Override | ||
public String toString() { | ||
return "WatchStocks(" + symbols.toString() + ")"; | ||
} | ||
} | ||
|
||
public static final class UnwatchStocks { | ||
final Set<String> symbols; | ||
|
||
public UnwatchStocks(Set<String> symbols) { | ||
this.symbols = requireNonNull(symbols); | ||
} | ||
|
||
@Override | ||
public String toString() { | ||
return "UnwatchStocks(" + symbols.toString() + ")"; | ||
} | ||
} | ||
|
||
public static class Stocks { | ||
final Set<Stock> stocks; | ||
|
||
public Stocks(Set<Stock> stocks) { | ||
this.stocks = requireNonNull(stocks); | ||
} | ||
} | ||
} | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,34 @@ | ||
package actors; | ||
|
||
import akka.actor.AbstractActor; | ||
import akka.event.Logging; | ||
import akka.event.LoggingAdapter; | ||
import stocks.Stock; | ||
|
||
import java.util.HashMap; | ||
import java.util.Map; | ||
import java.util.Set; | ||
import java.util.stream.Collector; | ||
import java.util.stream.Collectors; | ||
|
||
/** | ||
* This actor contains a set of stocks internally that may be used by | ||
* all websocket clients. | ||
*/ | ||
public class StocksActor extends AbstractActor { | ||
|
||
private final Map<String, Stock> stocksMap = new HashMap<>(); | ||
|
||
private final LoggingAdapter log = Logging.getLogger(getContext().system(), this); | ||
|
||
@Override | ||
public Receive createReceive() { | ||
return receiveBuilder() | ||
.match(Messages.WatchStocks.class, watchStocks -> { | ||
Set<Stock> stocks = watchStocks.symbols.stream() | ||
.map(symbol -> stocksMap.compute(symbol, (k, v) -> new Stock(k))) | ||
.collect(Collectors.toSet()); | ||
sender().tell(new Messages.Stocks(stocks), self()); | ||
}).build(); | ||
} | ||
} |
Oops, something went wrong.