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 85 2000-05-06 01:19:14Z 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.io.BufferedReader;
18
import java.util.Enumeration;
19
import java.util.Hashtable;
20
import java.util.ResourceBundle;
21
import java.util.PropertyResourceBundle;
22
import java.net.URL;
23
import java.net.MalformedURLException;
24
import java.sql.PreparedStatement;
25
import java.sql.ResultSet;
26
import java.sql.Connection;
27
import java.sql.SQLException;
28

    
29
import javax.servlet.ServletConfig;
30
import javax.servlet.ServletContext;
31
import javax.servlet.ServletException;
32
import javax.servlet.ServletInputStream;
33
import javax.servlet.http.HttpServlet;
34
import javax.servlet.http.HttpServletRequest;
35
import javax.servlet.http.HttpServletResponse;
36
import javax.servlet.http.HttpUtils;
37

    
38
import oracle.xml.parser.v2.XSLStylesheet;
39
import oracle.xml.parser.v2.XSLException;
40
import oracle.xml.parser.v2.XMLDocumentFragment;
41
import oracle.xml.parser.v2.XSLProcessor;
42
import oracle.xml.parser.v2.*;    //Oracle parser - DFH
43

    
44
/**
45
 * A metadata catalog server implemented as a Java Servlet
46
   *
47
   * <p>Valid parameters are:<br>
48
   * action=query -- query the values of all elements and attributes
49
   *                     and return a result set of nodes<br>
50
   * action=getdocument -- display an XML document in XML or HTML<br>
51
   * qformat=xml -- display resultset from query in XML<br>
52
   * qformat=html -- display resultset from query in HTML<br>
53
   * action=getdocument -- display an XML document in XML or HTML<br>
54
   * docid=34 -- display the document with the document ID number 34<br>
55
   * action=putdocument -- load an XML document into the database store<br>
56
   * doctext -- XML text ofthe document to load into the database<br>
57
   * query -- actual query text (to go with 'action=query')<br>
58
   * action=validate -- vallidate the xml contained in validatetext<br>
59
   * valtext -- XML text to be validated
60
 */
61
public class MetaCatServlet extends HttpServlet {
62

    
63
  private ServletConfig		config = null;
64
  private ServletContext	context = null;
65
  Connection 		conn = null;
66
  DBSimpleQuery		queryobj = null;
67
  DBReader		docreader = null;
68
  String 	user = null;
69
  String 	password = null;
70
  String 	defaultDB = null;
71
  String 	resultStyleURL = null;
72
  String 	xmlcatalogfile = null;
73
  PropertyResourceBundle options = null;
74

    
75
  /**
76
   * Initialize the servlet by creating appropriate database connections
77
   */
78
  public void init( ServletConfig config ) throws ServletException {
79
    try {
80
      super.init( config );
81
      this.config = config;
82
      this.context = config.getServletContext();
83
      System.out.println("Servlet Initialize");
84

    
85
      // Get the configuration file information
86
      options = (PropertyResourceBundle)PropertyResourceBundle.getBundle("edu.ucsb.nceas.metacat.metacat");
87
      user = (String)options.handleGetObject("user");
88
      password = (String)options.handleGetObject("password");
89
      defaultDB = (String)options.handleGetObject("defaultDB");
90
      resultStyleURL = (String)options.handleGetObject("resultStyleURL");
91
      xmlcatalogfile = (String)options.handleGetObject("xmlcatalogfile");
92

    
93
      try {
94
        // Open a connection to the database
95
        conn = MetaCatUtil.openDBConnection(
96
                "oracle.jdbc.driver.OracleDriver",
97
                defaultDB, user, password);
98

    
99
        queryobj = new DBSimpleQuery(conn);
100
        docreader = new DBReader(conn);
101

    
102
      } catch (Exception e) {
103
      }
104
    } catch ( ServletException ex ) {
105
      throw ex;
106
    }
107
  }
108

    
109
  /** Handle "GET" method requests from HTTP clients */
110
  public void doGet (HttpServletRequest request, HttpServletResponse response)
111
    throws ServletException, IOException {
112

    
113
    // Process the data and send back the response
114
    handleGetOrPost(request, response);
115
  }
116

    
117
  /** Handle "POST" method requests from HTTP clients */
118
  public void doPost( HttpServletRequest request, HttpServletResponse response)
119
    throws ServletException, IOException {
120

    
121
    // Process the data and send back the response
122
    handleGetOrPost(request, response);
123
  }
124

    
125
  /**
126
   * Control servlet response depending on the action parameter specified
127
   */
128
  private void handleGetOrPost(HttpServletRequest request, 
129
    HttpServletResponse response) 
130
    throws ServletException, IOException {
131

    
132
    // Get a handle to the output stream back to the client
133
    PrintWriter out = response.getWriter();
134
  
135
    String name = null;
136
    String[] value = null;
137
    Hashtable params = new Hashtable();
138
    Enumeration paramlist = request.getParameterNames();
139
    while (paramlist.hasMoreElements()) {
140
      name = (String)paramlist.nextElement();
141
      value = request.getParameterValues(name);
142
      params.put(name,value);
143
    }
144

    
145
    String action = ((String[])params.get("action"))[0];
146

    
147
    if (action.equals("query")) {
148
      handleQueryAction(out, params, response);
149
    } else if (action.equals("getdocument")) {
150
      handleGetDocumentAction(out, params, response);
151
    } else if (action.equals("putdocument")) {
152
      handlePutDocumentAction(out, params, response);
153
    } else if (action.equals("validate")) {
154
      handleValidateAction(out, params, response);  
155
    } else {
156
      out.println("Error: action not registered.  Please report this error.");
157
    }
158

    
159
    // Close the stream to the client
160
    out.close();
161
  }
162

    
163
  /** 
164
   * Handle the database query request and return a result set, possibly
165
   * transformed from XML into HTML
166
   */
167
  private void handleQueryAction(PrintWriter out, Hashtable params, 
168
               HttpServletResponse response) {
169
      // Run the query
170
      Hashtable nodelist = null;
171
      String query = ((String[])params.get("query"))[0]; 
172
      if (queryobj != null) {
173
        nodelist = queryobj.findRootNodes(query);
174
      } else {
175
        out.println("Query Object Init failed.");
176
	/*
177
        out.println(user);
178
        out.println(defaultDB);
179
        out.println(xmlcatalogfile);
180
        */
181
        return;
182
      }
183
 
184
      // Create a buffer to hold the xml result
185
      StringBuffer resultset = new StringBuffer();
186
 
187
      // Print the resulting root nodes
188
      long nodeid;
189
      resultset.append("<?xml version=\"1.0\"?>\n");
190
      resultset.append("<resultset>\n");
191
      resultset.append("  <query>" + query + "</query>");
192
      Enumeration rootlist = nodelist.keys(); 
193
      while (rootlist.hasMoreElements()) {
194
        nodeid = ((Long)rootlist.nextElement()).longValue();
195
        resultset.append("  <nodeid>" + nodeid + "</nodeid>");
196
      }
197
      resultset.append("</resultset>");
198

    
199
      String qformat = ((String[])params.get("qformat"))[0]; 
200
      if (qformat.equals("xml")) {
201
        // set content type and other response header fields first
202
        response.setContentType("text/xml");
203
        out.println(resultset.toString());
204
      } else if (qformat.equals("html")) {
205
        // set content type and other response header fields first
206
        response.setContentType("text/html");
207
        //out.println("Converting to HTML...");
208
        XMLDocumentFragment htmldoc = null;
209
        try {
210
          XSLStylesheet style = new XSLStylesheet(new URL(resultStyleURL), null);
211
          htmldoc = (new XSLProcessor()).processXSL(style, 
212
                     (Reader)(new StringReader(resultset.toString())),null);
213
          htmldoc.print(out);
214
        } catch (Exception e) {
215
          out.println("Error transforming document:\n" + e.getMessage());
216
        }
217
      }
218
  }
219

    
220
  /** 
221
   * Handle the database getdocument request and return a XML document, 
222
   * possibly transformed from XML into HTML
223
   */
224
  private void handleGetDocumentAction(PrintWriter out, Hashtable params, 
225
               HttpServletResponse response) {
226
      // Get the document indicated
227
      String docid = ((String[])params.get("docid"))[0]; 
228
      String doc = docreader.readXMLDocument((new Long(docid)).longValue());
229

    
230

    
231
      String qformat = ((String[])params.get("qformat"))[0]; 
232
      if (qformat.equals("xml")) {
233
        // set content type and other response header fields first
234
        response.setContentType("text/xml");
235
        out.println(doc);
236
      } else if (qformat.equals("html")) {
237
        // set content type and other response header fields first
238
        response.setContentType("text/html");
239
        //out.println("Converting to HTML...");
240
        XMLDocumentFragment htmldoc = null;
241

    
242
        // Look up the System ID of the XSL sheet
243
        PreparedStatement pstmt;
244
        String xsl_system_id = null;
245
  
246
        try {
247
          pstmt =
248
            conn.prepareStatement("SELECT system_id " +
249
                    "FROM xml_catalog_entities " +
250
                    "WHERE source_doctype LIKE ? " +
251
                    "AND target_doctype LIKE ?");
252
          // Bind the values to the query
253
          pstmt.setString(1, "-//NCEAS//eml-dataset//EN");
254
          pstmt.setString(2, "-//W3C//HTML//EN");
255
  
256
          pstmt.execute();
257
          try {
258
            ResultSet rs = pstmt.getResultSet();
259
            try {
260
              boolean tableHasRows = rs.next();
261
              if (tableHasRows) {
262
                try {
263
                  xsl_system_id = rs.getString(1);
264
                } catch (SQLException e) {
265
                  System.out.println("Error with getString: " + e.getMessage());
266
                }
267
              }
268
            } catch (SQLException e) {
269
              System.out.println("Error with next: " + e.getMessage());
270
            }
271
          } catch (SQLException e) {
272
            System.out.println("Error with getrset: " + e.getMessage());
273
          }
274
          pstmt.close();
275
        } catch (SQLException e) {
276
          System.out.println("Error getting id: " + e.getMessage());
277
        }
278
 
279
        // Try to apply the style
280
        try {
281
          XSLStylesheet style = new XSLStylesheet(new URL(xsl_system_id), null);
282
          htmldoc = (new XSLProcessor()).processXSL(style, 
283
                     (Reader)(new StringReader(doc)),null);
284
          htmldoc.print(out);
285
        } catch (Exception e) {
286
          out.println("Error transforming document:\n" + e.getMessage());
287
        }
288
      }
289
  }
290

    
291
  /** 
292
   * Handle the database putdocument request and write an XML document 
293
   * to the database connection
294
   */
295
  private void handlePutDocumentAction(PrintWriter out, Hashtable params, 
296
               HttpServletResponse response) {
297

    
298
      // Get the document indicated
299
      String[] doctext = (String[])params.get("doctext");
300
      StringReader xml = new StringReader(doctext[0]);
301

    
302
      // write the document to the database
303
      try {
304
        DBSAXWriter dbw = new DBSAXWriter(xml, conn);
305
      } catch (SQLException e1) {
306
          out.println("Error 1 loading document:<p>\n" + e1.getMessage());
307
      }catch (IOException e2) {
308
          out.println("Error 2 loading document:<p>\n" + e2.getMessage());
309
      }catch (ClassNotFoundException e3) {
310
          out.println("Error 3 loading document:<p>\n" + e3.getMessage());
311
      }
312

    
313
      // set content type and other response header fields first
314
      response.setContentType("text/xml");
315
  
316
      out.println(doctext[0]);
317
  }
318
  
319
  /** 
320
   * Handle the validtion request and return the results 
321
   * to the requestor - DFH
322
   */
323
  private void handleValidateAction(PrintWriter out, Hashtable params, HttpServletResponse response) {
324

    
325
      // Get the document indicated
326
      String[] valtext = (String[])params.get("valtext");
327

    
328

    
329
      SAXParser parser = new SAXParser();           // works for both Xerces and Oracle
330
      parser.setValidationMode(true);               // Oracle
331
      GenericXMLValidate gxv = new GenericXMLValidate(parser, xmlcatalogfile);
332
      boolean valid = gxv.validateString(valtext[0]);
333

    
334
      // set content type and other response header fields first
335
      response.setContentType("text/plain");
336
  
337
      if (valid) {
338
        out.println("The input XML is VALID!");
339
      }
340
      else {
341
        out.println("The input XML is NOT VALID\n" + gxv.returnErrors());
342
      } 
343
    }
344
}
(15-15/29)