package samples.services.stockquote;

import java.net.URL;
import java.io.*;
import org.w3c.dom.*;
import org.xml.sax.*;
import javax.xml.parsers.*;
import org.apache.soap.util.xml.*;


/**
 * This sample is taken from ApacheSOAP and changed to get
 *  JAXP document builder directly (no need for Apache SOAP classes).
 *
 * @author Alekander Slominski (aslom@watson.ibm.com)
 * @author Sanjiva Weerawarana (sanjiva@watson.ibm.com)
 */
public class StockQuote {
  
  public float getQuote (String symbol) throws Exception {
    

    if (symbol.equalsIgnoreCase("XXX"))
      return 3.14f;

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder xdb= factory.newDocumentBuilder();
    
    // get a real (delayed by 20min) stockquote from
    // http://www.xmltoday.com/examples/stockquote/. The IP addr
    // below came from the host that the above form posts to ..
    URL url = new URL ("http://www.xmltoday.com/examples/stockquote/getxmlquote.vep?s="+symbol);
    InputStream is = url.openStream ();
    Document d = xdb.parse(is);
    Element e = d.getDocumentElement ();
    NodeList nl = e.getElementsByTagName ("price");
    e = (Element) nl.item (0);
    String quoteStr = e.getAttribute ("value");
    try {
      return Float.valueOf (quoteStr).floatValue ();
    } catch (NumberFormatException e1) {
      // mebbe its an int?
      try {
        return Integer.valueOf (quoteStr).intValue () * 1.0F;
      } catch (NumberFormatException e2) {
        return -1.0F;
      }
    }
  }
}

