diff --git a/play-java-websocket-example/.gitignore b/play-java-websocket-example/.gitignore
new file mode 100644
index 000000000..07f0e59c0
--- /dev/null
+++ b/play-java-websocket-example/.gitignore
@@ -0,0 +1,10 @@
+logs
+target
+build
+/.idea
+/.idea_modules
+/.classpath
+/.project
+/.gradle
+/.settings
+/RUNNING_PID
diff --git a/play-java-websocket-example/.mergify.yml b/play-java-websocket-example/.mergify.yml
new file mode 100644
index 000000000..32f8689ae
--- /dev/null
+++ b/play-java-websocket-example/.mergify.yml
@@ -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: {}
diff --git a/play-java-websocket-example/.travis.yml b/play-java-websocket-example/.travis.yml
new file mode 100644
index 000000000..1e8c0e7c4
--- /dev/null
+++ b/play-java-websocket-example/.travis.yml
@@ -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 TRAVIS_JDK=adopt@1.8.192-12
+ - SCRIPT=scripts/test-sbt TRAVIS_JDK=adopt@1.11.0-1
+ - SCRIPT=scripts/test-gradle TRAVIS_JDK=adopt@1.8.192-12
+ - SCRIPT=scripts/test-gradle TRAVIS_JDK=adopt@1.11.0-1
+
+# 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 TRAVIS_JDK=adopt@1.8.192-12
+ - env: SCRIPT=scripts/test-gradle TRAVIS_JDK=adopt@1.11.0-1
+ # 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 TRAVIS_JDK=adopt@1.11.0-1
+
+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"
diff --git a/play-java-websocket-example/LICENSE b/play-java-websocket-example/LICENSE
new file mode 100644
index 000000000..670154e35
--- /dev/null
+++ b/play-java-websocket-example/LICENSE
@@ -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
+
diff --git a/play-java-websocket-example/NOTICE b/play-java-websocket-example/NOTICE
new file mode 100644
index 000000000..6d6c034d3
--- /dev/null
+++ b/play-java-websocket-example/NOTICE
@@ -0,0 +1,8 @@
+Written by Lightbend
+
+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 .
diff --git a/play-java-websocket-example/README.md b/play-java-websocket-example/README.md
new file mode 100644
index 000000000..614de6b1d
--- /dev/null
+++ b/play-java-websocket-example/README.md
@@ -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 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:
+
+*
+*
+*
diff --git a/play-java-websocket-example/app/Module.java b/play-java-websocket-example/app/Module.java
new file mode 100644
index 000000000..348fef887
--- /dev/null
+++ b/play-java-websocket-example/app/Module.java
@@ -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);
+ }
+}
diff --git a/play-java-websocket-example/app/actors/Messages.java b/play-java-websocket-example/app/actors/Messages.java
new file mode 100644
index 000000000..fed81f212
--- /dev/null
+++ b/play-java-websocket-example/app/actors/Messages.java
@@ -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 symbols;
+
+ public WatchStocks(Set symbols) {
+ this.symbols = requireNonNull(symbols);
+ }
+
+ @Override
+ public String toString() {
+ return "WatchStocks(" + symbols.toString() + ")";
+ }
+ }
+
+ public static final class UnwatchStocks {
+ final Set symbols;
+
+ public UnwatchStocks(Set symbols) {
+ this.symbols = requireNonNull(symbols);
+ }
+
+ @Override
+ public String toString() {
+ return "UnwatchStocks(" + symbols.toString() + ")";
+ }
+ }
+
+ public static class Stocks {
+ final Set stocks;
+
+ public Stocks(Set stocks) {
+ this.stocks = requireNonNull(stocks);
+ }
+ }
+}
+
diff --git a/play-java-websocket-example/app/actors/StocksActor.java b/play-java-websocket-example/app/actors/StocksActor.java
new file mode 100644
index 000000000..d936bc40a
--- /dev/null
+++ b/play-java-websocket-example/app/actors/StocksActor.java
@@ -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 stocksMap = new HashMap<>();
+
+ private final LoggingAdapter log = Logging.getLogger(getContext().system(), this);
+
+ @Override
+ public Receive createReceive() {
+ return receiveBuilder()
+ .match(Messages.WatchStocks.class, watchStocks -> {
+ Set 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();
+ }
+}
diff --git a/play-java-websocket-example/app/actors/UserActor.java b/play-java-websocket-example/app/actors/UserActor.java
new file mode 100644
index 000000000..6e24d8461
--- /dev/null
+++ b/play-java-websocket-example/app/actors/UserActor.java
@@ -0,0 +1,166 @@
+package actors;
+
+import actors.Messages.Stocks;
+import actors.Messages.UnwatchStocks;
+import actors.Messages.WatchStocks;
+import akka.Done;
+import akka.NotUsed;
+import akka.actor.AbstractActor;
+import akka.actor.Actor;
+import akka.actor.ActorRef;
+import akka.event.Logging;
+import akka.event.LoggingAdapter;
+import akka.japi.Pair;
+import akka.stream.KillSwitches;
+import akka.stream.Materializer;
+import akka.stream.UniqueKillSwitch;
+import akka.stream.javadsl.*;
+import akka.util.Timeout;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.google.inject.assistedinject.Assisted;
+import play.libs.Json;
+import scala.concurrent.duration.Duration;
+import stocks.Stock;
+
+import javax.inject.Inject;
+import javax.inject.Named;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.CompletionStage;
+import java.util.concurrent.TimeUnit;
+
+import static akka.pattern.PatternsCS.ask;
+
+/**
+ * The broker between the WebSocket and the StockActor(s). The UserActor holds the connection and sends serialized
+ * JSON data to the client.
+ */
+public class UserActor extends AbstractActor {
+
+ private final Timeout timeout = new Timeout(Duration.create(5, TimeUnit.SECONDS));
+
+ private final LoggingAdapter logger = Logging.getLogger(getContext().system(), this);
+
+ private final Map stocksMap = new HashMap<>();
+
+ private final String id;
+ private final ActorRef stocksActor;
+ private final Materializer mat;
+
+ private final Sink hubSink;
+ private final Flow websocketFlow;
+
+ @Inject
+ public UserActor(@Assisted String id,
+ @Named("stocksActor") ActorRef stocksActor,
+ Materializer mat) {
+ this.id = id;
+ this.stocksActor = stocksActor;
+ this.mat = mat;
+
+ Pair, Source> sinkSourcePair =
+ MergeHub.of(JsonNode.class, 16)
+ .toMat(BroadcastHub.of(JsonNode.class, 256), Keep.both())
+ .run(mat);
+
+ this.hubSink = sinkSourcePair.first();
+ Source hubSource = sinkSourcePair.second();
+
+ Sink> jsonSink = Sink.foreach((JsonNode json) -> {
+ // When the user types in a stock in the upper right corner, this is triggered,
+ String symbol = json.findPath("symbol").asText();
+ addStocks(Collections.singleton(symbol));
+ });
+
+ // Put the source and sink together to make a flow of hub source as output (aggregating all
+ // stocks as JSON to the browser) and the actor as the sink (receiving any JSON messages
+ // from the browse), using a coupled sink and source.
+ this.websocketFlow = Flow.fromSinkAndSourceCoupled(jsonSink, hubSource)
+ //.log("actorWebsocketFlow", logger)
+ .watchTermination((n, stage) -> {
+ // When the flow shuts down, make sure this actor also stops.
+ stage.thenAccept(f -> context().stop(self()));
+ return NotUsed.getInstance();
+ });
+ }
+
+ /**
+ * The receive block, useful if other actors want to manipulate the flow.
+ */
+ @Override
+ public Receive createReceive() {
+ return receiveBuilder()
+ .match(WatchStocks.class, watchStocks -> {
+ logger.info("Received message {}", watchStocks);
+ addStocks(watchStocks.symbols);
+ sender().tell(websocketFlow, self());
+ })
+ .match(UnwatchStocks.class, unwatchStocks -> {
+ logger.info("Received message {}", unwatchStocks);
+ unwatchStocks(unwatchStocks.symbols);
+ }).build();
+ }
+
+ /**
+ * Adds several stocks to the hub, by asking the stocks actor for stocks.
+ */
+ private void addStocks(Set symbols) {
+ // Ask the stocksActor for a stream containing these stocks.
+ CompletionStage future = ask(stocksActor, new WatchStocks(symbols), timeout).thenApply(Stocks.class::cast);
+
+ // when we get the response back, we want to turn that into a flow by creating a single
+ // source and a single sink, so we merge all of the stock sources together into one by
+ // pointing them to the hubSink, so we can add them dynamically even after the flow
+ // has started.
+ future.thenAccept((Stocks newStocks) -> {
+ newStocks.stocks.forEach(stock -> {
+ if (!stocksMap.containsKey(stock.symbol)) {
+ addStock(stock);
+ }
+ });
+ });
+ }
+
+ /**
+ * Adds a single stock to the hub.
+ */
+ private void addStock(Stock stock) {
+ logger.info("Adding stock {}", stock);
+
+ // We convert everything to JsValue so we get a single stream for the websocket.
+ // Make sure the history gets written out before the updates for this stock...
+ final Source historySource = stock.history(50).map(Json::toJson);
+ final Source updateSource = stock.update().map(Json::toJson);
+ final Source stockSource = historySource.concat(updateSource);
+
+ // Set up a flow that will let us pull out a killswitch for this specific stock,
+ // and automatic cleanup for very slow subscribers (where the browser has crashed, etc).
+ final Flow killswitchFlow = Flow.of(JsonNode.class)
+ .joinMat(KillSwitches.singleBidi(), Keep.right());
+ // Set up a complete runnable graph from the stock source to the hub's sink
+ String name = "stock-" + stock.symbol + "-" + id;
+ final RunnableGraph graph = stockSource
+ .viaMat(killswitchFlow, Keep.right())
+ .to(hubSink)
+ .named(name);
+
+ // Start it up!
+ UniqueKillSwitch killSwitch = graph.run(mat);
+
+ // Pull out the kill switch so we can stop it when we want to unwatch a stock.
+ stocksMap.put(stock.symbol, killSwitch);
+ }
+
+ private void unwatchStocks(Set symbols) {
+ symbols.forEach(symbol -> {
+ stocksMap.get(symbol).shutdown();
+ stocksMap.remove(symbol);
+ });
+ }
+
+ public interface Factory {
+ Actor create(String id);
+ }
+}
diff --git a/play-java-websocket-example/app/actors/UserParentActor.java b/play-java-websocket-example/app/actors/UserParentActor.java
new file mode 100644
index 000000000..1ab85a920
--- /dev/null
+++ b/play-java-websocket-example/app/actors/UserParentActor.java
@@ -0,0 +1,49 @@
+package actors;
+
+import akka.actor.AbstractActor;
+import akka.actor.ActorRef;
+import akka.util.Timeout;
+import com.typesafe.config.Config;
+import play.libs.akka.InjectedActorSupport;
+
+import javax.inject.Inject;
+import java.util.HashSet;
+import java.util.Set;
+import java.util.concurrent.CompletionStage;
+import java.util.concurrent.TimeUnit;
+
+import static akka.pattern.PatternsCS.ask;
+import static akka.pattern.PatternsCS.pipe;
+
+public class UserParentActor extends AbstractActor implements InjectedActorSupport {
+
+ private final Timeout timeout = new Timeout(2, TimeUnit.SECONDS);
+ private final Set defaultStocks;
+
+ public static class Create {
+ final String id;
+
+ public Create(String id) {
+ this.id = id;
+ }
+ }
+
+ private final UserActor.Factory childFactory;
+
+ @Inject
+ public UserParentActor(UserActor.Factory childFactory, Config config) {
+ this.childFactory = childFactory;
+ this.defaultStocks = new HashSet<>(config.getStringList("default.stocks"));
+ }
+
+ @Override
+ public Receive createReceive() {
+ return receiveBuilder()
+ .match(UserParentActor.Create.class, create -> {
+ ActorRef child = injectedChild(() -> childFactory.create(create.id), "userActor-" + create.id);
+ CompletionStage