Webreference-Getting out of the Sandbox: Building an Applet Proxy Server | 5
Putting It All Together: Quotron
Quotron is a tiny Java applet that relies on the Applet Proxy Server to contract the Yahoo stock quote service and get the value and change amount for a particular stock symbol. It can take a stock description and symbol as parameters in the <APPLET> tag, making it easy to configure. Yahoo provides a particularly simple text format (CSV, comma-separated values) that is meant for use in Excel, but also serves this process well. A URL like
https://quote.yahoo.com/d/quotes.csv?symbols=MSFT&format=sl1d1t1c1ohgv&ext=.csv
returns a screen with the contents:
"MSFT",138.5,"10/21/1997","4:01PM",+5.875,136.125,139.234,135.312,14460300
which, as you'll see below, you can parse very easily using the built-in text tools in Java to get out the stock fields you want (the second and the fifth in the case of Quotron).
The new generation of graphical user interface "painters" for Java make it relatively easy to create simple applets without knowing much about AWT, Java's GUI system. I created the interface for Quotron in Visual Café quickly, and then added the necessary code to call HttpProxyConnection to get the stock data. Since the whole point of using an applet is to take advantage of continuous updates (though not too often: with 20 minute delay on stock quotes, there is no point in polluting the network by checking the stock value every second), Quotron uses an independently-running thread that repeatedly calls getStockValue() in a loop, which is the only complication in the code.
The getStockValue() method fetches from the Yahoo URL (which has already been set up with the correct symbol in the CGI arguments) using the proxy connection. It should get back a line of comma-delimited data that includes the current stock value and its change. The rest of the method simply parses out this string to get the value and sets the text fields in the applet's user interface. It also adds a piece of logic to color-code positive or negative changes in the stock.
public String getStockValue() { InputStream stockData = null; try { HttpProxyConnection proxyConnection = new HttpProxyConnection(getCodeBase().getHost()); byte[] buffer = proxyConnection.fetch(stockServerUrl); // create a string representing the array String dataString = new String(buffer, 0); int currentValStart = dataString.indexOf(","); int currentValEnd = dataString.indexOf(",", currentValStart + 1); int valDeltaStart = dataString.indexOf(",", currentValEnd + 17); int valDeltaEnd = dataString.indexOf(",", valDeltaStart + 1); String deltaVal = dataString.substring(valDeltaStart + 1, valDeltaEnd); stockSymbolValue.setText(dataString.substring(currentValStart + 1, currentValEnd)); stockDelta.setText(deltaVal); if (Float.valueOf(deltaVal).floatValue()
Comments are welcome
Created: Oct. 27, 1997Revised: Oct. 30, 1997
URL: https://webreference.com/dev/proxy/quotron2.html