Example 6-17: Servlet to convert Yahoo quotes to XML quotes in real time

import javax.servlet.http.*;
import oracle.xml.parser.v2.*;
import java.net.URL;
import javax.servlet.*;
import java.io.*;
import JTidyConverter;

public class YahooXMLQuotesServlet extends HttpServlet {
  JTidyConverter jtc   = null;
  XSLStylesheet  sheet = null;

  protected void doGet(HttpServletRequest req, HttpServletResponse resp)
  throws ServletException, IOException {
    String YahooQuotesURL = "http://quote.yahoo.com/q?d2=v1&o=d&s=";
    String quotes = req.getParameter("symbols");
    // First, tell the requestor we're sending her XML data as the response.
    resp.setContentType("text/xml");
    // Then, get the Servlet's output Writer to write the response into.
    PrintWriter out = resp.getWriter();
    if (quotes != null) {
      URL yahooUrl  = new URL(YahooQuotesURL+quotes.replace(',','+'));
      try {
        // Convert the dynamically-produced Yahoo Quotes page to XML doc
        XMLDocument yahooquotes = jtc.XMLifyHTMLFrom(yahooUrl);
        // Transform the document using our stylesheet into <QuoteStream>
        // and let the XSLT Processor write the result to our 'out' Writer
        XSLProcessor xslt       = new XSLProcessor();
        xslt.processXSL(sheet,yahooquotes,out);
      }
      catch (Exception ex) {out.println("<error>"+ex.getMessage()+"</error>");}
    }
    else { out.println("<error>No Symbols Provided</error>"); }
  }

  public void init(ServletConfig sc) throws ServletException {
    super.init(sc);
    // Make sure the Servlet can "see" through the corporate firewall...
    System.setProperty("proxySet","true");
    System.setProperty("proxyHost","yourproxyserver.you.com");
    System.setProperty("proxyPort","80");
    // Construct a JTidyConverter. We can use the same one over and over.
    jtc   = new JTidyConverter();
    try {
      // Read the Yahoo2Xml.xsl stylesheet from the CLASSPATH as a resource.
      InputStream styleSource =
         getClass().getResourceAsStream("YahooQuotes-to-QuoteStream.xsl");
      if (styleSource == null) {
        throw new ServletException("YahooQuotes-to-QuoteStream.xsl not found.");
      }
      // Cache a new stylesheet. Note: XSLStylesheet object is not threadsafe
      // in Oracle XSLT Processor 2.0.2.7, but ok for this demo
      sheet = new XSLStylesheet(styleSource,null); // No base URL needed here!
    }
    catch (XSLException xslx) {
      throw new ServletException("Error preparing XSLT stylesheet.");
    }
  }
}