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 46 jones
import java.util.Enumeration;
18
import java.util.Hashtable;
19 50 jones
import java.net.URL;
20
import java.net.MalformedURLException;
21
import java.sql.Connection;
22 46 jones
23
import javax.servlet.ServletConfig;
24
import javax.servlet.ServletContext;
25
import javax.servlet.ServletException;
26 48 jones
import javax.servlet.ServletInputStream;
27 46 jones
import javax.servlet.http.HttpServlet;
28
import javax.servlet.http.HttpServletRequest;
29
import javax.servlet.http.HttpServletResponse;
30 47 jones
import javax.servlet.http.HttpUtils;
31 46 jones
32 50 jones
import oracle.xml.parser.v2.XSLStylesheet;
33
import oracle.xml.parser.v2.XSLException;
34
import oracle.xml.parser.v2.XMLDocumentFragment;
35
import oracle.xml.parser.v2.XSLProcessor;
36
37 46 jones
/**
38
 * A metadata catalog server implemented as a Java Servlet
39 50 jones
   *
40
   * <p>Valid parameters are:<br>
41
   * action=query -- query the values of all elements and attributes
42
   *                     and return a result set of nodes<br>
43
   * action=getdocument -- display an XML document in XML or HTML<br>
44
   * qformat=xml -- display resultset from query in XML<br>
45
   * qformat=html -- display resultset from query in HTML<br>
46
   * action=getdocument -- display an XML document in XML or HTML<br>
47
   * docid=34 -- display the document with the document ID number 34<br>
48 46 jones
 */
49
public class MetaCatServlet extends HttpServlet {
50
51
  private ServletConfig		config = null;
52
  private ServletContext	context = null;
53
  DBSimpleQuery		queryobj = null;
54 49 jones
  DBReader		docreader = null;
55 50 jones
  static  String 	user = MetaCatUtil.user;
56
  static  String 	password = MetaCatUtil.password;
57
  static  String 	defaultDB = MetaCatUtil.defaultDB;
58
  static  String 	resultStyleURL = "file:///home/httpd/html/xmltodb/resultset.xsl";
59 46 jones
60 50 jones
  /**
61
   * Initialize the servlet by creating appropriate database connections
62
   */
63 46 jones
  public void init( ServletConfig config ) throws ServletException {
64
    try {
65
      super.init( config );
66
      this.config = config;
67
      this.context = config.getServletContext();
68
69
      try {
70 50 jones
        // Open a connection to the database
71
        Connection dbconn = MetaCatUtil.openDBConnection(
72
                "oracle.jdbc.driver.OracleDriver",
73
                defaultDB, user, password);
74
75
        queryobj = new DBSimpleQuery(dbconn);
76
        docreader = new DBReader(dbconn);
77 46 jones
      } catch (Exception e) {
78
      }
79
    } catch ( ServletException ex ) {
80
      throw ex;
81
    }
82
  }
83
84 50 jones
  /** Handle "GET" method requests from HTTP clients */
85 46 jones
  public void doGet (HttpServletRequest request, HttpServletResponse response)
86
    throws ServletException, IOException {
87
88 47 jones
    // Get the parameters from the form
89
    String querystring = request.getQueryString();
90
    Hashtable params = HttpUtils.parseQueryString(querystring);
91
92 48 jones
    // Process the data and send back the response
93
    handleGetOrPost(response, params);
94
  }
95
96 50 jones
  /** Handle "POST" method requests from HTTP clients */
97 48 jones
  public void doPost( HttpServletRequest request, HttpServletResponse response)
98
    throws ServletException, IOException {
99
100
    // Get the input data from the client
101
    ServletInputStream in = request.getInputStream();
102
    int len = request.getContentLength();
103
104
    // Parse the input data into a Hashtable
105
    Hashtable params = HttpUtils.parsePostData(len, in);
106
107
    // Process the data and send back the response
108
    handleGetOrPost(response, params);
109
  }
110
111 49 jones
  /**
112 50 jones
   * Control servlet response depending on the action parameter specified
113 49 jones
   */
114 48 jones
  private void handleGetOrPost(HttpServletResponse response, Hashtable params)
115
    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
    String action = ((String[])params.get("action"))[0];
121 46 jones
122 49 jones
    if (action.equals("query")) {
123
      handleQueryAction(out, params, response);
124
    } else if (action.equals("getdocument")) {
125
      handleGetDocumentAction(out, params, response);
126 50 jones
    } else {
127
      out.println("Error: action not registered.  Please report this error.");
128 46 jones
    }
129
130 49 jones
    // Close the stream to the client
131 46 jones
    out.close();
132
  }
133 49 jones
134 50 jones
  /**
135
   * Handle the database query request and return a result set, possibly
136
   * transformed from XML into HTML
137
   */
138 49 jones
  private void handleQueryAction(PrintWriter out, Hashtable params,
139
               HttpServletResponse response) {
140
      // Run the query
141
      String query = ((String[])params.get("query"))[0];
142
      Hashtable nodelist = queryobj.findRootNodes(query);
143 50 jones
144
      // Create a buffer to hold the xml result
145
      StringBuffer resultset = new StringBuffer();
146
147 49 jones
      // Print the resulting root nodes
148
      long nodeid;
149 50 jones
      resultset.append("<?xml version=\"1.0\"?>\n");
150
      resultset.append("<resultset>\n");
151
      resultset.append("  <query>" + query + "</query>");
152 49 jones
      Enumeration rootlist = nodelist.keys();
153
      while (rootlist.hasMoreElements()) {
154
        nodeid = ((Long)rootlist.nextElement()).longValue();
155 50 jones
        resultset.append("  <nodeid>" + nodeid + "</nodeid>");
156 49 jones
      }
157 50 jones
      resultset.append("</resultset>");
158
159
      String qformat = ((String[])params.get("qformat"))[0];
160
      if (qformat.equals("xml")) {
161
        // set content type and other response header fields first
162
        response.setContentType("text/xml");
163
        out.println(resultset.toString());
164
      } else if (qformat.equals("html")) {
165
        // set content type and other response header fields first
166
        response.setContentType("text/html");
167
        //out.println("Converting to HTML...");
168
        XMLDocumentFragment htmldoc = null;
169
        try {
170
          XSLStylesheet style = new XSLStylesheet(new URL(resultStyleURL), null);
171
          htmldoc = (new XSLProcessor()).processXSL(style,
172
                     (Reader)(new StringReader(resultset.toString())),null);
173
          htmldoc.print(out);
174
        } catch (Exception e) {
175
          out.println("Error transforming document:\n" + e.getMessage());
176
        }
177
      }
178 49 jones
  }
179
180 50 jones
  /**
181
   * Handle the database getdocument request and return a XML document,
182
   * possibly transformed from XML into HTML
183
   */
184 49 jones
  private void handleGetDocumentAction(PrintWriter out, Hashtable params,
185
               HttpServletResponse response) {
186
      // Get the document indicated
187
      String docid = ((String[])params.get("docid"))[0];
188
      String doc = docreader.readXMLDocument((new Long(docid)).longValue());
189
190
      // set content type and other response header fields first
191
      response.setContentType("text/xml");
192
193
      out.println(doc);
194
  }
195 46 jones
}