FileDocCategorySizeDatePackage
UpdateItemServlet.javaAPI DocExample8433Thu Aug 16 16:59:34 BST 2001javaxml2

UpdateItemServlet.java

/*-- 

 Copyright (C) 2001 Brett McLaughlin.
 All rights reserved.
 
 Redistribution and use in source and binary forms, with or without
 modification, are permitted provided that the following conditions
 are met:
 
 1. Redistributions of source code must retain the above copyright
    notice, this list of conditions, and the following disclaimer.
 
 2. Redistributions in binary form must reproduce the above copyright
    notice, this list of conditions, and the disclaimer that follows 
    these conditions in the documentation and/or other materials 
    provided with the distribution.

 3. The name "Java and XML" must not be used to endorse or promote products
    derived from this software without prior written permission.  For
    written permission, please contact brett@newInstance.com.
 
 In addition, we request (but do not require) that you include in the 
 end-user documentation provided with the redistribution and/or in the 
 software itself an acknowledgement equivalent to the following:
     "This product includes software developed for the
      'Java and XML' book, by Brett McLaughlin (O'Reilly & Associates)."

 THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 DISCLAIMED.  IN NO EVENT SHALL THE JDOM AUTHORS OR THE PROJECT
 CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 SUCH DAMAGE.

 */
package javaxml2;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.xml.sax.SAXException;

// DOM imports
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.DOMImplementation;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;

// Range import
import org.w3c.dom.ranges.DocumentRange;
import org.w3c.dom.ranges.Range;
import org.w3c.dom.ranges.RangeException;

// Parser import
import org.apache.xerces.dom.DOMImplementationImpl;
import org.apache.xerces.parsers.DOMParser;

/**
 * <b><code>UpdateItemServlet</code></b> demonstrates how the DOM
 *   Level 2 Range module can be used for handling range within a document.
 */
public class UpdateItemServlet extends HttpServlet {

    /** The directory to load XML from */
    private static final String ITEMS_DIRECTORY = "c:\\javaxml2\\ch06\\xml\\";

    /**
     * <p>Allow a user to input a new item for the auction.</p>
     */
    public void doGet(HttpServletRequest req, HttpServletResponse res)
        throws ServletException, IOException {

        // Get output
        PrintWriter out = res.getWriter();
        res.setContentType("text/html");

        // Output HTML        
        out.println("<html>");
        out.println(" <head><title>Input/Update Item Listing</title></head>");
        out.println(" <body>");
        out.println("  <h1 align='center'>Input/Update Item Listing</h1>");
        out.println("  <p align='center'>");
        out.println("   <form method='POST' " +
            "action='/javaxml2/servlet/javaxml2.UpdateItemServlet'>");
        out.println("    Item ID (Unique Identifier): <br />");
        out.println("    <input name='id' type='text' maxLength='10' />" +
            "<br /><br />");
        out.println("    Item Name: <br />");
        out.println("    <input name='name' type='text' maxLength='50' />" +
            "<br /><br />");
        out.println("    Item Description: <br />");
        out.println("    <textarea name='description' rows='10' cols='30' " +
            "wrap='wrap' ></textarea><br /><br />");
        out.println("    <input type='reset' value='Reset Form' />  ");
        out.println("    <input type='submit' value='Add/Update Item' />");
        out.println("   </form>");
        out.println("  </p>");
        out.println(" </body>");
        out.println("</html>");
 
        out.close();
    }

    /**
     * <p>Search for the item specified, and either create a new file or
     *   update the existing one. DOM Level 2 Range is used for quicker
     *   replacement of a range of data.</p>
     */
    public void doPost(HttpServletRequest req, HttpServletResponse res)
        throws ServletException, IOException {

        // Get parameter values
        String id = req.getParameterValues("id")[0];
        String name = req.getParameterValues("name")[0];
        String description = req.getParameterValues("description")[0];

        // See if this file exists
        Document doc = null;
        File xmlFile = new File(ITEMS_DIRECTORY + "item-" + id + ".xml");
        String docNS = "http://www.oreilly.com/javaxml2";

        if (!xmlFile.exists()) {
            // Create new DOM tree
            DOMImplementation domImpl = new DOMImplementationImpl();
            doc = domImpl.createDocument(docNS, "item", null);
            Element root = doc.getDocumentElement();
            root.setAttribute("xmlns", docNS);

            // ID of item (as attribute)
            root.setAttribute("id", id);

            // Name of item
            Element nameElement = doc.createElementNS(docNS, "name");
            Text nameText = doc.createTextNode(name);
            nameElement.appendChild(nameText);
            root.appendChild(nameElement);

            // Description of item
            Element descriptionElement = doc.createElementNS(docNS, "description");
            Text descriptionText = doc.createTextNode(description);
            descriptionElement.appendChild(descriptionText);
            root.appendChild(descriptionElement);
        } else {
            // Load document
            try {
                DOMParser parser = new DOMParser();
                parser.parse(xmlFile.toURL().toString());
                doc = parser.getDocument();

                Element root = doc.getDocumentElement();
   
                // Name of item
                NodeList nameElements = root.getElementsByTagNameNS(docNS, "name");
                Element nameElement = (Element)nameElements.item(0);
                Text nameText = (Text)nameElement.getFirstChild();
                nameText.setData(name);
            
                // Description of item
                NodeList descriptionElements = 
                    root.getElementsByTagNameNS(docNS, "description");
                Element descriptionElement = (Element)descriptionElements.item(0);

                // Remove and recreate description
                Range range = ((DocumentRange)doc).createRange();
                range.setStartBefore(descriptionElement.getFirstChild());
                range.setEndAfter(descriptionElement.getLastChild());
                range.deleteContents();
                Text descriptionText = doc.createTextNode(description);
                descriptionElement.appendChild(descriptionText);
            } catch (SAXException e) {
                // Print error
                PrintWriter out = res.getWriter();
                res.setContentType("text/html");
                out.println("<HTML><BODY>Error in reading XML: " +
                    e.getMessage() + ".</BODY></HTML>");
                out.close(); 
                return;
            }
        }

        // Serialize DOM tree
        DOMSerializer serializer = new DOMSerializer();
        serializer.serialize(doc, xmlFile);

        // Print confirmation
        PrintWriter out = res.getWriter();
        res.setContentType("text/html");
        out.println("<HTML><BODY>Thank you for your submission. " +
            "Your item has been processed.</BODY></HTML>");
        out.close();        
    }
}