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 60 2000-04-18 21:19:17Z 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.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

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

    
55
  private ServletConfig		config = null;
56
  private ServletContext	context = null;
57
  Connection 		conn = null;
58
  DBSimpleQuery		queryobj = null;
59
  DBReader		docreader = null;
60
  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

    
65
  /**
66
   * Initialize the servlet by creating appropriate database connections
67
   */
68
  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
        // Open a connection to the database
76
        conn = MetaCatUtil.openDBConnection(
77
                "oracle.jdbc.driver.OracleDriver",
78
                defaultDB, user, password);
79

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

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

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

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

    
101
    // Process the data and send back the response
102
    handleGetOrPost(request, response);
103
  }
104

    
105
  /**
106
   * Control servlet response depending on the action parameter specified
107
   */
108
  private void handleGetOrPost(HttpServletRequest request, 
109
    HttpServletResponse response) 
110
    throws ServletException, IOException {
111

    
112
    // Get a handle to the output stream back to the client
113
    PrintWriter out = response.getWriter();
114
  
115
    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
    String action = ((String[])params.get("action"))[0];
126

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

    
137
    // Close the stream to the client
138
    out.close();
139
  }
140

    
141
  /** 
142
   * Handle the database query request and return a result set, possibly
143
   * transformed from XML into HTML
144
   */
145
  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
 
151
      // Create a buffer to hold the xml result
152
      StringBuffer resultset = new StringBuffer();
153
 
154
      // Print the resulting root nodes
155
      long nodeid;
156
      resultset.append("<?xml version=\"1.0\"?>\n");
157
      resultset.append("<resultset>\n");
158
      resultset.append("  <query>" + query + "</query>");
159
      Enumeration rootlist = nodelist.keys(); 
160
      while (rootlist.hasMoreElements()) {
161
        nodeid = ((Long)rootlist.nextElement()).longValue();
162
        resultset.append("  <nodeid>" + nodeid + "</nodeid>");
163
      }
164
      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
  }
186

    
187
  /** 
188
   * Handle the database getdocument request and return a XML document, 
189
   * possibly transformed from XML into HTML
190
   */
191
  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

    
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

    
210
      // Get the document indicated
211
      String[] doctext = (String[])params.get("doctext");
212
      StringReader xml = new StringReader(doctext[0]);
213

    
214
      // write the document to the database
215
      try {
216
        DBSAXWriter dbw = new DBSAXWriter(xml, conn);
217
      } catch (SQLException e1) {
218
          out.println("Error 1 loading document:<p>\n" + e1.getMessage());
219
      }catch (IOException e2) {
220
          out.println("Error 2 loading document:<p>\n" + e2.getMessage());
221
      }catch (ClassNotFoundException e3) {
222
          out.println("Error 3 loading document:<p>\n" + e3.getMessage());
223
      }
224

    
225
      // set content type and other response header fields first
226
      response.setContentType("text/xml");
227
  
228
      out.println(doctext[0]);
229
  }
230
}
(11-11/20)