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