Typesafe Activator

Reactive Stocks

Reactive Stocks

Typesafe
Source
July 26, 2014
sample java scala playframework akka reactive

The Reactive Stocks application uses Java, Scala, Play Framework, and Akka to illustrate a reactive app. The tutorial in this example will teach you the reactive basics including Reactive Composition and Reactive Push.

How to get "Reactive Stocks" on your computer

There are several ways to get this template.

Option 1: Choose reactive-stocks in the Typesafe Activator UI.

Already have Typesafe Activator (get it here)? Launch the UI then search for reactive-stocks in the list of templates.

Option 2: Download the reactive-stocks project as a zip archive

If you haven't installed Activator, you can get the code by downloading the template bundle for reactive-stocks.

  1. Download the Template Bundle for "Reactive Stocks"
  2. Extract the downloaded zip file to your system
  3. The bundle includes a small bootstrap script that can start Activator. To start Typesafe Activator's UI:

    In your File Explorer, navigate into the directory that the template was extracted to, right-click on the file named "activator.bat", then select "Open", and if prompted with a warning, click to continue:

    Or from a command line:

     C:\Users\typesafe\reactive-stocks> activator ui 
    This will start Typesafe Activator and open this template in your browser.

Option 3: Create a reactive-stocks project from the command line

If you have Typesafe Activator, use its command line mode to create a new project from this template. Type activator new PROJECTNAME reactive-stocks on the command line.

Option 4: View the template source

The creator of this template maintains it at https://github.com/typesafehub/reactive-stocks#master.

Option 5: Preview the tutorial below

We've included the text of this template's tutorial below, but it may work better if you view it inside Activator on your computer. Activator tutorials are often designed to be interactive.

Preview the tutorial

The Reactive Stocks application has been created!

Explore the App

Once the application has been compiled and the server started, your application can be accessed at: http://localhost:9000
Check in Run to see the server status.

The first thing you will see are three stock charts which are being pushed values in real-time from the server. These values are simulated so the application always has interesting data flowing in real-time. Clicking on a stock chart will fetch recent news mentioning the stock symbol, use a service to do sentiment analysis on each news, and then display a buy, sell, or hold recommendation based on the aggregate sentiments. New stocks can be added to the list using the form in the header.

Reactive Apps

As The Reactive Manifesto outlines, Reactive apps are Resilient, Interactive, Scalable, and Event-Driven. The Reactive Stocks application has all of these characteristics because it is built using the Typesafe Platform, including Play Framework for the web interface and Akka for managing concurrency, scalability and fault-tolerance. Both Java and Scala are for the back-end code since Play and Akka support both of those languages. Any piece written in Java could have been written in Scala, or vice-versa. The front-end uses HTML, LESS (compiled to CSS), and CoffeeScript (compiled to JavaScript). WebSockets are used to push data in real-time from the server to the client.

The Reactive Stocks application showcases four types of Reactive: Reactive Push, Reactive Requests, Reactive Composition, and Reactive UIs. Two types of Reactive which are not directly used in this application are Reactive Pull and 2-way Reactive. In a real stock feed application, the stock stream would be attached to an actual stock feed service using Reactive Pull. Those values would then be pushed to the client using Reactive Push. The combination of Reactive Push & Reactive Pull is 2-way Reactive. Play's internal network handling is 2-way Reactive.

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:

GET /ws controllers.Application.ws
The ws method in the Application.java controller handles the request and does the protocol upgrade to the WebSocket connection. This method create a new UserActor defined in UsersActor.java ( tests). 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.scala ( tests). 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 using the newPrice method in the FakeStockQuote.java file. Every StockActor sends itself a FetchLatest message every 75 milliseconds. Once a new price is generated it is added to the history and then a message is sent to each UserActor that is watching the stock. The UserActor then serializes the data as JSON and pushes it to the client using the WebSocket.

Underneath the covers, resources (threads) are only allocated to the Actors and WebSockets when they are needed. This is why Reactive Push is scalable with Play and Akka.

Reactive UI - Real-time Chart

On the client-side a Reactive UI updates the stock charts every time a message is received. The index.scala.html file produces the web page at http://localhost:9000 and loads the JavaScript and CSS needed render the page and setup the UI.

The JavaScript for the page is compiled from the index.coffee file which is written in CoffeeScript (an elegant way to write JavaScript). Using jQuery, a page ready handler sets up the WebSocket connection and sets up functions which will be called when the server sends a message to the client through the WebSocket:

$ ->
  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:

GET /sentiment/:symbol controllers.StockSentiment.get(symbol)
A GET request to /sentiment/GOOG will call get("GOOG") on the StockSentiment.scala controller. That method begins with:
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:

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.

Inspect the App

Use Inspect to see the requests that have been handled by the running Play application and to see the Akka Actors (if any) in the Actor System. Drilling down into an individual request will provide details about the request. Drilling down into an individual Actor will display a number of statistics and information about the Actor. Deviations will show you any issues with your Actors.

Further Learning

The Reactive Stocks example combines Reactive Push, Reactive Requests, Reactive Composition, and a Reactive UI to create a Resilient, Interactive, Scalable, and Event-Driven application. Check out the Hello Scala!, Hello Play Framework!, and Hello Akka! templates to learn more about those technologies. Go back to the Activator home page to create a new application.

comments powered by Disqus