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
39 46 jones
/**
40
 * A metadata catalog server implemented as a Java Servlet
41 50 jones
   *
42
   * <p>Valid parameters are:<br>
43
   * action=query -- query the values of all elements and attributes
44
   *                     and return a result set of nodes<br>
45
   * action=getdocument -- display an XML document in XML or HTML<br>
46
   * qformat=xml -- display resultset from query in XML<br>
47
   * qformat=html -- display resultset from query in HTML<br>
48
   * action=getdocument -- display an XML document in XML or HTML<br>
49
   * docid=34 -- display the document with the document ID number 34<br>
50 60 jones
   * action=putdocument -- load an XML document into the database store<br>
51
   * doctext -- XML text ofthe document to load into the database<br>
52 46 jones
 */
53
public class MetaCatServlet extends HttpServlet {
54
55
  private ServletConfig		config = null;
56
  private ServletContext	context = null;
57 55 jones
  Connection 		conn = null;
58 46 jones
  DBSimpleQuery		queryobj = null;
59 49 jones
  DBReader		docreader = null;
60 50 jones
  static  String 	user = MetaCatUtil.user;
61
  static  String 	password = MetaCatUtil.password;
62
  static  String 	defaultDB = MetaCatUtil.defaultDB;
63
  static  String 	resultStyleURL = "file:///home/httpd/html/xmltodb/resultset.xsl";
64 46 jones
65 50 jones
  /**
66
   * Initialize the servlet by creating appropriate database connections
67
   */
68 46 jones
  public void init( ServletConfig config ) throws ServletException {
69
    try {
70
      super.init( config );
71
      this.config = config;
72
      this.context = config.getServletContext();
73
74
      try {
75 50 jones
        // Open a connection to the database
76 55 jones
        conn = MetaCatUtil.openDBConnection(
77 50 jones
                "oracle.jdbc.driver.OracleDriver",
78
                defaultDB, user, password);
79
80 55 jones
        queryobj = new DBSimpleQuery(conn);
81
        docreader = new DBReader(conn);
82 46 jones
      } catch (Exception e) {
83
      }
84
    } catch ( ServletException ex ) {
85
      throw ex;
86
    }
87
  }
88
89 50 jones
  /** Handle "GET" method requests from HTTP clients */
90 46 jones
  public void doGet (HttpServletRequest request, HttpServletResponse response)
91
    throws ServletException, IOException {
92
93 48 jones
    // Process the data and send back the response
94 59 jones
    handleGetOrPost(request, response);
95 48 jones
  }
96
97 50 jones
  /** Handle "POST" method requests from HTTP clients */
98 48 jones
  public void doPost( HttpServletRequest request, HttpServletResponse response)
99
    throws ServletException, IOException {
100
101
    // Process the data and send back the response
102 59 jones
    handleGetOrPost(request, response);
103 48 jones
  }
104
105 49 jones
  /**
106 50 jones
   * Control servlet response depending on the action parameter specified
107 49 jones
   */
108 59 jones
  private void handleGetOrPost(HttpServletRequest request,
109
    HttpServletResponse response)
110 48 jones
    throws ServletException, IOException {
111
112 49 jones
    // Get a handle to the output stream back to the client
113 48 jones
    PrintWriter out = response.getWriter();
114 49 jones
115 59 jones
    String name = null;
116
    String[] value = null;
117
    Hashtable params = new Hashtable();
118
    Enumeration paramlist = request.getParameterNames();
119
    while (paramlist.hasMoreElements()) {
120
      name = (String)paramlist.nextElement();
121
      value = request.getParameterValues(name);
122
      params.put(name,value);
123
    }
124
125 49 jones
    String action = ((String[])params.get("action"))[0];
126 46 jones
127 49 jones
    if (action.equals("query")) {
128
      handleQueryAction(out, params, response);
129
    } else if (action.equals("getdocument")) {
130
      handleGetDocumentAction(out, params, response);
131 55 jones
    } else if (action.equals("putdocument")) {
132
      handlePutDocumentAction(out, params, response);
133 50 jones
    } else {
134
      out.println("Error: action not registered.  Please report this error.");
135 46 jones
    }
136
137 49 jones
    // Close the stream to the client
138 46 jones
    out.close();
139
  }
140 49 jones
141 50 jones
  /**
142
   * Handle the database query request and return a result set, possibly
143
   * transformed from XML into HTML
144
   */
145 49 jones
  private void handleQueryAction(PrintWriter out, Hashtable params,
146
               HttpServletResponse response) {
147
      // Run the query
148
      String query = ((String[])params.get("query"))[0];
149
      Hashtable nodelist = queryobj.findRootNodes(query);
150 50 jones
151
      // Create a buffer to hold the xml result
152
      StringBuffer resultset = new StringBuffer();
153
154 49 jones
      // Print the resulting root nodes
155
      long nodeid;
156 50 jones
      resultset.append("<?xml version=\"1.0\"?>\n");
157
      resultset.append("<resultset>\n");
158
      resultset.append("  <query>" + query + "</query>");
159 49 jones
      Enumeration rootlist = nodelist.keys();
160
      while (rootlist.hasMoreElements()) {
161
        nodeid = ((Long)rootlist.nextElement()).longValue();
162 50 jones
        resultset.append("  <nodeid>" + nodeid + "</nodeid>");
163 49 jones
      }
164 50 jones
      resultset.append("</resultset>");
165
166
      String qformat = ((String[])params.get("qformat"))[0];
167
      if (qformat.equals("xml")) {
168
        // set content type and other response header fields first
169
        response.setContentType("text/xml");
170
        out.println(resultset.toString());
171
      } else if (qformat.equals("html")) {
172
        // set content type and other response header fields first
173
        response.setContentType("text/html");
174
        //out.println("Converting to HTML...");
175
        XMLDocumentFragment htmldoc = null;
176
        try {
177
          XSLStylesheet style = new XSLStylesheet(new URL(resultStyleURL), null);
178
          htmldoc = (new XSLProcessor()).processXSL(style,
179
                     (Reader)(new StringReader(resultset.toString())),null);
180
          htmldoc.print(out);
181
        } catch (Exception e) {
182
          out.println("Error transforming document:\n" + e.getMessage());
183
        }
184
      }
185 49 jones
  }
186
187 50 jones
  /**
188
   * Handle the database getdocument request and return a XML document,
189
   * possibly transformed from XML into HTML
190
   */
191 49 jones
  private void handleGetDocumentAction(PrintWriter out, Hashtable params,
192
               HttpServletResponse response) {
193
      // Get the document indicated
194
      String docid = ((String[])params.get("docid"))[0];
195
      String doc = docreader.readXMLDocument((new Long(docid)).longValue());
196
197
      // set content type and other response header fields first
198
      response.setContentType("text/xml");
199
200
      out.println(doc);
201
  }
202 55 jones
203
  /**
204
   * Handle the database putdocument request and write an XML document
205
   * to the database connection
206
   */
207
  private void handlePutDocumentAction(PrintWriter out, Hashtable params,
208
               HttpServletResponse response) {
209 59 jones
210 55 jones
      // Get the document indicated
211 59 jones
      String[] doctext = (String[])params.get("doctext");
212
      StringReader xml = new StringReader(doctext[0]);
213
214
      // write the document to the database
215 55 jones
      try {
216 59 jones
        DBSAXWriter dbw = new DBSAXWriter(xml, conn);
217 55 jones
      } catch (SQLException e1) {
218 59 jones
          out.println("Error 1 loading document:<p>\n" + e1.getMessage());
219 55 jones
      }catch (IOException e2) {
220 59 jones
          out.println("Error 2 loading document:<p>\n" + e2.getMessage());
221 55 jones
      }catch (ClassNotFoundException e3) {
222 59 jones
          out.println("Error 3 loading document:<p>\n" + e3.getMessage());
223 55 jones
      }
224
225
      // set content type and other response header fields first
226 59 jones
      response.setContentType("text/xml");
227 55 jones
228 59 jones
      out.println(doctext[0]);
229 55 jones
  }
230 46 jones
}