KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > samples > stock > StockQuoteService


1 /*
2  * Copyright 2001-2004 The Apache Software Foundation.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */

16
17 package samples.stock ;
18
19 import org.w3c.dom.Document JavaDoc;
20 import org.w3c.dom.Element JavaDoc;
21 import org.w3c.dom.NodeList JavaDoc;
22
23 import javax.xml.parsers.DocumentBuilder JavaDoc;
24 import javax.xml.parsers.DocumentBuilderFactory JavaDoc;
25 import java.net.URL JavaDoc;
26
27 /**
28  * See \samples\stock\readme for info.
29  *
30  * @author Sanjiva Weerawarana (sanjiva@watson.ibm.com)
31  * @author Doug Davis (dug@us.ibm.com)
32  */

33 public class StockQuoteService {
34   public String JavaDoc test() {
35     return( "Just a test" );
36   }
37
38   public float getQuote (String JavaDoc symbol) throws Exception JavaDoc {
39     // get a real (delayed by 20min) stockquote from
40
// http://services.xmethods.net/axis/. The IP addr
41
// below came from the host that the above form posts to ..
42

43     if ( symbol.equals("XXX") ) return( (float) 55.25 );
44
45     URL JavaDoc url = new URL JavaDoc( "http://services.xmethods.net/axis/getQuote?s="
46                                 + symbol );
47
48     DocumentBuilderFactory JavaDoc dbf = DocumentBuilderFactory.newInstance();
49     DocumentBuilder JavaDoc db = dbf.newDocumentBuilder();
50
51     Document JavaDoc doc = db.parse( url.toExternalForm() );
52     Element JavaDoc elem = doc.getDocumentElement();
53     NodeList JavaDoc list = elem.getElementsByTagName( "stock_quote" );
54
55     if ( list != null && list.getLength() != 0 ) {
56       elem = (Element JavaDoc) list.item(0);
57       list = elem.getElementsByTagName( "price" );
58       elem = (Element JavaDoc) list.item(0);
59       String JavaDoc quoteStr = elem.getAttribute("value");
60       try {
61         return Float.valueOf(quoteStr).floatValue();
62       } catch (NumberFormatException JavaDoc e1) {
63         // maybe its an int?
64
try {
65           return Integer.valueOf(quoteStr).intValue() * 1.0F;
66         } catch (NumberFormatException JavaDoc e2) {
67           return -1.0F;
68         }
69       }
70     }
71     return( 0 );
72   }
73 }
74
Popular Tags