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 68 2000-05-04 21:44:38Z higgins $'
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.io.BufferedReader;
18
import java.util.Enumeration;
19
import java.util.Hashtable;
20
import java.net.URL;
21
import java.net.MalformedURLException;
22
import java.sql.Connection;
23
import java.sql.SQLException;
24

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

    
34
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
import oracle.xml.parser.v2.*;    //Oracle parser - DFH
39

    
40
/**
41
 * A metadata catalog server implemented as a Java Servlet
42
   *
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
   * action=putdocument -- load an XML document into the database store<br>
52
   * doctext -- XML text ofthe document to load into the database<br>
53
   * 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
 */
57
public class MetaCatServlet extends HttpServlet {
58

    
59
  private ServletConfig		config = null;
60
  private ServletContext	context = null;
61
  Connection 		conn = null;
62
  DBSimpleQuery		queryobj = null;
63
  DBReader		docreader = null;
64
  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

    
69
  /**
70
   * Initialize the servlet by creating appropriate database connections
71
   */
72
  public void init( ServletConfig config ) throws ServletException {
73
    try {
74
      super.init( config );
75
      this.config = config;
76
      this.context = config.getServletContext();
77
    System.out.println("Servlet Initialize");
78
      try {
79
        // Open a connection to the database
80
        conn = MetaCatUtil.openDBConnection(
81
                "oracle.jdbc.driver.OracleDriver",
82
                defaultDB, user, password);
83

    
84
        queryobj = new DBSimpleQuery(conn);
85
        docreader = new DBReader(conn);
86

    
87
      } catch (Exception e) {
88
      }
89
    } catch ( ServletException ex ) {
90
      throw ex;
91
    }
92
  }
93

    
94
  /** Handle "GET" method requests from HTTP clients */
95
  public void doGet (HttpServletRequest request, HttpServletResponse response)
96
    throws ServletException, IOException {
97

    
98
    // Process the data and send back the response
99
    handleGetOrPost(request, response);
100
  }
101

    
102
  /** Handle "POST" method requests from HTTP clients */
103
  public void doPost( HttpServletRequest request, HttpServletResponse response)
104
    throws ServletException, IOException {
105

    
106
    // Process the data and send back the response
107
    handleGetOrPost(request, response);
108
  }
109

    
110
  /**
111
   * Control servlet response depending on the action parameter specified
112
   */
113
  private void handleGetOrPost(HttpServletRequest request, 
114
    HttpServletResponse response) 
115
    throws ServletException, IOException {
116

    
117
    // Get a handle to the output stream back to the client
118
    PrintWriter out = response.getWriter();
119
  
120
    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
    String action = ((String[])params.get("action"))[0];
131

    
132
    if (action.equals("query")) {
133
      handleQueryAction(out, params, response);
134
    } else if (action.equals("getdocument")) {
135
      handleGetDocumentAction(out, params, response);
136
    } else if (action.equals("putdocument")) {
137
      handlePutDocumentAction(out, params, response);
138
    } else if (action.equals("validate")) {
139
      handleValidateAction(out, params, response);  
140
    } else {
141
      out.println("Error: action not registered.  Please report this error.");
142
    }
143

    
144
    // Close the stream to the client
145
    out.close();
146
  }
147

    
148
  /** 
149
   * Handle the database query request and return a result set, possibly
150
   * transformed from XML into HTML
151
   */
152
  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
 
158
      // Create a buffer to hold the xml result
159
      StringBuffer resultset = new StringBuffer();
160
 
161
      // Print the resulting root nodes
162
      long nodeid;
163
      resultset.append("<?xml version=\"1.0\"?>\n");
164
      resultset.append("<resultset>\n");
165
      resultset.append("  <query>" + query + "</query>");
166
      Enumeration rootlist = nodelist.keys(); 
167
      while (rootlist.hasMoreElements()) {
168
        nodeid = ((Long)rootlist.nextElement()).longValue();
169
        resultset.append("  <nodeid>" + nodeid + "</nodeid>");
170
      }
171
      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
  }
193

    
194
  /** 
195
   * Handle the database getdocument request and return a XML document, 
196
   * possibly transformed from XML into HTML
197
   */
198
  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

    
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

    
217
      // Get the document indicated
218
      String[] doctext = (String[])params.get("doctext");
219
      StringReader xml = new StringReader(doctext[0]);
220

    
221
      // write the document to the database
222
      try {
223
        DBSAXWriter dbw = new DBSAXWriter(xml, conn);
224
      } catch (SQLException e1) {
225
          out.println("Error 1 loading document:<p>\n" + e1.getMessage());
226
      }catch (IOException e2) {
227
          out.println("Error 2 loading document:<p>\n" + e2.getMessage());
228
      }catch (ClassNotFoundException e3) {
229
          out.println("Error 3 loading document:<p>\n" + e3.getMessage());
230
      }
231

    
232
      // set content type and other response header fields first
233
      response.setContentType("text/xml");
234
  
235
      out.println(doctext[0]);
236
  }
237
  
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
}
(12-12/23)