Package actors

Source Code of actors.UserActor

package actors;

import akka.actor.UntypedActor;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import play.Play;
import play.libs.Json;
import play.mvc.WebSocket;

import java.util.List;

/**
* 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 UntypedActor {

    private final WebSocket.Out<JsonNode> out;
   
    public UserActor(WebSocket.Out<JsonNode> out) {
        this.out = out;
       
        // watch the default stocks
        List<String> defaultStocks = Play.application().configuration().getStringList("default.stocks");

        for (String stockSymbol : defaultStocks) {
            StocksActor.stocksActor().tell(new WatchStock(stockSymbol), getSelf());
        }
    }
   
    public void onReceive(Object message) {
        if (message instanceof StockUpdate) {
            // push the stock to the client
            StockUpdate stockUpdate = (StockUpdate)message;
            ObjectNode stockUpdateMessage = Json.newObject();
            stockUpdateMessage.put("type", "stockupdate");
            stockUpdateMessage.put("symbol", stockUpdate.symbol());
            stockUpdateMessage.put("price", stockUpdate.price().doubleValue());
            out.write(stockUpdateMessage);
        }
        else if (message instanceof StockHistory) {
            // push the history to the client
            StockHistory stockHistory = (StockHistory)message;

            ObjectNode stockUpdateMessage = Json.newObject();
            stockUpdateMessage.put("type", "stockhistory");
            stockUpdateMessage.put("symbol", stockHistory.symbol());

            ArrayNode historyJson = stockUpdateMessage.putArray("history");
            for (Object price : stockHistory.history()) {
                historyJson.add(((Number)price).doubleValue());
            }
           
            out.write(stockUpdateMessage);
        }
    }
}
TOP

Related Classes of actors.UserActor

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.