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 83 2000-05-05 22:17:15Z 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.Connection;
25
import java.sql.SQLException;
26

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

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

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

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

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

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

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

    
97
        queryobj = new DBSimpleQuery(conn);
98
        docreader = new DBReader(conn);
99

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

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

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

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

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

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

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

    
143
    String action = ((String[])params.get("action"))[0];
144

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

    
157
    // Close the stream to the client
158
    out.close();
159
  }
160

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

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

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

    
228
      // set content type and other response header fields first
229
      response.setContentType("text/xml");
230
  
231
      out.println(doc);
232
  }
233

    
234
  /** 
235
   * Handle the database putdocument request and write an XML document 
236
   * to the database connection
237
   */
238
  private void handlePutDocumentAction(PrintWriter out, Hashtable params, 
239
               HttpServletResponse response) {
240

    
241
      // Get the document indicated
242
      String[] doctext = (String[])params.get("doctext");
243
      StringReader xml = new StringReader(doctext[0]);
244

    
245
      // write the document to the database
246
      try {
247
        DBSAXWriter dbw = new DBSAXWriter(xml, conn);
248
      } catch (SQLException e1) {
249
          out.println("Error 1 loading document:<p>\n" + e1.getMessage());
250
      }catch (IOException e2) {
251
          out.println("Error 2 loading document:<p>\n" + e2.getMessage());
252
      }catch (ClassNotFoundException e3) {
253
          out.println("Error 3 loading document:<p>\n" + e3.getMessage());
254
      }
255

    
256
      // set content type and other response header fields first
257
      response.setContentType("text/xml");
258
  
259
      out.println(doctext[0]);
260
  }
261
  
262
  /** 
263
   * Handle the validtion request and return the results 
264
   * to the requestor - DFH
265
   */
266
  private void handleValidateAction(PrintWriter out, Hashtable params, HttpServletResponse response) {
267

    
268
      // Get the document indicated
269
      String[] valtext = (String[])params.get("valtext");
270

    
271

    
272
      SAXParser parser = new SAXParser();           // works for both Xerces and Oracle
273
      parser.setValidationMode(true);               // Oracle
274
      GenericXMLValidate gxv = new GenericXMLValidate(parser, xmlcatalogfile);
275
      boolean valid = gxv.validateString(valtext[0]);
276

    
277
      // set content type and other response header fields first
278
      response.setContentType("text/plain");
279
  
280
      if (valid) {
281
        out.println("The input XML is VALID!");
282
      }
283
      else {
284
        out.println("The input XML is NOT VALID\n" + gxv.returnErrors());
285
      } 
286
    }
287
}
(16-16/19)