Project

General

Profile

1
/**
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: MetaCatServlet.java 55 2000-04-18 17:48:47Z jones $'
9
 */
10

    
11
package edu.ucsb.nceas.metacat;
12

    
13
import java.io.PrintWriter;
14
import java.io.IOException;
15
import java.io.Reader;
16
import java.io.StringReader;
17
import java.util.Enumeration;
18
import java.util.Hashtable;
19
import java.net.URL;
20
import java.net.MalformedURLException;
21
import java.sql.Connection;
22
import java.sql.SQLException;
23

    
24
import javax.servlet.ServletConfig;
25
import javax.servlet.ServletContext;
26
import javax.servlet.ServletException;
27
import javax.servlet.ServletInputStream;
28
import javax.servlet.http.HttpServlet;
29
import javax.servlet.http.HttpServletRequest;
30
import javax.servlet.http.HttpServletResponse;
31
import javax.servlet.http.HttpUtils;
32

    
33
import oracle.xml.parser.v2.XSLStylesheet;
34
import oracle.xml.parser.v2.XSLException;
35
import oracle.xml.parser.v2.XMLDocumentFragment;
36
import oracle.xml.parser.v2.XSLProcessor;
37

    
38
/**
39
 * A metadata catalog server implemented as a Java Servlet
40
   *
41
   * <p>Valid parameters are:<br>
42
   * action=query -- query the values of all elements and attributes
43
   *                     and return a result set of nodes<br>
44
   * action=getdocument -- display an XML document in XML or HTML<br>
45
   * qformat=xml -- display resultset from query in XML<br>
46
   * qformat=html -- display resultset from query in HTML<br>
47
   * action=getdocument -- display an XML document in XML or HTML<br>
48
   * docid=34 -- display the document with the document ID number 34<br>
49
 */
50
public class MetaCatServlet extends HttpServlet {
51

    
52
  private ServletConfig		config = null;
53
  private ServletContext	context = null;
54
  Connection 		conn = null;
55
  DBSimpleQuery		queryobj = null;
56
  DBReader		docreader = null;
57
  static  String 	user = MetaCatUtil.user;
58
  static  String 	password = MetaCatUtil.password;
59
  static  String 	defaultDB = MetaCatUtil.defaultDB;
60
  static  String 	resultStyleURL = "file:///home/httpd/html/xmltodb/resultset.xsl";
61

    
62
  /**
63
   * Initialize the servlet by creating appropriate database connections
64
   */
65
  public void init( ServletConfig config ) throws ServletException {
66
    try {
67
      super.init( config );
68
      this.config = config;
69
      this.context = config.getServletContext();
70
    
71
      try {
72
        // Open a connection to the database
73
        conn = MetaCatUtil.openDBConnection(
74
                "oracle.jdbc.driver.OracleDriver",
75
                defaultDB, user, password);
76

    
77
        queryobj = new DBSimpleQuery(conn);
78
        docreader = new DBReader(conn);
79
      } catch (Exception e) {
80
      }
81
    } catch ( ServletException ex ) {
82
      throw ex;
83
    }
84
  }
85

    
86
  /** Handle "GET" method requests from HTTP clients */
87
  public void doGet (HttpServletRequest request, HttpServletResponse response)
88
    throws ServletException, IOException {
89

    
90
    // Get the parameters from the form
91
    String querystring = request.getQueryString();
92
    Hashtable params = HttpUtils.parseQueryString(querystring);
93

    
94
    // Process the data and send back the response
95
    handleGetOrPost(response, params);
96
  }
97

    
98
  /** Handle "POST" method requests from HTTP clients */
99
  public void doPost( HttpServletRequest request, HttpServletResponse response)
100
    throws ServletException, IOException {
101

    
102
    // Get the input data from the client
103
    ServletInputStream in = request.getInputStream();
104
    int len = request.getContentLength();
105

    
106
    // Parse the input data into a Hashtable
107
    Hashtable params = HttpUtils.parsePostData(len, in);
108

    
109
    // Process the data and send back the response
110
    handleGetOrPost(response, params);
111
  }
112

    
113
  /**
114
   * Control servlet response depending on the action parameter specified
115
   */
116
  private void handleGetOrPost(HttpServletResponse response, Hashtable params) 
117
    throws ServletException, IOException {
118

    
119
    // Get a handle to the output stream back to the client
120
    PrintWriter out = response.getWriter();
121
  
122
    String action = ((String[])params.get("action"))[0];
123

    
124
    if (action.equals("query")) {
125
      handleQueryAction(out, params, response);
126
    } else if (action.equals("getdocument")) {
127
      handleGetDocumentAction(out, params, response);
128
    } else if (action.equals("putdocument")) {
129
      handlePutDocumentAction(out, params, response);
130
    } else {
131
      out.println("Error: action not registered.  Please report this error.");
132
    }
133

    
134
    // Close the stream to the client
135
    out.close();
136
  }
137

    
138
  /** 
139
   * Handle the database query request and return a result set, possibly
140
   * transformed from XML into HTML
141
   */
142
  private void handleQueryAction(PrintWriter out, Hashtable params, 
143
               HttpServletResponse response) {
144
      // Run the query
145
      String query = ((String[])params.get("query"))[0]; 
146
      Hashtable nodelist = queryobj.findRootNodes(query);
147
 
148
      // Create a buffer to hold the xml result
149
      StringBuffer resultset = new StringBuffer();
150
 
151
      // Print the resulting root nodes
152
      long nodeid;
153
      resultset.append("<?xml version=\"1.0\"?>\n");
154
      resultset.append("<resultset>\n");
155
      resultset.append("  <query>" + query + "</query>");
156
      Enumeration rootlist = nodelist.keys(); 
157
      while (rootlist.hasMoreElements()) {
158
        nodeid = ((Long)rootlist.nextElement()).longValue();
159
        resultset.append("  <nodeid>" + nodeid + "</nodeid>");
160
      }
161
      resultset.append("</resultset>");
162

    
163
      String qformat = ((String[])params.get("qformat"))[0]; 
164
      if (qformat.equals("xml")) {
165
        // set content type and other response header fields first
166
        response.setContentType("text/xml");
167
        out.println(resultset.toString());
168
      } else if (qformat.equals("html")) {
169
        // set content type and other response header fields first
170
        response.setContentType("text/html");
171
        //out.println("Converting to HTML...");
172
        XMLDocumentFragment htmldoc = null;
173
        try {
174
          XSLStylesheet style = new XSLStylesheet(new URL(resultStyleURL), null);
175
          htmldoc = (new XSLProcessor()).processXSL(style, 
176
                     (Reader)(new StringReader(resultset.toString())),null);
177
          htmldoc.print(out);
178
        } catch (Exception e) {
179
          out.println("Error transforming document:\n" + e.getMessage());
180
        }
181
      }
182
  }
183

    
184
  /** 
185
   * Handle the database getdocument request and return a XML document, 
186
   * possibly transformed from XML into HTML
187
   */
188
  private void handleGetDocumentAction(PrintWriter out, Hashtable params, 
189
               HttpServletResponse response) {
190
      // Get the document indicated
191
      String docid = ((String[])params.get("docid"))[0]; 
192
      String doc = docreader.readXMLDocument((new Long(docid)).longValue());
193

    
194
      // set content type and other response header fields first
195
      response.setContentType("text/xml");
196
  
197
      out.println(doc);
198
  }
199

    
200
  /** 
201
   * Handle the database putdocument request and write an XML document 
202
   * to the database connection
203
   */
204
  private void handlePutDocumentAction(PrintWriter out, Hashtable params, 
205
               HttpServletResponse response) {
206
      // Get the document indicated
207
      String doctext = ((String[])params.get("doctext"))[0]; 
208
      StringReader xml = new StringReader(doctext);
209
      try {
210
        DBSAXWriter dbw = new DBSAXWriter(doctext, conn);
211
      } catch (SQLException e1) {
212
          out.println("Error loading document:<p>\n" + e1.getMessage());
213
      }catch (IOException e2) {
214
          out.println("Error loading document:<p>\n" + e2.getMessage());
215
      }catch (ClassNotFoundException e3) {
216
          out.println("Error loading document:<p>\n" + e3.getMessage());
217
      }
218
      //String doc = docreader.readXMLDocument((new Long(docid)).longValue());
219

    
220
      // set content type and other response header fields first
221
      response.setContentType("text/html");
222
  
223
      out.println("Finished loading document.");
224
  }
225
}
(11-11/20)