Handouts from Web Services 2 (Dave Stampf)

Circle.java


public class Circle {

    private double radius;

    public Circle() {
        this(1.0);
    }

    public Circle(double r) {
        setRadius(r);
    }

    public void setRadius(double r) {
        assert r >= 0.0 : "radius must be >= 0.0";
        radius = r;
    }

    public double getRadius() {
        return radius;
    }

    public double getArea() {
        return Math.PI*radius*radius;
    }

    public boolean equals(Object o) {
        return radius == ((Circle)o).getRadius();
    }

    public String toString() {
        return "Circle with radius " + radius;
    }

    public static void main(String[] args) {
        Circle c1 = new Circle(1.0);
        Circle c2 = new Circle();
        System.out.println(c1 + " has area " + c1.getArea());
        if (c1.equals(c2))
            System.out.println(c1 + " " + c2 + " are equal");
        Circle c3 = new Circle(-4.0);
    }
}

DesignPatterns.xml

<?xml version="1.0" encoding="UTF-8"?>

<!--
    Document   : DesignPatterns.xml
    Created on : September 7, 2003, 12:52 PM
    Author     : Dave Stampf
    Description:
        Purpose of the document follows.
-->

<book isbn="0-201-633511-2">
    <title>Design Patterns</title>
    <subtitle>Elements of Reusable Object-Oriented Software</subtitle>
    <author>Eric Gamma</author>
    <author>Richard Helm</author>
    <author>Ralph Johnson</author>
    <author>John Vlissides</author>
    <publisher>Addison-Wesley Publishing Company</publisher>
    <copyright>1995</copyright>
    <hardcover />

</book>

Pruner.java

/*
 * Pruner.java
 *
 * This is a content handler for SAX. It prunes and XML tree at a collection of
 * named elements.
 *
 * Created on September 20, 2003, 5:21 PM
 */

import java.util.*;
import java.io.*;
import javax.xml.parsers.*;
import org.xml.sax.*;


public class Pruner implements ContentHandler {

    private Vector pruneAt;     // elements to prune
    private PrintStream ps;     // where the output goes
    private boolean skip = false;   // skipping pruned parts
    private String skipTo = ""; // what started the pruning

    /** Creates a new instance of Pruner */
    public Pruner() {
        pruneAt = new Vector();
    }

    public void addPrunePoint(String s) {
        pruneAt.add(s);
    }

    public void setOutputStream(OutputStream os) {
        ps = new PrintStream(os);
    }

    public void startDocument() throws SAXException {
        ps.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
    }


    public void characters(char[] ch, int start, int length) throws SAXException {
        if (!skip) {    // if not skipping, copy characters
            for (int i = start; i < start+length; i++) {
                ps.print(ch[i]);
            }
        }
    }

    public void endDocument() throws SAXException {
        ps.close();
    }

    public void endElement(String namespaceURI, String localName, String qName) throws SAXException { 
        if (skip & skipTo.equals(qName)) {  // see if it is time to stop skip
            skip = false;
        } else {
            ps.println("\n</" + qName + ">");
        }
    }


    public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException {
        if (!skip) {    // if we aren't skipping, see if we should
            if (this.pruneAt.contains(qName)) {
                skip = true;
                skipTo = qName;
            } else {    // otherwise, ouput start of element
                ps.print("<" + qName + " ");
                if (atts != null) {
                    for (int i = 0; i < atts.getLength(); i++) {
                        ps.print(atts.getQName(i) + "=\"" + atts.getValue(i) + "\"");
                    }
                }
                ps.println(">");
            }
        }
    }

    public void startPrefixMapping(String prefix, String uri) throws SAXException {
    }

    public void endPrefixMapping(String prefix) throws SAXException {
    }

    public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException {
    }

    public void processingInstruction(String target, String data) throws SAXException {
    }

    public void setDocumentLocator(Locator locator) {
    }

    public void skippedEntity(String name) throws SAXException {
    }

    // test the Prune content handler.

    public static void main(String[] args) throws Exception {

        Pruner p = new Pruner();
        p.setOutputStream(System.out);
        p.addPrunePoint("author");

        SAXParserFactory spf = SAXParserFactory.newInstance();
        SAXParser sp = spf.newSAXParser();
        XMLReader xr = sp.getXMLReader();

        xr.setContentHandler(p);

        Reader r = new FileReader("C:/WebServicesTutorial/DesignPatternsWithDTD.xml");
        InputSource is = new InputSource(r);
        xr.parse(is);
    }
}

PrunedBook.java

/*
 * PrunedBook.java
 *
 * Created on September 20, 2003, 6:01 PM
 */

import java.io.*;
import javax.xml.parsers.*;
import org.xml.sax.*;
import org.w3c.dom.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;

public class PrunedBook {

    private PipedOutputStream pos;
    private PipedInputStream pis;

    private Pruner pruner;
    private InputSource is;

    /** Creates a new instance of PrunedBook */
    public PrunedBook() throws Exception {

        // create a pipe for the two threads - the pruner and me

        pos = new PipedOutputStream();
        pis = new PipedInputStream(pos);

        // create the Pruner

        pruner = new Pruner();
        pruner.setOutputStream(pos);
        pruner.addPrunePoint("author");

        // access the XML file

        Reader r = new FileReader("C:/WebServicesTutorial/DesignPatternsWithDTD.xml");
        is = new InputSource(r);

        // OK - let the pruner do its work in a separate thread.

        (new Thread(new Runnable () {
            public void run() {
                try {
                    SAXParserFactory spf = SAXParserFactory.newInstance();
                    SAXParser sp = spf.newSAXParser();
                    XMLReader xr = sp.getXMLReader();

                    xr.setContentHandler(pruner);
                    xr.parse(is);
                } catch (Exception e) {
                }
            }
        })).start();

        // while the pruner is working, one can start up DOM

    }

    public void process() throws Exception {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        InputSource is = new InputSource(pis);

        Document doc = db.parse(is);

        // transform into output again

        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer t = tf.newTransformer();
        t.transform(new DOMSource(doc), new StreamResult(System.out));
    }

    public static void main(String[] args) throws Exception {
       PrunedBook pb = new PrunedBook();
       pb.process();
    }
}

Walk.java

import java.io.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;
import org.xml.sax.InputSource;
import org.w3c.dom.*;

public class Walk {

    public Walk(Reader r) throws Exception {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setValidating(true);
        DocumentBuilder db = dbf.newDocumentBuilder();
        InputSource is = new InputSource(r);

        Document doc = db.parse(is);
        Node root = doc.getDocumentElement();
        walkTheDoc(root,0);
    }

    private void walkTheDoc(Node n, int in) throws Exception {
        // ignore white space
        if (n.getNodeName().equals("#text")) {
            if (n.getNodeValue().trim().length() == 0) return;
        }
        indent(in);
        System.out.print(n.getNodeName());
        if (n.getNodeValue() != null) {
            System.out.print(": " + n.getNodeValue());
        }
        System.out.println();
        NamedNodeMap nnm = n.getAttributes();
        if (nnm != null) {
            for (int j = 0; j < nnm.getLength(); j++) {
                indent(in+1);
                Node attr = nnm.item(j);
                System.out.println(attr.getNodeName() + ": " + attr.getNodeValue());
            }
        }

        NodeList nl = n.getChildNodes();
        if (nl == null) return;
        for (int i = 0; i < nl.getLength(); i++) {
            Node child = nl.item(i);
            walkTheDoc(child, in+2);
        }
    }

    private void indent(int n) {
        while (n-- > 0) System.out.print(" ");
    }

    public static void main(String[] args) throws Exception{
        Reader r = new FileReader("C:/WebServicesTutorial/DesignPatternsWithDTD.xml");
        Walk b = new Walk(r);
    }
}

index.html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<HTML>
  <HEAD>
    <TITLE>Test1 Main page</TITLE>
  </HEAD>
  <BODY>
    Hello, world!
  </BODY>
</HTML>

index.jsp

<%@page contentType="text/html"%>
<html>
<head><title>JSP Page</title></head>
<body>

<%-- <jsp:useBean id="beanInstanceName" scope="session" class="package.class" /> --%>
<%-- <jsp:getProperty name="beanInstanceName"  property="propertyName" /> --%>

Hello - from a JSP!
Welcome to visitor from

<%= request.getRemoteHost() %>.


</body>
</html>

Test1Servlet.java

/*
 * Test1Servlet.java
 *
 * Created on September 21, 2003, 10:29 PM
 */

import java.io.*;
import java.net.*;

import javax.servlet.*;
import javax.servlet.http.*;

/**
 *
 * @author  Dave Stampf
 * @version
 */
public class Test1Servlet extends HttpServlet {

    /** Initializes the servlet.
     */
    public void init(ServletConfig config) throws ServletException {
        super.init(config);

    }

    /** Destroys the servlet.
     */
    public void destroy() {

    }

    /** Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        /* output your page here */
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet</title>");
        out.println("</head>");
        out.println("<body>");
         out.println("Hello from a servlet");
        out.println("</body>");
        out.println("</html>");
         /**/
        out.close();
    }

    /** Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /** Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /** Returns a short description of the servlet.
     */
    public String getServletInfo() {
        return "Short description";
    }

}

Arithmetic.html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<HTML>
  <HEAD>
    <TITLE>Let's do some addition!</TITLE>
  </HEAD>
  <BODY>
    <FORM action="sum">
        First Number <INPUT type="TEXT" name="x"> <P>
        Second Number <INPUT type="TEXT" name="y"><P>
        <INPUT type="SUBMIT">
    </FORM>

  </BODY>
</HTML>

AddUp.java

/*
 * AddUp.java
 *
 * Created on September 21, 2003, 10:55 PM
 */

import java.io.*;
import java.net.*;

import javax.servlet.*;
import javax.servlet.http.*;

/**
 *
 * @author  Dave Stampf
 * @version
 */
public class AddUp extends HttpServlet {

    /** Initializes the servlet.
     */
    public void init(ServletConfig config) throws ServletException {
        super.init(config);

    }

    /** Destroys the servlet.
     */
    public void destroy() {

    }

    /** Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();

        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet</title>");
        out.println("</head>");
        out.println("<body>");
         out.println("The sum is: ");

         int x = Integer.parseInt(request.getParameter("x"));
         int y = Integer.parseInt(request.getParameter("y"));
         out.println(x + y);
        out.println("</body>");
        out.println("</html>");

        out.close();
    }

    /** Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /** Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /** Returns a short description of the servlet.
     */
    public String getServletInfo() {
        return "Short description";
    }

}


Thomas G. Throwe
Last modified: Mon Sep 22 11:31:23 EDT 2003