Project

General

Profile

1 51 jones
/**
2
 *        Name: MetaCatServlet.java
3
 *     Purpose: A Class that implements a metadata catalog as a java Servlet
4
 *   Copyright: 2000 Regents of the University of California and the
5
 *              National Center for Ecological Analysis and Synthesis
6
 *     Authors: Matt Jones
7
 *
8
 *     Version: '$Id$'
9
 */
10
11
package edu.ucsb.nceas.metacat;
12
13 46 jones
import java.io.PrintWriter;
14
import java.io.IOException;
15 50 jones
import java.io.Reader;
16
import java.io.StringReader;
17 59 jones
import java.io.BufferedReader;
18 46 jones
import java.util.Enumeration;
19
import java.util.Hashtable;
20 50 jones
import java.net.URL;
21
import java.net.MalformedURLException;
22
import java.sql.Connection;
23 55 jones
import java.sql.SQLException;
24 46 jones
25
import javax.servlet.ServletConfig;
26
import javax.servlet.ServletContext;
27
import javax.servlet.ServletException;
28 48 jones
import javax.servlet.ServletInputStream;
29 46 jones
import javax.servlet.http.HttpServlet;
30
import javax.servlet.http.HttpServletRequest;
31
import javax.servlet.http.HttpServletResponse;
32 47 jones
import javax.servlet.http.HttpUtils;
33 46 jones
34 50 jones
import oracle.xml.parser.v2.XSLStylesheet;
35
import oracle.xml.parser.v2.XSLException;
36
import oracle.xml.parser.v2.XMLDocumentFragment;
37
import oracle.xml.parser.v2.XSLProcessor;
38 68 higgins
import oracle.xml.parser.v2.*;    //Oracle parser - DFH
39 50 jones
40 46 jones
/**
41
 * A metadata catalog server implemented as a Java Servlet
42 50 jones
   *
43
   * <p>Valid parameters are:<br>
44
   * action=query -- query the values of all elements and attributes
45
   *                     and return a result set of nodes<br>
46
   * action=getdocument -- display an XML document in XML or HTML<br>
47
   * qformat=xml -- display resultset from query in XML<br>
48
   * qformat=html -- display resultset from query in HTML<br>
49
   * action=getdocument -- display an XML document in XML or HTML<br>
50
   * docid=34 -- display the document with the document ID number 34<br>
51 60 jones
   * action=putdocument -- load an XML document into the database store<br>
52
   * doctext -- XML text ofthe document to load into the database<br>
53 68 higgins
   * query -- actual query text (to go with 'action=query')<br>
54
   * action=validate -- vallidate the xml contained in validatetext<br>
55
   * valtext -- XML text to be validated
56 46 jones
 */
57
public class MetaCatServlet extends HttpServlet {
58
59
  private ServletConfig		config = null;
60
  private ServletContext	context = null;
61 55 jones
  Connection 		conn = null;
62 46 jones
  DBSimpleQuery		queryobj = null;
63 49 jones
  DBReader		docreader = null;
64 50 jones
  static  String 	user = MetaCatUtil.user;
65
  static  String 	password = MetaCatUtil.password;
66
  static  String 	defaultDB = MetaCatUtil.defaultDB;
67
  static  String 	resultStyleURL = "file:///home/httpd/html/xmltodb/resultset.xsl";
68 46 jones
69 50 jones
  /**
70
   * Initialize the servlet by creating appropriate database connections
71
   */
72 46 jones
  public void init( ServletConfig config ) throws ServletException {
73
    try {
74
      super.init( config );
75
      this.config = config;
76
      this.context = config.getServletContext();
77 68 higgins
    System.out.println("Servlet Initialize");
78 46 jones
      try {
79 50 jones
        // Open a connection to the database
80 55 jones
        conn = MetaCatUtil.openDBConnection(
81 50 jones
                "oracle.jdbc.driver.OracleDriver",
82
                defaultDB, user, password);
83
84 55 jones
        queryobj = new DBSimpleQuery(conn);
85
        docreader = new DBReader(conn);
86 68 higgins
87 46 jones
      } catch (Exception e) {
88
      }
89
    } catch ( ServletException ex ) {
90
      throw ex;
91
    }
92
  }
93
94 50 jones
  /** Handle "GET" method requests from HTTP clients */
95 46 jones
  public void doGet (HttpServletRequest request, HttpServletResponse response)
96
    throws ServletException, IOException {
97
98 48 jones
    // Process the data and send back the response
99 59 jones
    handleGetOrPost(request, response);
100 48 jones
  }
101
102 50 jones
  /** Handle "POST" method requests from HTTP clients */
103 48 jones
  public void doPost( HttpServletRequest request, HttpServletResponse response)
104
    throws ServletException, IOException {
105
106
    // Process the data and send back the response
107 59 jones
    handleGetOrPost(request, response);
108 48 jones
  }
109
110 49 jones
  /**
111 50 jones
   * Control servlet response depending on the action parameter specified
112 49 jones
   */
113 59 jones
  private void handleGetOrPost(HttpServletRequest request,
114
    HttpServletResponse response)
115 48 jones
    throws ServletException, IOException {
116
117 49 jones
    // Get a handle to the output stream back to the client
118 48 jones
    PrintWriter out = response.getWriter();
119 49 jones
120 59 jones
    String name = null;
121
    String[] value = null;
122
    Hashtable params = new Hashtable();
123
    Enumeration paramlist = request.getParameterNames();
124
    while (paramlist.hasMoreElements()) {
125
      name = (String)paramlist.nextElement();
126
      value = request.getParameterValues(name);
127
      params.put(name,value);
128
    }
129
130 49 jones
    String action = ((String[])params.get("action"))[0];
131 46 jones
132 49 jones
    if (action.equals("query")) {
133
      handleQueryAction(out, params, response);
134
    } else if (action.equals("getdocument")) {
135
      handleGetDocumentAction(out, params, response);
136 55 jones
    } else if (action.equals("putdocument")) {
137
      handlePutDocumentAction(out, params, response);
138 68 higgins
    } else if (action.equals("validate")) {
139
      handleValidateAction(out, params, response);
140 50 jones
    } else {
141
      out.println("Error: action not registered.  Please report this error.");
142 46 jones
    }
143
144 49 jones
    // Close the stream to the client
145 46 jones
    out.close();
146
  }
147 49 jones
148 50 jones
  /**
149
   * Handle the database query request and return a result set, possibly
150
   * transformed from XML into HTML
151
   */
152 49 jones
  private void handleQueryAction(PrintWriter out, Hashtable params,
153
               HttpServletResponse response) {
154
      // Run the query
155
      String query = ((String[])params.get("query"))[0];
156
      Hashtable nodelist = queryobj.findRootNodes(query);
157 50 jones
158
      // Create a buffer to hold the xml result
159
      StringBuffer resultset = new StringBuffer();
160
161 49 jones
      // Print the resulting root nodes
162
      long nodeid;
163 50 jones
      resultset.append("<?xml version=\"1.0\"?>\n");
164
      resultset.append("<resultset>\n");
165
      resultset.append("  <query>" + query + "</query>");
166 49 jones
      Enumeration rootlist = nodelist.keys();
167
      while (rootlist.hasMoreElements()) {
168
        nodeid = ((Long)rootlist.nextElement()).longValue();
169 50 jones
        resultset.append("  <nodeid>" + nodeid + "</nodeid>");
170 49 jones
      }
171 50 jones
      resultset.append("</resultset>");
172
173
      String qformat = ((String[])params.get("qformat"))[0];
174
      if (qformat.equals("xml")) {
175
        // set content type and other response header fields first
176
        response.setContentType("text/xml");
177
        out.println(resultset.toString());
178
      } else if (qformat.equals("html")) {
179
        // set content type and other response header fields first
180
        response.setContentType("text/html");
181
        //out.println("Converting to HTML...");
182
        XMLDocumentFragment htmldoc = null;
183
        try {
184
          XSLStylesheet style = new XSLStylesheet(new URL(resultStyleURL), null);
185
          htmldoc = (new XSLProcessor()).processXSL(style,
186
                     (Reader)(new StringReader(resultset.toString())),null);
187
          htmldoc.print(out);
188
        } catch (Exception e) {
189
          out.println("Error transforming document:\n" + e.getMessage());
190
        }
191
      }
192 49 jones
  }
193
194 50 jones
  /**
195
   * Handle the database getdocument request and return a XML document,
196
   * possibly transformed from XML into HTML
197
   */
198 49 jones
  private void handleGetDocumentAction(PrintWriter out, Hashtable params,
199
               HttpServletResponse response) {
200
      // Get the document indicated
201
      String docid = ((String[])params.get("docid"))[0];
202
      String doc = docreader.readXMLDocument((new Long(docid)).longValue());
203
204
      // set content type and other response header fields first
205
      response.setContentType("text/xml");
206
207
      out.println(doc);
208
  }
209 55 jones
210
  /**
211
   * Handle the database putdocument request and write an XML document
212
   * to the database connection
213
   */
214
  private void handlePutDocumentAction(PrintWriter out, Hashtable params,
215
               HttpServletResponse response) {
216 59 jones
217 55 jones
      // Get the document indicated
218 59 jones
      String[] doctext = (String[])params.get("doctext");
219
      StringReader xml = new StringReader(doctext[0]);
220
221
      // write the document to the database
222 55 jones
      try {
223 59 jones
        DBSAXWriter dbw = new DBSAXWriter(xml, conn);
224 55 jones
      } catch (SQLException e1) {
225 59 jones
          out.println("Error 1 loading document:<p>\n" + e1.getMessage());
226 55 jones
      }catch (IOException e2) {
227 59 jones
          out.println("Error 2 loading document:<p>\n" + e2.getMessage());
228 55 jones
      }catch (ClassNotFoundException e3) {
229 59 jones
          out.println("Error 3 loading document:<p>\n" + e3.getMessage());
230 55 jones
      }
231
232
      // set content type and other response header fields first
233 59 jones
      response.setContentType("text/xml");
234 55 jones
235 59 jones
      out.println(doctext[0]);
236 55 jones
  }
237 68 higgins
238
  /**
239
   * Handle the validtion request and return the results
240
   * to the requestor - DFH
241
   */
242
  private void handleValidateAction(PrintWriter out, Hashtable params, HttpServletResponse response) {
243
244
      // Get the document indicated
245
      String[] valtext = (String[])params.get("valtext");
246
247
248
      SAXParser parser = new SAXParser();           // works for both Xerces and Oracle
249
      parser.setValidationMode(true);               // Oracle
250
      GenericXMLValidate gxv = new GenericXMLValidate(parser);
251
      boolean valid = gxv.validateString(valtext[0]);
252
253
      // set content type and other response header fields first
254
      response.setContentType("text/plain");
255
256
      if (valid) {
257
        out.println("The input XML is VALID!");
258
      }
259
      else {
260
        out.println("The input XML is NOT VALID\n" + gxv.returnErrors());
261
      }
262
    }
263 46 jones
}