Create a JSON feed of stock prices in Java
The canvas page of your application will display the user's stock portfolio and other available stocks, and will update the prices of those stocks once per second using AJAX. So the first step in this section will be to provide this JSON data. It makes sense to assume that the stock price functionality would already exist in the stock brokerage's application (written in Java), so you will provide this JSON feed from a controller running in IBM WebSphere.
Using StockListController.java to provide stock prices
To get started you must first modify the handleRequests() method in StockListController.java, as shown in Listing 1, so you'll be provided with some stock prices.
Listing 1. Modifying the
StockListController class (Java) to provide stock prices
public ModelAndView handleRequest(HttpServletRequest request,
HttpServletResponse response) throws Exception {
List<Stock> stocks = getDao().fetchAllStocks();
for (Stock stock : stocks) {
stock.setPrice (getStockPriceSource().getPriceInCents(stock.getId()));
}
return new ModelAndView (getSuccessView(), "stocks", stocks);
}
|
Using a StockPriceSource class to simulate stock price movement
Instead of just providing the stocks to the view as fetched from the DAO, StockListController now calls a StockPriceSource object for the price of each stock, because these prices change in real-time as opposed to being database-driven. A real stock brokerage would implement the StockPriceSource class to retrieve the stock prices from some highly-secure and industry-specific data source somewhere. This application, however, will simulate stock price movement with a StockPriceSource class that holds a Map of "stock ticker to price", and every request for a stock's price will update that price in the map, varying it randomly up and down within a set range of volatility (see attached code in Downloads for details).
To provide the StockPriceSource to the StockListController, modify the latter's bean definition in spring-servlet.xml and provide a new one for the StockPriceSource object, as shown in Listing 2.
Listing 2. Providing
StockListController with a StockPriceSource in spring-servlet.xml
<bean id="stockPriceSource" class="com.jm.fbstockdemo.StockPriceSource">
<property name="volatility" value="50"/>
<property name="startPrice" value="5000"/>
<property name="minPrice" value="500"/>
<property name="maxPrice" value="10000"/>
</bean>
<bean id="stockListController" class="com.jm.fbstockdemo.StockListController">
<property name="dao" ref="stocksDao"/>
<property name="stockPriceSource" ref="stockPriceSource"/>
<property name="successView">
<value>stockList.jsp</value>
</property>
</bean>
|
The stockPriceSource bean's properties configure its behavior: all stocks start out with a price of 5000 cents ($50), can vary up to 50 cents per tick (the volatility property), and are not allowed to drop below $5 or go above $100 in their random variation over time. The stockPriceSource property on the stockListController bean provides the latter with the application-wise instance of the former. Because StockPriceSource is a bean, the same instance will remain in memory as long as the Web application or IBM WebSphere is restarted, and so the stock price variation will remain consistent in the Facebook canvas page as long as the app stays running.
Using the JSON JSP tag library to produce the JSON feed
Now that you have a source of stocks and their simulated real-time prices, provide this information as JSON data for the Javascript AJAX calls that will run in the canvas page. JSON (JavaScript Object Notation), whose specification is available at http://www.json.org/, is an alternative format to XML for object data transfer, and is becoming the preference for AJAX data. It is more concise (therefore faster to transmit), provides a straightforward notation for an object's properties (as opposed to XML's mix of attributes and sub-tags), and unlike XML provides an explicit construct for denoting a list of items. These features make it fast, simple, and non-ambiguous to turn JSON data into objects in a language like Javascript that supports objects and arrays.
However, the application's views are JSPs, and JSPs are composed of XML, so use a JSP tag library that lets you construct objects using XML, while the tags render the object data in JSON format. To do that, use the JSON JSP tag library available at http://json-taglib.sourceforge.net/index.html. Download the json-taglib JAR to your WEB-INF/lib directory. Then modify stockList.jsp -- the view rendered by StockListController -- to provide the data in JSON format, as shown in Listing 3.
Listing 3. Using the JSON JSP tag library to render the JSON stock price feed
<%@ page contentType="text" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="json" uri="http://www.atg.com/taglibs/json" %>
<json:object>
<json:array name="stocks">
<c:forEach items="${stocks}" var="stock">
<json:object>
<json:property name="id"><c:out
value="${stock.id}"/></json:property>
<json:property name="ticker"><c:out
value="${stock.ticker}"/></json:property>
<json:property name="price"><c:out
value="${stock.price}"/></json:property>
</json:object>
</c:forEach>
</json:array>
</json:object>
|
A JSON object is composed of name/value pairs, where a value can be a primitive value like a string, another JSON object, or a JSON array. In stockList.jsp, the <json:object> tag creates a JSON object as its top-level wrapper. The <json:array> tag creates a property on the top-level object called stocks that is an array of JSON objects, in this case stocks. The JSP loops through the stocks provided by StockListController to build the JSON array, creating one JSON object per stock, each with an id, ticker and price property.
Note that the contentType here is text so that you can view the results in a browser and debug the Javascript more easily, but it could otherwise be "text/json". Also note that you cannot include <!-- xml comments --> in this JSP, because although they would be ignored if the output were XML, they will be interpreted as broken data when the result is interpreted as JSON.
To test the JSON feed of stock prices, redeploy the Web application to WebSphere (as in Part 2 of this tutorial), go to http://localhost/fb_stock_demo/stockList in your browser, and you will see the stocks and their prices in JSON format. Reload the browser and the stock prices in the JSON data will change, because StockPriceSource is varying their prices with each request.
See this JSON feed in action when you implement the AJAX call in the canvas page's FBJS (Facebook JavaScript). Before you get there though you need to identify the Facebook user viewing the portfolio page, so turn your attention back to the PHP side of the application to connect to Facebook and identify the Facebook user in your DB2 database.





