1 16 17 package samples.stock ; 18 19 import org.w3c.dom.Document ; 20 import org.w3c.dom.Element ; 21 import org.w3c.dom.NodeList ; 22 23 import javax.xml.parsers.DocumentBuilder ; 24 import javax.xml.parsers.DocumentBuilderFactory ; 25 import java.net.URL ; 26 27 33 public class StockQuoteService { 34 public String test() { 35 return( "Just a test" ); 36 } 37 38 public float getQuote (String symbol) throws Exception { 39 43 if ( symbol.equals("XXX") ) return( (float) 55.25 ); 44 45 URL url = new URL ( "http://services.xmethods.net/axis/getQuote?s=" 46 + symbol ); 47 48 DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); 49 DocumentBuilder db = dbf.newDocumentBuilder(); 50 51 Document doc = db.parse( url.toExternalForm() ); 52 Element elem = doc.getDocumentElement(); 53 NodeList list = elem.getElementsByTagName( "stock_quote" ); 54 55 if ( list != null && list.getLength() != 0 ) { 56 elem = (Element ) list.item(0); 57 list = elem.getElementsByTagName( "price" ); 58 elem = (Element ) list.item(0); 59 String quoteStr = elem.getAttribute("value"); 60 try { 61 return Float.valueOf(quoteStr).floatValue(); 62 } catch (NumberFormatException e1) { 63 try { 65 return Integer.valueOf(quoteStr).intValue() * 1.0F; 66 } catch (NumberFormatException e2) { 67 return -1.0F; 68 } 69 } 70 } 71 return( 0 ); 72 } 73 } 74 | Popular Tags |