├── project ├── build.properties └── plugins.sbt ├── README.md ├── public └── images │ ├── buy.png │ ├── hold.png │ ├── sell.png │ └── favicon.png ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── .gitignore ├── app ├── stocks │ ├── StockQuoteGenerator.java │ ├── StockQuote.java │ ├── StockHistory.java │ ├── StockUpdate.java │ ├── FakeStockQuoteGenerator.java │ └── Stock.java ├── Module.java ├── actors │ ├── Messages.java │ ├── StocksActor.java │ ├── UserParentActor.java │ └── UserActor.java ├── views │ └── index.scala.html ├── assets │ ├── stylesheets │ │ └── main.less │ └── javascripts │ │ └── index.coffee └── controllers │ ├── StockSentiment.java │ └── HomeController.java ├── scripts ├── test-sbt └── test-gradle ├── NOTICE ├── conf ├── routes ├── logback.xml └── application.conf ├── .mergify.yml ├── .travis.yml ├── gradlew.bat ├── test └── controllers │ ├── WebSocketClient.java │ └── FunctionalTest.java ├── .github └── settings.yml ├── gradlew └── LICENSE /project/build.properties: -------------------------------------------------------------------------------- 1 | sbt.version=1.2.8 2 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | MOVED TO https://github.com/playframework/play-samples 2 | -------------------------------------------------------------------------------- /public/images/buy.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/playframework/play-java-websocket-example/2.7.x/public/images/buy.png -------------------------------------------------------------------------------- /public/images/hold.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/playframework/play-java-websocket-example/2.7.x/public/images/hold.png -------------------------------------------------------------------------------- /public/images/sell.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/playframework/play-java-websocket-example/2.7.x/public/images/sell.png -------------------------------------------------------------------------------- /public/images/favicon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/playframework/play-java-websocket-example/2.7.x/public/images/favicon.png -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/playframework/play-java-websocket-example/2.7.x/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | logs 2 | target 3 | build 4 | /.idea 5 | /.idea_modules 6 | /.classpath 7 | /.project 8 | /.gradle 9 | /.settings 10 | /RUNNING_PID 11 | -------------------------------------------------------------------------------- /app/stocks/StockQuoteGenerator.java: -------------------------------------------------------------------------------- 1 | package stocks; 2 | 3 | public interface StockQuoteGenerator { 4 | StockQuote newQuote(StockQuote last); 5 | 6 | StockQuote seed(); 7 | } 8 | -------------------------------------------------------------------------------- /scripts/test-sbt: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | echo "+----------------------------+" 4 | echo "| Executing tests using sbt |" 5 | echo "+----------------------------+" 6 | sbt ++$TRAVIS_SCALA_VERSION test 7 | -------------------------------------------------------------------------------- /project/plugins.sbt: -------------------------------------------------------------------------------- 1 | addSbtPlugin("com.typesafe.play" % "sbt-plugin" % "2.7.0") 2 | 3 | addSbtPlugin("com.typesafe.sbt" % "sbt-less" % "1.1.2") 4 | 5 | addSbtPlugin("com.typesafe.sbt" % "sbt-coffeescript" % "1.0.2") 6 | 7 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionUrl=https\://services.gradle.org/distributions/gradle-4.9-bin.zip 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStorePath=wrapper/dists 5 | zipStoreBase=GRADLE_USER_HOME 6 | -------------------------------------------------------------------------------- /app/stocks/StockQuote.java: -------------------------------------------------------------------------------- 1 | package stocks; 2 | 3 | import java.util.Objects; 4 | 5 | import static java.util.Objects.requireNonNull; 6 | 7 | public class StockQuote { 8 | public final String symbol; 9 | public final Double price; 10 | 11 | public StockQuote(String symbol, Double price) { 12 | this.symbol = requireNonNull(symbol); 13 | this.price = requireNonNull(price); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /NOTICE: -------------------------------------------------------------------------------- 1 | Written by Lightbend 2 | 3 | To the extent possible under law, the author(s) have dedicated all copyright and 4 | related and neighboring rights to this software to the public domain worldwide. 5 | This software is distributed without any warranty. 6 | 7 | You should have received a copy of the CC0 Public Domain Dedication along with 8 | this software. If not, see . 9 | -------------------------------------------------------------------------------- /scripts/test-gradle: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | # Using cut because TRAVIS_SCALA_VERSION is the full Scala 4 | # version (for example 2.12.4), but Gradle expects just the 5 | # binary version (for example 2.12) 6 | scala_binary_version=$(echo $TRAVIS_SCALA_VERSION | cut -c1-4) 7 | 8 | echo "+------------------------------+" 9 | echo "| Executing tests using Gradle |" 10 | echo "+------------------------------+" 11 | ./gradlew -Dscala.binary.version=$scala_binary_version check -i --stacktrace 12 | -------------------------------------------------------------------------------- /app/Module.java: -------------------------------------------------------------------------------- 1 | import actors.*; 2 | import com.google.inject.AbstractModule; 3 | import play.libs.akka.AkkaGuiceSupport; 4 | 5 | @SuppressWarnings("unused") 6 | public class Module extends AbstractModule implements AkkaGuiceSupport { 7 | @Override 8 | protected void configure() { 9 | bindActor(StocksActor.class, "stocksActor"); 10 | bindActor(UserParentActor.class, "userParentActor"); 11 | bindActorFactory(UserActor.class, UserActor.Factory.class); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /conf/routes: -------------------------------------------------------------------------------- 1 | # Routes 2 | # This file defines all application routes (Higher priority routes first) 3 | # ~~~~ 4 | 5 | GET / controllers.HomeController.index(request :Request) 6 | GET /ws controllers.HomeController.ws 7 | GET /sentiment/:symbol controllers.StockSentiment.get(symbol) 8 | 9 | # Map static resources from the /public folder to the /assets URL path 10 | GET /assets/*file controllers.Assets.at(path="/public", file) 11 | 12 | -> /webjars webjars.Routes 13 | -------------------------------------------------------------------------------- /app/stocks/StockHistory.java: -------------------------------------------------------------------------------- 1 | package stocks; 2 | 3 | import java.util.List; 4 | 5 | import static java.util.Objects.requireNonNull; 6 | 7 | /** A JSON presentation class for stock history. */ 8 | public class StockHistory { 9 | private final String symbol; 10 | private final List prices; 11 | 12 | public StockHistory(String symbol, List prices) { 13 | this.symbol = requireNonNull(symbol); 14 | this.prices = requireNonNull(prices); 15 | } 16 | 17 | public String getType() { 18 | return "stockhistory"; 19 | } 20 | 21 | public String getSymbol() { 22 | return symbol; 23 | } 24 | 25 | public List getHistory() { 26 | return prices; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /app/stocks/StockUpdate.java: -------------------------------------------------------------------------------- 1 | package stocks; 2 | 3 | import com.fasterxml.jackson.annotation.JsonTypeInfo; 4 | 5 | import static java.util.Objects.requireNonNull; 6 | 7 | /** A JSON presentation class for stock updates. */ 8 | public class StockUpdate { 9 | private final String symbol; 10 | private final Double price; 11 | 12 | public StockUpdate(String symbol, Double price) { 13 | this.symbol = requireNonNull(symbol); 14 | this.price = requireNonNull(price); 15 | } 16 | 17 | public String getType() { 18 | return "stockupdate"; 19 | } 20 | 21 | public Double getPrice() { 22 | return price; 23 | } 24 | 25 | public String getSymbol() { 26 | return symbol; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /app/stocks/FakeStockQuoteGenerator.java: -------------------------------------------------------------------------------- 1 | package stocks; 2 | 3 | import java.util.concurrent.ThreadLocalRandom; 4 | 5 | public class FakeStockQuoteGenerator implements StockQuoteGenerator { 6 | 7 | private final String symbol; 8 | 9 | public FakeStockQuoteGenerator(String symbol) { 10 | this.symbol = symbol; 11 | } 12 | 13 | private Double random() { 14 | return ThreadLocalRandom.current().nextDouble(); 15 | } 16 | 17 | @Override 18 | public StockQuote newQuote(StockQuote last) { 19 | return new StockQuote(last.symbol, last.price * (0.95 + (0.1 * random()))); 20 | } 21 | 22 | @Override 23 | public StockQuote seed() { 24 | return new StockQuote(symbol, random() * 800); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /.mergify.yml: -------------------------------------------------------------------------------- 1 | pull_request_rules: 2 | - name: Merge PRs that are ready 3 | conditions: 4 | - status-success=Travis CI - Pull Request 5 | - status-success=typesafe-cla-validator 6 | - "#approved-reviews-by>=1" 7 | - "#review-requested=0" 8 | - "#changes-requested-reviews-by=0" 9 | - label!=status:block-merge 10 | actions: 11 | merge: 12 | method: squash 13 | strict: smart 14 | 15 | - name: Merge TemplateControl's PRs that are ready 16 | conditions: 17 | - status-success=Travis CI - Pull Request 18 | - "#review-requested=0" 19 | - "#changes-requested-reviews-by=0" 20 | - label!=status:block-merge 21 | - label=status:merge-when-green 22 | - label!=status:block-merge 23 | actions: 24 | merge: 25 | method: squash 26 | strict: smart 27 | 28 | - name: Delete the PR branch after merge 29 | conditions: 30 | - merged 31 | actions: 32 | delete_head_branch: {} 33 | -------------------------------------------------------------------------------- /conf/logback.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | logs/application.log 7 | 8 | %date [%level] from %logger in %thread - %message%n%xException 9 | 10 | 11 | 12 | 13 | 14 | %coloredLevel %logger{15} - %message%n%xException{10} 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /conf/application.conf: -------------------------------------------------------------------------------- 1 | # This is the main configuration file for the application. 2 | # ~~~~~ 3 | 4 | # Uncomment this for the most verbose Akka debugging: 5 | akka { 6 | loggers = ["akka.event.slf4j.Slf4jLogger"] 7 | loglevel = "INFO" 8 | logging-filter = "akka.event.slf4j.Slf4jLoggingFilter" 9 | #actor { 10 | # debug { 11 | # receive = on 12 | # autoreceive = on 13 | # lifecycle = on 14 | # } 15 | #} 16 | } 17 | 18 | # https://www.playframework.com/documentation/latest/SecurityHeaders 19 | # Allow URLs from the same origin to be loaded by frames and scripts 20 | play.filters.headers { 21 | frameOptions = "SAMEORIGIN" 22 | } 23 | 24 | play.filters.csp.directives { 25 | connect-src = "'self'" 26 | default-src = "'self'" 27 | } 28 | 29 | # https://www.playframework.com/documentation/latest/AllowedHostsFilter 30 | # Allow requests to localhost:9000. 31 | play.filters.hosts { 32 | allowed = ["localhost:9000"] 33 | } 34 | 35 | default.stocks=["GOOG", "AAPL", "ORCL"] 36 | 37 | sentiment.url="http://text-processing.com/api/sentiment/" 38 | tweet.url="http://twitter-search-proxy.herokuapp.com/search/tweets" 39 | -------------------------------------------------------------------------------- /app/actors/Messages.java: -------------------------------------------------------------------------------- 1 | package actors; 2 | 3 | import stocks.Stock; 4 | 5 | import java.util.Set; 6 | 7 | import static java.util.Objects.requireNonNull; 8 | 9 | public final class Messages { 10 | 11 | public static final class WatchStocks { 12 | final Set symbols; 13 | 14 | public WatchStocks(Set symbols) { 15 | this.symbols = requireNonNull(symbols); 16 | } 17 | 18 | @Override 19 | public String toString() { 20 | return "WatchStocks(" + symbols.toString() + ")"; 21 | } 22 | } 23 | 24 | public static final class UnwatchStocks { 25 | final Set symbols; 26 | 27 | public UnwatchStocks(Set symbols) { 28 | this.symbols = requireNonNull(symbols); 29 | } 30 | 31 | @Override 32 | public String toString() { 33 | return "UnwatchStocks(" + symbols.toString() + ")"; 34 | } 35 | } 36 | 37 | public static class Stocks { 38 | final Set stocks; 39 | 40 | public Stocks(Set stocks) { 41 | this.stocks = requireNonNull(stocks); 42 | } 43 | } 44 | } 45 | 46 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: scala 2 | scala: 2.12.8 3 | script: $SCRIPT 4 | 5 | env: 6 | matrix: 7 | - SCRIPT=scripts/test-sbt TRAVIS_JDK=adopt@1.8.202-08 8 | - SCRIPT=scripts/test-sbt TRAVIS_JDK=adopt@1.11.0-2 9 | - SCRIPT=scripts/test-gradle TRAVIS_JDK=adopt@1.8.202-08 10 | - SCRIPT=scripts/test-gradle TRAVIS_JDK=adopt@1.11.0-2 11 | 12 | matrix: 13 | fast_finish: true 14 | allow_failures: 15 | - env: SCRIPT=scripts/test-gradle TRAVIS_JDK=adopt@1.8.202-08 # current gradle doesn't support play 2.7 16 | - env: SCRIPT=scripts/test-gradle TRAVIS_JDK=adopt@1.11.0-2 # current gradle doesn't support play 2.7 17 | - env: SCRIPT=scripts/test-sbt TRAVIS_JDK=adopt@1.11.0-2 # not fully supported but allows problem discovery 18 | 19 | before_install: curl -Ls https://git.io/jabba | bash && . ~/.jabba/jabba.sh 20 | install: jabba install "$TRAVIS_JDK" && jabba use "$_" && java -Xmx32m -version 21 | 22 | cache: 23 | directories: 24 | - "$HOME/.gradle/caches" 25 | - "$HOME/.ivy2/cache" 26 | - "$HOME/.jabba/jdk" 27 | - "$HOME/.sbt" 28 | 29 | before_cache: 30 | - find $HOME/.ivy2 -name "ivydata-*.properties" -delete 31 | - find $HOME/.sbt -name "*.lock" -delete 32 | -------------------------------------------------------------------------------- /app/actors/StocksActor.java: -------------------------------------------------------------------------------- 1 | package actors; 2 | 3 | import akka.actor.AbstractActor; 4 | import akka.event.Logging; 5 | import akka.event.LoggingAdapter; 6 | import stocks.Stock; 7 | 8 | import java.util.HashMap; 9 | import java.util.Map; 10 | import java.util.Set; 11 | import java.util.stream.Collector; 12 | import java.util.stream.Collectors; 13 | 14 | /** 15 | * This actor contains a set of stocks internally that may be used by 16 | * all websocket clients. 17 | */ 18 | public class StocksActor extends AbstractActor { 19 | 20 | private final Map stocksMap = new HashMap<>(); 21 | 22 | private final LoggingAdapter log = Logging.getLogger(getContext().system(), this); 23 | 24 | @Override 25 | public Receive createReceive() { 26 | return receiveBuilder() 27 | .match(Messages.WatchStocks.class, watchStocks -> { 28 | Set stocks = watchStocks.symbols.stream() 29 | .map(symbol -> stocksMap.compute(symbol, (k, v) -> new Stock(k))) 30 | .collect(Collectors.toSet()); 31 | sender().tell(new Messages.Stocks(stocks), self()); 32 | }).build(); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /app/views/index.scala.html: -------------------------------------------------------------------------------- 1 | @(request: play.mvc.Http.Request, webJarsUtil: org.webjars.play.WebJarsUtil) 2 | 3 | 4 | 5 | 6 | Reactive Stock News Dashboard 7 | 8 | 9 | 10 | 11 | @webJarsUtil.locate("bootstrap.min.css").css() 12 | 13 | 14 | @webJarsUtil.locate("jquery.min.js").script() 15 | @webJarsUtil.locate("jquery.flot.js").script() 16 | 17 | 18 | 19 | 30 | 31 |
32 | 33 |
34 | 35 | 36 | -------------------------------------------------------------------------------- /app/actors/UserParentActor.java: -------------------------------------------------------------------------------- 1 | package actors; 2 | 3 | import akka.actor.AbstractActor; 4 | import akka.actor.ActorRef; 5 | import akka.util.Timeout; 6 | import com.typesafe.config.Config; 7 | import play.libs.akka.InjectedActorSupport; 8 | 9 | import javax.inject.Inject; 10 | import java.util.HashSet; 11 | import java.util.Set; 12 | import java.util.concurrent.CompletionStage; 13 | import java.util.concurrent.TimeUnit; 14 | 15 | import static akka.pattern.PatternsCS.ask; 16 | import static akka.pattern.PatternsCS.pipe; 17 | 18 | public class UserParentActor extends AbstractActor implements InjectedActorSupport { 19 | 20 | private final Timeout timeout = new Timeout(2, TimeUnit.SECONDS); 21 | private final Set defaultStocks; 22 | 23 | public static class Create { 24 | final String id; 25 | 26 | public Create(String id) { 27 | this.id = id; 28 | } 29 | } 30 | 31 | private final UserActor.Factory childFactory; 32 | 33 | @Inject 34 | public UserParentActor(UserActor.Factory childFactory, Config config) { 35 | this.childFactory = childFactory; 36 | this.defaultStocks = new HashSet<>(config.getStringList("default.stocks")); 37 | } 38 | 39 | @Override 40 | public Receive createReceive() { 41 | return receiveBuilder() 42 | .match(UserParentActor.Create.class, create -> { 43 | ActorRef child = injectedChild(() -> childFactory.create(create.id), "userActor-" + create.id); 44 | CompletionStage future = ask(child, new Messages.WatchStocks(defaultStocks), timeout); 45 | pipe(future, context().dispatcher()).to(sender()); 46 | }).build(); 47 | } 48 | 49 | } 50 | -------------------------------------------------------------------------------- /app/stocks/Stock.java: -------------------------------------------------------------------------------- 1 | package stocks; 2 | 3 | import akka.NotUsed; 4 | import akka.japi.Pair; 5 | import akka.japi.function.Function; 6 | import akka.stream.ThrottleMode; 7 | import akka.stream.javadsl.Source; 8 | 9 | import java.time.Duration; 10 | import java.time.temporal.ChronoUnit; 11 | import java.util.Optional; 12 | import java.util.stream.Collectors; 13 | 14 | import static java.util.Objects.requireNonNull; 15 | 16 | /** 17 | * A stock is a source of stock quotes and a symbol. 18 | */ 19 | public class Stock { 20 | public final String symbol; 21 | 22 | private final StockQuoteGenerator stockQuoteGenerator; 23 | 24 | private final Source source; 25 | 26 | private static final Duration duration = Duration.of(75, ChronoUnit.MILLIS); 27 | 28 | public Stock(String symbol) { 29 | this.symbol = requireNonNull(symbol); 30 | stockQuoteGenerator = new FakeStockQuoteGenerator(symbol); 31 | source = Source.unfold(stockQuoteGenerator.seed(), (Function>>) last -> { 32 | StockQuote next = stockQuoteGenerator.newQuote(last); 33 | return Optional.of(Pair.apply(next, next)); 34 | }); 35 | } 36 | 37 | /** 38 | * Returns a source of stock history, containing a single element. 39 | */ 40 | public Source history(int n) { 41 | return source.grouped(n) 42 | .map(quotes -> new StockHistory(symbol, quotes.stream().map(sq -> sq.price).collect(Collectors.toList()))) 43 | .take(1); 44 | } 45 | 46 | /** 47 | * Provides a source that returns a stock quote every 75 milliseconds. 48 | */ 49 | public Source update() { 50 | return source.throttle(1, duration, 1, ThrottleMode.shaping()) 51 | .map(sq -> new StockUpdate(sq.symbol, sq.price)); 52 | } 53 | 54 | @Override 55 | public String toString() { 56 | return "Stock(" + symbol + ")"; 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | set DIRNAME=%~dp0 12 | if "%DIRNAME%" == "" set DIRNAME=. 13 | set APP_BASE_NAME=%~n0 14 | set APP_HOME=%DIRNAME% 15 | 16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 17 | set DEFAULT_JVM_OPTS= 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windows variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | 53 | :win9xME_args 54 | @rem Slurp the command line arguments. 55 | set CMD_LINE_ARGS= 56 | set _SKIP=2 57 | 58 | :win9xME_args_slurp 59 | if "x%~1" == "x" goto execute 60 | 61 | set CMD_LINE_ARGS=%* 62 | 63 | :execute 64 | @rem Setup the command line 65 | 66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 67 | 68 | @rem Execute Gradle 69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 70 | 71 | :end 72 | @rem End local scope for the variables with windows NT shell 73 | if "%ERRORLEVEL%"=="0" goto mainEnd 74 | 75 | :fail 76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 77 | rem the _cmd.exe /c_ return code! 78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 79 | exit /b 1 80 | 81 | :mainEnd 82 | if "%OS%"=="Windows_NT" endlocal 83 | 84 | :omega 85 | -------------------------------------------------------------------------------- /test/controllers/WebSocketClient.java: -------------------------------------------------------------------------------- 1 | package controllers; 2 | 3 | import play.shaded.ahc.org.asynchttpclient.AsyncHttpClient; 4 | import play.shaded.ahc.org.asynchttpclient.BoundRequestBuilder; 5 | import play.shaded.ahc.org.asynchttpclient.ListenableFuture; 6 | import play.shaded.ahc.org.asynchttpclient.netty.ws.NettyWebSocket; 7 | import play.shaded.ahc.org.asynchttpclient.ws.WebSocket; 8 | import play.shaded.ahc.org.asynchttpclient.ws.WebSocketListener; 9 | import play.shaded.ahc.org.asynchttpclient.ws.WebSocketUpgradeHandler; 10 | import org.slf4j.Logger; 11 | 12 | import java.util.concurrent.CompletableFuture; 13 | import java.util.concurrent.ExecutionException; 14 | import java.util.function.Consumer; 15 | 16 | public class WebSocketClient { 17 | 18 | private AsyncHttpClient client; 19 | 20 | public WebSocketClient(AsyncHttpClient c) { 21 | this.client = c; 22 | } 23 | 24 | public CompletableFuture call(String url, String origin, WebSocketListener listener) throws ExecutionException, InterruptedException { 25 | final BoundRequestBuilder requestBuilder = client.prepareGet(url).addHeader("Origin", origin); 26 | 27 | final WebSocketUpgradeHandler handler = new WebSocketUpgradeHandler.Builder().addWebSocketListener(listener).build(); 28 | final ListenableFuture future = requestBuilder.execute(handler); 29 | return future.toCompletableFuture(); 30 | } 31 | 32 | static class LoggingListener implements WebSocketListener { 33 | private final Consumer onMessageCallback; 34 | 35 | public LoggingListener(Consumer onMessageCallback) { 36 | this.onMessageCallback = onMessageCallback; 37 | } 38 | 39 | private Logger logger = org.slf4j.LoggerFactory.getLogger(LoggingListener.class); 40 | 41 | private Throwable throwableFound = null; 42 | 43 | public Throwable getThrowable() { 44 | return throwableFound; 45 | } 46 | 47 | public void onOpen(WebSocket websocket) { 48 | // do nothing 49 | } 50 | 51 | @Override 52 | public void onClose(WebSocket webSocket, int i, String s) { 53 | // do nothing 54 | } 55 | 56 | public void onError(Throwable t) { 57 | // do nothing 58 | throwableFound = t; 59 | } 60 | 61 | @Override 62 | public void onTextFrame(String payload, boolean finalFragment, int rsv) { 63 | //logger.info("onMessage: s = " + s); 64 | onMessageCallback.accept(payload); 65 | } 66 | } 67 | 68 | } -------------------------------------------------------------------------------- /app/assets/stylesheets/main.less: -------------------------------------------------------------------------------- 1 | .perspective (@value) { 2 | -webkit-perspective: @value; 3 | -moz-perspective: @value; 4 | perspective: @value; 5 | } 6 | 7 | .transform (@value) { 8 | -webkit-transform: rotateY(@value); 9 | -moz-transform: rotateY(@value); 10 | transform: rotateY(@value); 11 | } 12 | 13 | .border-radius (@value) { 14 | -webkit-border-radius: @value; 15 | -moz-border-radius: @value; 16 | border-radius: @value; 17 | } 18 | 19 | 20 | body { 21 | margin-top: 50px; 22 | } 23 | 24 | .flip-container { 25 | .perspective(1000); 26 | margin-bottom: 20px; 27 | &:hover .flipper { 28 | .transform(10deg); 29 | } 30 | &.flipped .flipper { 31 | .transform(180deg); 32 | } 33 | } 34 | 35 | .flipper { 36 | height: 250px; 37 | 38 | background-color: #fafafa; 39 | border: 1px solid #ddd; 40 | 41 | .border-radius(4px); 42 | 43 | cursor: hand; 44 | cursor: pointer; 45 | 46 | -webkit-transition: 0.6s; 47 | -moz-transition: 0.6s; 48 | transition: 0.6s; 49 | 50 | -webkit-transform-style: preserve-3d; 51 | -moz-transform-style: preserve-3d; 52 | transform-style: preserve-3d; 53 | 54 | &:after { 55 | content: attr(data-content); 56 | position: absolute; 57 | top: -1px; 58 | left: -1px; 59 | padding: 3px 7px; 60 | font-size: 12px; 61 | font-weight: bold; 62 | background-color: #ffffff; 63 | border: 1px solid #ddd; 64 | color: #9da0a4; 65 | 66 | .border-radius(4px 0 4px 0); 67 | } 68 | } 69 | 70 | .chart-holder, .details-holder { 71 | position: absolute; 72 | width: 100%; 73 | height: 250px; 74 | top: 0px; 75 | left: 0px; 76 | 77 | -webkit-backface-visibility: hidden; 78 | -moz-backface-visibility: hidden; 79 | backface-visibility: hidden; 80 | } 81 | 82 | .details-holder { 83 | z-index: 1; 84 | transform-style: preserve-3d; 85 | } 86 | 87 | .chart-holder { 88 | z-index: 2; 89 | & p { 90 | position: absolute; 91 | bottom: 7px; 92 | right: 20px; 93 | font-size: 10px; 94 | color: #aaaaaa; 95 | font-style: italic; 96 | } 97 | } 98 | 99 | .details-holder { 100 | .transform(180deg); 101 | text-align: center; 102 | & h4 { 103 | padding: 20px; 104 | } 105 | & .progress { 106 | padding: 20px; 107 | background: none; 108 | border: none; 109 | 110 | -webkit-box-shadow: none; 111 | -moz-box-shadow: none; 112 | box-shadow: none; 113 | } 114 | & img { 115 | height: 128px; 116 | width: 128px; 117 | } 118 | } 119 | 120 | .chart { 121 | position: relative; 122 | width: 920px; 123 | height: 210px; 124 | margin-top: 30px; 125 | margin-bottom: 10px; 126 | margin-left: 10px; 127 | margin-right: 10px; 128 | } 129 | -------------------------------------------------------------------------------- /.github/settings.yml: -------------------------------------------------------------------------------- 1 | # These settings are synced to GitHub by https://probot.github.io/apps/settings/ 2 | repository: 3 | homepage: "https://developer.lightbend.com/start/?group=play" 4 | topics: playframework, example, example-project, sample, sample-app, jvm, webapp 5 | private: false 6 | has_issues: true 7 | # We don't need projects in sample projects 8 | has_projects: false 9 | # We don't need wiki in sample projects 10 | has_wiki: false 11 | has_downloads: true 12 | default_branch: 2.7.x 13 | allow_squash_merge: true 14 | allow_merge_commit: false 15 | allow_rebase_merge: false 16 | 17 | teams: 18 | - name: core 19 | permission: admin 20 | - name: integrators 21 | permission: write 22 | - name: write-bots 23 | permission: write 24 | 25 | branches: 26 | - name: "[0-9].*.x" 27 | protection: 28 | # We don't require reviews for sample applications because they are mainly 29 | # updated by template-control, which is an automated process 30 | required_pull_request_reviews: null 31 | # Required. Require status checks to pass before merging. Set to null to disable 32 | required_status_checks: 33 | # Required. The list of status checks to require in order to merge into this branch 34 | contexts: ["Travis CI - Pull Request", "typesafe-cla-validator"] 35 | 36 | # Labels: tailored list of labels to be used by sample applications 37 | labels: 38 | - color: f9d0c4 39 | name: "closed:declined" 40 | - color: f9d0c4 41 | name: "closed:duplicated" 42 | oldname: duplicate 43 | - color: f9d0c4 44 | name: "closed:invalid" 45 | oldname: invalid 46 | - color: f9d0c4 47 | name: "closed:question" 48 | oldname: question 49 | - color: f9d0c4 50 | name: "closed:wontfix" 51 | oldname: wontfix 52 | - color: 7057ff 53 | name: "good first issue" 54 | - color: 7057ff 55 | name: "Hacktoberfest" 56 | - color: 7057ff 57 | name: "help wanted" 58 | - color: cceecc 59 | name: "status:backlog" 60 | oldname: backlog 61 | - color: b60205 62 | name: "status:block-merge" 63 | oldname: block-merge 64 | - color: b60205 65 | name: "status:blocked" 66 | - color: 0e8a16 67 | name: "status:in-progress" 68 | - color: 0e8a16 69 | name: "status:merge-when-green" 70 | oldname: merge-when-green 71 | - color: fbca04 72 | name: "status:needs-backport" 73 | - color: fbca04 74 | name: "status:needs-forwardport" 75 | - color: fbca04 76 | name: "status:needs-info" 77 | - color: fbca04 78 | name: "status:needs-verification" 79 | - color: 0e8a16 80 | name: "status:ready" 81 | - color: fbca04 82 | name: "status:to-review" 83 | oldname: review 84 | - color: c5def5 85 | name: "topic:build/tests" 86 | - color: c5def5 87 | name: "topic:dev-environment" 88 | - color: c5def5 89 | name: "topic:documentation" 90 | - color: c5def5 91 | name: "topic:jdk-next" 92 | - color: b60205 93 | name: "type:defect" 94 | oldname: bug 95 | - color: 0052cc 96 | name: "type:feature" 97 | - color: 0052cc 98 | name: "type:improvement" 99 | oldname: enhancement 100 | - color: 0052cc 101 | name: "type:updates" 102 | - color: bf0d92 103 | name: "type:template-control" 104 | oldname: template-control 105 | -------------------------------------------------------------------------------- /test/controllers/FunctionalTest.java: -------------------------------------------------------------------------------- 1 | package controllers; 2 | 3 | import com.fasterxml.jackson.databind.JsonNode; 4 | import org.junit.Test; 5 | import play.libs.Json; 6 | import play.shaded.ahc.org.asynchttpclient.AsyncHttpClient; 7 | import play.shaded.ahc.org.asynchttpclient.AsyncHttpClientConfig; 8 | import play.shaded.ahc.org.asynchttpclient.DefaultAsyncHttpClient; 9 | import play.shaded.ahc.org.asynchttpclient.DefaultAsyncHttpClientConfig; 10 | import play.shaded.ahc.org.asynchttpclient.netty.ws.NettyWebSocket; 11 | import play.shaded.ahc.org.asynchttpclient.ws.WebSocket; 12 | import play.test.TestServer; 13 | 14 | import java.util.Collections; 15 | import java.util.concurrent.ArrayBlockingQueue; 16 | import java.util.concurrent.CompletableFuture; 17 | 18 | import static org.assertj.core.api.Assertions.assertThat; 19 | import static org.assertj.core.api.Assertions.fail; 20 | import static org.awaitility.Awaitility.await; 21 | import static play.test.Helpers.running; 22 | import static play.test.Helpers.testServer; 23 | 24 | public class FunctionalTest { 25 | 26 | 27 | @Test 28 | public void testRejectWebSocket() { 29 | TestServer server = testServer(37117); 30 | running(server, () -> { 31 | try { 32 | AsyncHttpClientConfig config = new DefaultAsyncHttpClientConfig.Builder().setMaxRequestRetry(0).build(); 33 | AsyncHttpClient client = new DefaultAsyncHttpClient(config); 34 | WebSocketClient webSocketClient = new WebSocketClient(client); 35 | 36 | try { 37 | String serverURL = "ws://localhost:37117/ws"; 38 | WebSocketClient.LoggingListener listener = new WebSocketClient.LoggingListener(message -> {}); 39 | CompletableFuture completionStage = webSocketClient.call(serverURL, serverURL, listener); 40 | await().until(completionStage::isDone); 41 | assertThat(completionStage.get()) 42 | .isNull(); 43 | } finally { 44 | client.close(); 45 | } 46 | } catch (Exception e) { 47 | fail("Unexpected exception", e); 48 | } 49 | }); 50 | } 51 | 52 | @Test 53 | public void testAcceptWebSocket() { 54 | TestServer server = testServer(19001); 55 | running(server, () -> { 56 | try { 57 | AsyncHttpClientConfig config = new DefaultAsyncHttpClientConfig.Builder().setMaxRequestRetry(0).build(); 58 | AsyncHttpClient client = new DefaultAsyncHttpClient(config); 59 | WebSocketClient webSocketClient = new WebSocketClient(client); 60 | 61 | try { 62 | String serverURL = "ws://localhost:19001/ws"; 63 | ArrayBlockingQueue queue = new ArrayBlockingQueue(10); 64 | WebSocketClient.LoggingListener listener = new WebSocketClient.LoggingListener((message) -> { 65 | try { 66 | queue.put(message); 67 | } catch (InterruptedException e) { 68 | e.printStackTrace(); 69 | } 70 | }); 71 | CompletableFuture completionStage = webSocketClient.call(serverURL, serverURL, listener); 72 | 73 | await().until(completionStage::isDone); 74 | WebSocket websocket = completionStage.get(); 75 | await().until(() -> websocket.isOpen() && queue.peek() != null); 76 | String input = queue.take(); 77 | 78 | JsonNode json = Json.parse(input); 79 | String symbol = json.get("symbol").asText(); 80 | assertThat(Collections.singletonList(symbol)).isSubsetOf("AAPL", "GOOG", "ORCL"); 81 | } finally { 82 | client.close(); 83 | } 84 | } catch (Exception e) { 85 | fail("Unexpected exception", e); 86 | } 87 | }); 88 | } 89 | } 90 | -------------------------------------------------------------------------------- /app/assets/javascripts/index.coffee: -------------------------------------------------------------------------------- 1 | $ -> 2 | ws = new WebSocket $("body").data("ws-url") 3 | ws.onmessage = (event) -> 4 | message = JSON.parse event.data 5 | switch message.type 6 | when "stockhistory" 7 | populateStockHistory(message) 8 | when "stockupdate" 9 | updateStockChart(message) 10 | else 11 | console.log(message) 12 | 13 | $("#addsymbolform").submit (event) -> 14 | event.preventDefault() 15 | # send the message to watch the stock 16 | ws.send(JSON.stringify({symbol: $("#addsymboltext").val()})) 17 | # reset the form 18 | $("#addsymboltext").val("") 19 | 20 | getPricesFromArray = (data) -> 21 | (v[1] for v in data) 22 | 23 | getChartArray = (data) -> 24 | ([i, v] for v, i in data) 25 | 26 | getChartOptions = (data) -> 27 | series: 28 | shadowSize: 0 29 | yaxis: 30 | min: getAxisMin(data) 31 | max: getAxisMax(data) 32 | xaxis: 33 | show: false 34 | 35 | getAxisMin = (data) -> 36 | Math.min.apply(Math, data) * 0.9 37 | 38 | getAxisMax = (data) -> 39 | Math.max.apply(Math, data) * 1.1 40 | 41 | populateStockHistory = (message) -> 42 | chart = $("
").addClass("chart").prop("id", message.symbol) 43 | chartHolder = $("
").addClass("chart-holder").append(chart) 44 | chartHolder.append($("

").text("values are simulated")) 45 | detailsHolder = $("

").addClass("details-holder") 46 | flipper = $("
").addClass("flipper").append(chartHolder).append(detailsHolder).attr("data-content", message.symbol) 47 | flipContainer = $("
").addClass("flip-container").append(flipper).click (event) -> 48 | handleFlip($(this)) 49 | $("#stocks").prepend(flipContainer) 50 | plot = chart.plot([getChartArray(message.history)], getChartOptions(message.history)).data("plot") 51 | 52 | updateStockChart = (message) -> 53 | if ($("#" + message.symbol).size() > 0) 54 | plot = $("#" + message.symbol).data("plot") 55 | data = getPricesFromArray(plot.getData()[0].data) 56 | data.shift() 57 | data.push(message.price) 58 | plot.setData([getChartArray(data)]) 59 | # update the yaxes if either the min or max is now out of the acceptable range 60 | yaxes = plot.getOptions().yaxes[0] 61 | if ((getAxisMin(data) < yaxes.min) || (getAxisMax(data) > yaxes.max)) 62 | # reseting yaxes 63 | yaxes.min = getAxisMin(data) 64 | yaxes.max = getAxisMax(data) 65 | plot.setupGrid() 66 | # redraw the chart 67 | plot.draw() 68 | 69 | handleFlip = (container) -> 70 | if (container.hasClass("flipped")) 71 | container.removeClass("flipped") 72 | container.find(".details-holder").empty() 73 | else 74 | container.addClass("flipped") 75 | # fetch stock details and tweet 76 | $.ajax 77 | url: "/sentiment/" + container.children(".flipper").attr("data-content") 78 | dataType: "json" 79 | context: container 80 | success: (data) -> 81 | detailsHolder = $(this).find(".details-holder") 82 | detailsHolder.empty() 83 | switch data.label 84 | when "pos" 85 | detailsHolder.append($("

").text("The tweets say BUY!")) 86 | detailsHolder.append($("").attr("src", "/assets/images/buy.png")) 87 | when "neg" 88 | detailsHolder.append($("

").text("The tweets say SELL!")) 89 | detailsHolder.append($("").attr("src", "/assets/images/sell.png")) 90 | else 91 | detailsHolder.append($("

").text("The tweets say HOLD!")) 92 | detailsHolder.append($("").attr("src", "/assets/images/hold.png")) 93 | error: (jqXHR, textStatus, error) -> 94 | detailsHolder = $(this).find(".details-holder") 95 | detailsHolder.empty() 96 | detailsHolder.append($("

").text("Error: " + JSON.parse(jqXHR.responseText).error)) 97 | # display loading info 98 | detailsHolder = container.find(".details-holder") 99 | detailsHolder.append($("

").text("Determining whether you should buy or sell based on the sentiment of recent tweets...")) 100 | detailsHolder.append($("
").addClass("progress progress-striped active").append($("
").addClass("bar").css("width", "100%"))) -------------------------------------------------------------------------------- /app/controllers/StockSentiment.java: -------------------------------------------------------------------------------- 1 | package controllers; 2 | 3 | import com.fasterxml.jackson.databind.JsonNode; 4 | import com.typesafe.config.Config; 5 | import play.libs.Json; 6 | import play.libs.concurrent.Futures; 7 | import play.libs.concurrent.HttpExecutionContext; 8 | import play.libs.ws.WSClient; 9 | import play.libs.ws.WSResponse; 10 | import play.mvc.Controller; 11 | import play.mvc.Http; 12 | import play.mvc.Result; 13 | import play.mvc.Results; 14 | 15 | import javax.inject.Inject; 16 | import javax.inject.Singleton; 17 | import java.util.List; 18 | import java.util.concurrent.CompletionStage; 19 | import java.util.stream.Collectors; 20 | import java.util.stream.Stream; 21 | 22 | import static java.util.stream.Collectors.averagingDouble; 23 | import static java.util.stream.Collectors.toList; 24 | import static java.util.stream.StreamSupport.stream; 25 | 26 | @Singleton 27 | public class StockSentiment extends Controller { 28 | 29 | private final String sentimentUrl; 30 | private final String tweetUrl; 31 | private final WSClient wsClient; 32 | private final HttpExecutionContext ec; 33 | 34 | @Inject 35 | public StockSentiment(WSClient wsClient, Config configuration, HttpExecutionContext ec) { 36 | this.wsClient = wsClient; 37 | this.ec = ec; 38 | this.sentimentUrl = configuration.getString("sentiment.url"); 39 | this.tweetUrl = configuration.getString("tweet.url"); 40 | } 41 | 42 | public CompletionStage get(String symbol) { 43 | return fetchTweets(symbol) 44 | .thenComposeAsync(this::fetchSentiments) 45 | .thenApplyAsync(this::averageSentiment) 46 | .thenApplyAsync(Results::ok) 47 | .exceptionally(this::errorResponse); 48 | } 49 | 50 | private CompletionStage> fetchTweets(String symbol) { 51 | final CompletionStage futureResponse = wsClient.url(tweetUrl) 52 | .addQueryParameter("q", "$" + symbol) 53 | .get(); 54 | 55 | final CompletionStage filter = futureResponse.thenApplyAsync(response -> { 56 | if (response.getStatus() == Http.Status.OK) { 57 | return response; 58 | } else { 59 | return null; 60 | } 61 | }, ec.current()); 62 | 63 | return filter.thenApplyAsync(response -> { 64 | final List statuses = stream(response.asJson().findPath("statuses").spliterator(), false) 65 | .map(s -> s.findValue("text").asText()) 66 | .collect(Collectors.toList()); 67 | return statuses; 68 | }); 69 | } 70 | 71 | private CompletionStage> fetchSentiments(List tweets) { 72 | Stream> sentiments = tweets.stream().map(text -> { 73 | return wsClient.url(sentimentUrl).post("text=" + text); 74 | }); 75 | return Futures.sequence(sentiments::iterator).thenApplyAsync(this::responsesAsJson); 76 | } 77 | 78 | private List responsesAsJson(List responses) { 79 | return responses.stream().map(WSResponse::asJson).collect(toList()); 80 | } 81 | 82 | private JsonNode averageSentiment(List sentiments) { 83 | double neg = collectAverage(sentiments, "neg"); 84 | double neutral = collectAverage(sentiments, "neutral"); 85 | double pos = collectAverage(sentiments, "pos"); 86 | 87 | String label = (neutral > 0.5) ? "neutral" : (neg > pos) ? "neg" : "pos"; 88 | 89 | return Json.newObject() 90 | .put("label", label) 91 | .set("probability", Json.newObject() 92 | .put("neg", neg) 93 | .put("neutral", neutral) 94 | .put("pos", pos)); 95 | } 96 | 97 | private double collectAverage(List jsons, String label) { 98 | return jsons.stream().collect(averagingDouble(json -> json.findValue(label).asDouble())); 99 | } 100 | 101 | private Result errorResponse(Throwable ignored) { 102 | return internalServerError(Json.newObject().put("error", "Could not fetch the tweets")); 103 | } 104 | } 105 | -------------------------------------------------------------------------------- /app/controllers/HomeController.java: -------------------------------------------------------------------------------- 1 | package controllers; 2 | 3 | import actors.UserParentActor; 4 | import akka.NotUsed; 5 | import akka.actor.ActorRef; 6 | import akka.stream.javadsl.Flow; 7 | import com.fasterxml.jackson.databind.JsonNode; 8 | import org.slf4j.Logger; 9 | import org.webjars.play.WebJarsUtil; 10 | import play.libs.F.Either; 11 | import play.mvc.*; 12 | 13 | 14 | import javax.inject.Inject; 15 | import javax.inject.Named; 16 | import javax.inject.Singleton; 17 | import java.time.Duration; 18 | import java.time.temporal.ChronoUnit; 19 | import java.util.Arrays; 20 | import java.util.List; 21 | import java.util.Optional; 22 | import java.util.concurrent.CompletableFuture; 23 | import java.util.concurrent.CompletionStage; 24 | 25 | import static akka.pattern.PatternsCS.ask; 26 | 27 | /** 28 | * The main web controller that handles returning the index page, setting up a WebSocket, and watching a stock. 29 | */ 30 | @Singleton 31 | public class HomeController extends Controller { 32 | 33 | private final Duration t = Duration.of(1, ChronoUnit.SECONDS); 34 | private final Logger logger = org.slf4j.LoggerFactory.getLogger("controllers.HomeController"); 35 | private final ActorRef userParentActor; 36 | 37 | private WebJarsUtil webJarsUtil; 38 | 39 | @Inject 40 | public HomeController(@Named("userParentActor") ActorRef userParentActor, WebJarsUtil webJarsUtil) { 41 | this.userParentActor = userParentActor; 42 | this.webJarsUtil = webJarsUtil; 43 | } 44 | 45 | public Result index(Http.Request request) { 46 | return ok(views.html.index.render(request, webJarsUtil)); 47 | } 48 | 49 | public WebSocket ws() { 50 | return WebSocket.Json.acceptOrResult(request -> { 51 | if (sameOriginCheck(request)) { 52 | final CompletionStage> future = wsFutureFlow(request); 53 | final CompletionStage>> stage = future.thenApply(Either::Right); 54 | return stage.exceptionally(this::logException); 55 | } else { 56 | return forbiddenResult(); 57 | } 58 | }); 59 | } 60 | 61 | @SuppressWarnings("unchecked") 62 | private CompletionStage> wsFutureFlow(Http.RequestHeader request) { 63 | long id = request.asScala().id(); 64 | UserParentActor.Create create = new UserParentActor.Create(Long.toString(id)); 65 | 66 | return ask(userParentActor, create, t).thenApply((Object flow) -> { 67 | final Flow f = (Flow) flow; 68 | return f.named("websocket"); 69 | }); 70 | } 71 | 72 | private CompletionStage>> forbiddenResult() { 73 | final Result forbidden = Results.forbidden("forbidden"); 74 | final Either> left = Either.Left(forbidden); 75 | 76 | return CompletableFuture.completedFuture(left); 77 | } 78 | 79 | private Either> logException(Throwable throwable) { 80 | logger.error("Cannot create websocket", throwable); 81 | Result result = Results.internalServerError("error"); 82 | return Either.Left(result); 83 | } 84 | 85 | /** 86 | * Checks that the WebSocket comes from the same origin. This is necessary to protect 87 | * against Cross-Site WebSocket Hijacking as WebSocket does not implement Same Origin Policy. 88 | *

89 | * See https://tools.ietf.org/html/rfc6455#section-1.3 and 90 | * http://blog.dewhurstsecurity.com/2013/08/30/security-testing-html5-websockets.html 91 | */ 92 | private boolean sameOriginCheck(Http.RequestHeader rh) { 93 | final Optional origin = rh.header("Origin"); 94 | 95 | if (! origin.isPresent()) { 96 | logger.error("originCheck: rejecting request because no Origin header found"); 97 | return false; 98 | } else if (originMatches(origin.get())) { 99 | logger.debug("originCheck: originValue = " + origin); 100 | return true; 101 | } else { 102 | logger.error("originCheck: rejecting request because Origin header value " + origin + " is not in the same origin: " 103 | + String.join(", ", validOrigins)); 104 | return false; 105 | } 106 | } 107 | 108 | private List validOrigins = Arrays.asList("localhost:9000", "localhost:19001"); 109 | private boolean originMatches(String actualOrigin) { 110 | return validOrigins.stream().anyMatch(actualOrigin::contains); 111 | } 112 | 113 | } 114 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Attempt to set APP_HOME 10 | # Resolve links: $0 may be a link 11 | PRG="$0" 12 | # Need this for relative symlinks. 13 | while [ -h "$PRG" ] ; do 14 | ls=`ls -ld "$PRG"` 15 | link=`expr "$ls" : '.*-> \(.*\)$'` 16 | if expr "$link" : '/.*' > /dev/null; then 17 | PRG="$link" 18 | else 19 | PRG=`dirname "$PRG"`"/$link" 20 | fi 21 | done 22 | SAVED="`pwd`" 23 | cd "`dirname \"$PRG\"`/" >/dev/null 24 | APP_HOME="`pwd -P`" 25 | cd "$SAVED" >/dev/null 26 | 27 | APP_NAME="Gradle" 28 | APP_BASE_NAME=`basename "$0"` 29 | 30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 31 | DEFAULT_JVM_OPTS="" 32 | 33 | # Use the maximum available, or set MAX_FD != -1 to use that value. 34 | MAX_FD="maximum" 35 | 36 | warn () { 37 | echo "$*" 38 | } 39 | 40 | die () { 41 | echo 42 | echo "$*" 43 | echo 44 | exit 1 45 | } 46 | 47 | # OS specific support (must be 'true' or 'false'). 48 | cygwin=false 49 | msys=false 50 | darwin=false 51 | nonstop=false 52 | case "`uname`" in 53 | CYGWIN* ) 54 | cygwin=true 55 | ;; 56 | Darwin* ) 57 | darwin=true 58 | ;; 59 | MINGW* ) 60 | msys=true 61 | ;; 62 | NONSTOP* ) 63 | nonstop=true 64 | ;; 65 | esac 66 | 67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 68 | 69 | # Determine the Java command to use to start the JVM. 70 | if [ -n "$JAVA_HOME" ] ; then 71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 72 | # IBM's JDK on AIX uses strange locations for the executables 73 | JAVACMD="$JAVA_HOME/jre/sh/java" 74 | else 75 | JAVACMD="$JAVA_HOME/bin/java" 76 | fi 77 | if [ ! -x "$JAVACMD" ] ; then 78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 79 | 80 | Please set the JAVA_HOME variable in your environment to match the 81 | location of your Java installation." 82 | fi 83 | else 84 | JAVACMD="java" 85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 86 | 87 | Please set the JAVA_HOME variable in your environment to match the 88 | location of your Java installation." 89 | fi 90 | 91 | # Increase the maximum file descriptors if we can. 92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 93 | MAX_FD_LIMIT=`ulimit -H -n` 94 | if [ $? -eq 0 ] ; then 95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 96 | MAX_FD="$MAX_FD_LIMIT" 97 | fi 98 | ulimit -n $MAX_FD 99 | if [ $? -ne 0 ] ; then 100 | warn "Could not set maximum file descriptor limit: $MAX_FD" 101 | fi 102 | else 103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 104 | fi 105 | fi 106 | 107 | # For Darwin, add options to specify how the application appears in the dock 108 | if $darwin; then 109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 110 | fi 111 | 112 | # For Cygwin, switch paths to Windows format before running java 113 | if $cygwin ; then 114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 116 | JAVACMD=`cygpath --unix "$JAVACMD"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Escape application args 158 | save () { 159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 160 | echo " " 161 | } 162 | APP_ARGS=$(save "$@") 163 | 164 | # Collect all arguments for the java command, following the shell quoting and substitution rules 165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 166 | 167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong 168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then 169 | cd "$(dirname "$0")" 170 | fi 171 | 172 | exec "$JAVACMD" "$@" 173 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | CC0 1.0 Universal 2 | 3 | Statement of Purpose 4 | 5 | The laws of most jurisdictions throughout the world automatically confer 6 | exclusive Copyright and Related Rights (defined below) upon the creator and 7 | subsequent owner(s) (each and all, an "owner") of an original work of 8 | authorship and/or a database (each, a "Work"). 9 | 10 | Certain owners wish to permanently relinquish those rights to a Work for the 11 | purpose of contributing to a commons of creative, cultural and scientific 12 | works ("Commons") that the public can reliably and without fear of later 13 | claims of infringement build upon, modify, incorporate in other works, reuse 14 | and redistribute as freely as possible in any form whatsoever and for any 15 | purposes, including without limitation commercial purposes. These owners may 16 | contribute to the Commons to promote the ideal of a free culture and the 17 | further production of creative, cultural and scientific works, or to gain 18 | reputation or greater distribution for their Work in part through the use and 19 | efforts of others. 20 | 21 | For these and/or other purposes and motivations, and without any expectation 22 | of additional consideration or compensation, the person associating CC0 with a 23 | Work (the "Affirmer"), to the extent that he or she is an owner of Copyright 24 | and Related Rights in the Work, voluntarily elects to apply CC0 to the Work 25 | and publicly distribute the Work under its terms, with knowledge of his or her 26 | Copyright and Related Rights in the Work and the meaning and intended legal 27 | effect of CC0 on those rights. 28 | 29 | 1. Copyright and Related Rights. A Work made available under CC0 may be 30 | protected by copyright and related or neighboring rights ("Copyright and 31 | Related Rights"). Copyright and Related Rights include, but are not limited 32 | to, the following: 33 | 34 | i. the right to reproduce, adapt, distribute, perform, display, communicate, 35 | and translate a Work; 36 | 37 | ii. moral rights retained by the original author(s) and/or performer(s); 38 | 39 | iii. publicity and privacy rights pertaining to a person's image or likeness 40 | depicted in a Work; 41 | 42 | iv. rights protecting against unfair competition in regards to a Work, 43 | subject to the limitations in paragraph 4(a), below; 44 | 45 | v. rights protecting the extraction, dissemination, use and reuse of data in 46 | a Work; 47 | 48 | vi. database rights (such as those arising under Directive 96/9/EC of the 49 | European Parliament and of the Council of 11 March 1996 on the legal 50 | protection of databases, and under any national implementation thereof, 51 | including any amended or successor version of such directive); and 52 | 53 | vii. other similar, equivalent or corresponding rights throughout the world 54 | based on applicable law or treaty, and any national implementations thereof. 55 | 56 | 2. Waiver. To the greatest extent permitted by, but not in contravention of, 57 | applicable law, Affirmer hereby overtly, fully, permanently, irrevocably and 58 | unconditionally waives, abandons, and surrenders all of Affirmer's Copyright 59 | and Related Rights and associated claims and causes of action, whether now 60 | known or unknown (including existing as well as future claims and causes of 61 | action), in the Work (i) in all territories worldwide, (ii) for the maximum 62 | duration provided by applicable law or treaty (including future time 63 | extensions), (iii) in any current or future medium and for any number of 64 | copies, and (iv) for any purpose whatsoever, including without limitation 65 | commercial, advertising or promotional purposes (the "Waiver"). Affirmer makes 66 | the Waiver for the benefit of each member of the public at large and to the 67 | detriment of Affirmer's heirs and successors, fully intending that such Waiver 68 | shall not be subject to revocation, rescission, cancellation, termination, or 69 | any other legal or equitable action to disrupt the quiet enjoyment of the Work 70 | by the public as contemplated by Affirmer's express Statement of Purpose. 71 | 72 | 3. Public License Fallback. Should any part of the Waiver for any reason be 73 | judged legally invalid or ineffective under applicable law, then the Waiver 74 | shall be preserved to the maximum extent permitted taking into account 75 | Affirmer's express Statement of Purpose. In addition, to the extent the Waiver 76 | is so judged Affirmer hereby grants to each affected person a royalty-free, 77 | non transferable, non sublicensable, non exclusive, irrevocable and 78 | unconditional license to exercise Affirmer's Copyright and Related Rights in 79 | the Work (i) in all territories worldwide, (ii) for the maximum duration 80 | provided by applicable law or treaty (including future time extensions), (iii) 81 | in any current or future medium and for any number of copies, and (iv) for any 82 | purpose whatsoever, including without limitation commercial, advertising or 83 | promotional purposes (the "License"). The License shall be deemed effective as 84 | of the date CC0 was applied by Affirmer to the Work. Should any part of the 85 | License for any reason be judged legally invalid or ineffective under 86 | applicable law, such partial invalidity or ineffectiveness shall not 87 | invalidate the remainder of the License, and in such case Affirmer hereby 88 | affirms that he or she will not (i) exercise any of his or her remaining 89 | Copyright and Related Rights in the Work or (ii) assert any associated claims 90 | and causes of action with respect to the Work, in either case contrary to 91 | Affirmer's express Statement of Purpose. 92 | 93 | 4. Limitations and Disclaimers. 94 | 95 | a. No trademark or patent rights held by Affirmer are waived, abandoned, 96 | surrendered, licensed or otherwise affected by this document. 97 | 98 | b. Affirmer offers the Work as-is and makes no representations or warranties 99 | of any kind concerning the Work, express, implied, statutory or otherwise, 100 | including without limitation warranties of title, merchantability, fitness 101 | for a particular purpose, non infringement, or the absence of latent or 102 | other defects, accuracy, or the present or absence of errors, whether or not 103 | discoverable, all to the greatest extent permissible under applicable law. 104 | 105 | c. Affirmer disclaims responsibility for clearing rights of other persons 106 | that may apply to the Work or any use thereof, including without limitation 107 | any person's Copyright and Related Rights in the Work. Further, Affirmer 108 | disclaims responsibility for obtaining any necessary consents, permissions 109 | or other rights required for any use of the Work. 110 | 111 | d. Affirmer understands and acknowledges that Creative Commons is not a 112 | party to this document and has no duty or obligation with respect to this 113 | CC0 or use of the Work. 114 | 115 | For more information, please see 116 | 117 | -------------------------------------------------------------------------------- /app/actors/UserActor.java: -------------------------------------------------------------------------------- 1 | package actors; 2 | 3 | import actors.Messages.Stocks; 4 | import actors.Messages.UnwatchStocks; 5 | import actors.Messages.WatchStocks; 6 | import akka.Done; 7 | import akka.NotUsed; 8 | import akka.actor.AbstractActor; 9 | import akka.actor.Actor; 10 | import akka.actor.ActorRef; 11 | import akka.event.Logging; 12 | import akka.event.LoggingAdapter; 13 | import akka.japi.Pair; 14 | import akka.stream.KillSwitches; 15 | import akka.stream.Materializer; 16 | import akka.stream.UniqueKillSwitch; 17 | import akka.stream.javadsl.*; 18 | import com.fasterxml.jackson.databind.JsonNode; 19 | import com.google.inject.assistedinject.Assisted; 20 | import play.libs.Json; 21 | import stocks.Stock; 22 | 23 | import javax.inject.Inject; 24 | import javax.inject.Named; 25 | import java.time.Duration; 26 | import java.time.temporal.ChronoUnit; 27 | import java.util.Collections; 28 | import java.util.HashMap; 29 | import java.util.Map; 30 | import java.util.Set; 31 | import java.util.concurrent.CompletionStage; 32 | 33 | import static akka.pattern.PatternsCS.ask; 34 | 35 | /** 36 | * The broker between the WebSocket and the StockActor(s). The UserActor holds the connection and sends serialized 37 | * JSON data to the client. 38 | */ 39 | public class UserActor extends AbstractActor { 40 | 41 | private final Duration timeout = Duration.of(5, ChronoUnit.MILLIS); 42 | 43 | private final LoggingAdapter logger = Logging.getLogger(getContext().system(), this); 44 | 45 | private final Map stocksMap = new HashMap<>(); 46 | 47 | private final String id; 48 | private final ActorRef stocksActor; 49 | private final Materializer mat; 50 | 51 | private final Sink hubSink; 52 | private final Flow websocketFlow; 53 | 54 | @Inject 55 | public UserActor(@Assisted String id, 56 | @Named("stocksActor") ActorRef stocksActor, 57 | Materializer mat) { 58 | this.id = id; 59 | this.stocksActor = stocksActor; 60 | this.mat = mat; 61 | 62 | Pair, Source> sinkSourcePair = 63 | MergeHub.of(JsonNode.class, 16) 64 | .toMat(BroadcastHub.of(JsonNode.class, 256), Keep.both()) 65 | .run(mat); 66 | 67 | this.hubSink = sinkSourcePair.first(); 68 | Source hubSource = sinkSourcePair.second(); 69 | 70 | Sink> jsonSink = Sink.foreach((JsonNode json) -> { 71 | // When the user types in a stock in the upper right corner, this is triggered, 72 | String symbol = json.findPath("symbol").asText(); 73 | addStocks(Collections.singleton(symbol)); 74 | }); 75 | 76 | // Put the source and sink together to make a flow of hub source as output (aggregating all 77 | // stocks as JSON to the browser) and the actor as the sink (receiving any JSON messages 78 | // from the browse), using a coupled sink and source. 79 | this.websocketFlow = Flow.fromSinkAndSourceCoupled(jsonSink, hubSource) 80 | //.log("actorWebsocketFlow", logger) 81 | .watchTermination((n, stage) -> { 82 | // When the flow shuts down, make sure this actor also stops. 83 | stage.thenAccept(f -> context().stop(self())); 84 | return NotUsed.getInstance(); 85 | }); 86 | } 87 | 88 | /** 89 | * The receive block, useful if other actors want to manipulate the flow. 90 | */ 91 | @Override 92 | public Receive createReceive() { 93 | return receiveBuilder() 94 | .match(WatchStocks.class, watchStocks -> { 95 | logger.info("Received message {}", watchStocks); 96 | addStocks(watchStocks.symbols); 97 | sender().tell(websocketFlow, self()); 98 | }) 99 | .match(UnwatchStocks.class, unwatchStocks -> { 100 | logger.info("Received message {}", unwatchStocks); 101 | unwatchStocks(unwatchStocks.symbols); 102 | }).build(); 103 | } 104 | 105 | /** 106 | * Adds several stocks to the hub, by asking the stocks actor for stocks. 107 | */ 108 | private void addStocks(Set symbols) { 109 | // Ask the stocksActor for a stream containing these stocks. 110 | CompletionStage future = ask(stocksActor, new WatchStocks(symbols), timeout).thenApply(Stocks.class::cast); 111 | 112 | // when we get the response back, we want to turn that into a flow by creating a single 113 | // source and a single sink, so we merge all of the stock sources together into one by 114 | // pointing them to the hubSink, so we can add them dynamically even after the flow 115 | // has started. 116 | future.thenAccept((Stocks newStocks) -> { 117 | newStocks.stocks.forEach(stock -> { 118 | if (!stocksMap.containsKey(stock.symbol)) { 119 | addStock(stock); 120 | } 121 | }); 122 | }); 123 | } 124 | 125 | /** 126 | * Adds a single stock to the hub. 127 | */ 128 | private void addStock(Stock stock) { 129 | logger.info("Adding stock {}", stock); 130 | 131 | // We convert everything to JsValue so we get a single stream for the websocket. 132 | // Make sure the history gets written out before the updates for this stock... 133 | final Source historySource = stock.history(50).map(Json::toJson); 134 | final Source updateSource = stock.update().map(Json::toJson); 135 | final Source stockSource = historySource.concat(updateSource); 136 | 137 | // Set up a flow that will let us pull out a killswitch for this specific stock, 138 | // and automatic cleanup for very slow subscribers (where the browser has crashed, etc). 139 | final Flow killswitchFlow = Flow.of(JsonNode.class) 140 | .joinMat(KillSwitches.singleBidi(), Keep.right()); 141 | // Set up a complete runnable graph from the stock source to the hub's sink 142 | String name = "stock-" + stock.symbol + "-" + id; 143 | final RunnableGraph graph = stockSource 144 | .viaMat(killswitchFlow, Keep.right()) 145 | .to(hubSink) 146 | .named(name); 147 | 148 | // Start it up! 149 | UniqueKillSwitch killSwitch = graph.run(mat); 150 | 151 | // Pull out the kill switch so we can stop it when we want to unwatch a stock. 152 | stocksMap.put(stock.symbol, killSwitch); 153 | } 154 | 155 | private void unwatchStocks(Set symbols) { 156 | symbols.forEach(symbol -> { 157 | stocksMap.get(symbol).shutdown(); 158 | stocksMap.remove(symbol); 159 | }); 160 | } 161 | 162 | public interface Factory { 163 | Actor create(String id); 164 | } 165 | } 166 | --------------------------------------------------------------------------------