Project

General

Profile

1
import java.io.PrintWriter;
2
import java.io.IOException;
3
import java.io.Reader;
4
import java.io.StringReader;
5
import java.util.Enumeration;
6
import java.util.Hashtable;
7
import java.net.URL;
8
import java.net.MalformedURLException;
9
import java.sql.Connection;
10

    
11
import javax.servlet.ServletConfig;
12
import javax.servlet.ServletContext;
13
import javax.servlet.ServletException;
14
import javax.servlet.ServletInputStream;
15
import javax.servlet.http.HttpServlet;
16
import javax.servlet.http.HttpServletRequest;
17
import javax.servlet.http.HttpServletResponse;
18
import javax.servlet.http.HttpUtils;
19

    
20
import oracle.xml.parser.v2.XSLStylesheet;
21
import oracle.xml.parser.v2.XSLException;
22
import oracle.xml.parser.v2.XMLDocumentFragment;
23
import oracle.xml.parser.v2.XSLProcessor;
24

    
25
/**
26
 * A metadata catalog server implemented as a Java Servlet
27
   *
28
   * <p>Valid parameters are:<br>
29
   * action=query -- query the values of all elements and attributes
30
   *                     and return a result set of nodes<br>
31
   * action=getdocument -- display an XML document in XML or HTML<br>
32
   * qformat=xml -- display resultset from query in XML<br>
33
   * qformat=html -- display resultset from query in HTML<br>
34
   * action=getdocument -- display an XML document in XML or HTML<br>
35
   * docid=34 -- display the document with the document ID number 34<br>
36
 */
37
public class MetaCatServlet extends HttpServlet {
38

    
39
  private ServletConfig		config = null;
40
  private ServletContext	context = null;
41
  DBSimpleQuery		queryobj = null;
42
  DBReader		docreader = null;
43
  static  String 	user = MetaCatUtil.user;
44
  static  String 	password = MetaCatUtil.password;
45
  static  String 	defaultDB = MetaCatUtil.defaultDB;
46
  static  String 	resultStyleURL = "file:///home/httpd/html/xmltodb/resultset.xsl";
47

    
48
  /**
49
   * Initialize the servlet by creating appropriate database connections
50
   */
51
  public void init( ServletConfig config ) throws ServletException {
52
    try {
53
      super.init( config );
54
      this.config = config;
55
      this.context = config.getServletContext();
56
    
57
      try {
58
        // Open a connection to the database
59
        Connection dbconn = MetaCatUtil.openDBConnection(
60
                "oracle.jdbc.driver.OracleDriver",
61
                defaultDB, user, password);
62

    
63
        queryobj = new DBSimpleQuery(dbconn);
64
        docreader = new DBReader(dbconn);
65
      } catch (Exception e) {
66
      }
67
    } catch ( ServletException ex ) {
68
      throw ex;
69
    }
70
  }
71

    
72
  /** Handle "GET" method requests from HTTP clients */
73
  public void doGet (HttpServletRequest request, HttpServletResponse response)
74
    throws ServletException, IOException {
75

    
76
    // Get the parameters from the form
77
    String querystring = request.getQueryString();
78
    Hashtable params = HttpUtils.parseQueryString(querystring);
79

    
80
    // Process the data and send back the response
81
    handleGetOrPost(response, params);
82
  }
83

    
84
  /** Handle "POST" method requests from HTTP clients */
85
  public void doPost( HttpServletRequest request, HttpServletResponse response)
86
    throws ServletException, IOException {
87

    
88
    // Get the input data from the client
89
    ServletInputStream in = request.getInputStream();
90
    int len = request.getContentLength();
91

    
92
    // Parse the input data into a Hashtable
93
    Hashtable params = HttpUtils.parsePostData(len, in);
94

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

    
99
  /**
100
   * Control servlet response depending on the action parameter specified
101
   */
102
  private void handleGetOrPost(HttpServletResponse response, Hashtable params) 
103
    throws ServletException, IOException {
104

    
105
    // Get a handle to the output stream back to the client
106
    PrintWriter out = response.getWriter();
107
  
108
    String action = ((String[])params.get("action"))[0];
109

    
110
    if (action.equals("query")) {
111
      handleQueryAction(out, params, response);
112
    } else if (action.equals("getdocument")) {
113
      handleGetDocumentAction(out, params, response);
114
    } else {
115
      out.println("Error: action not registered.  Please report this error.");
116
    }
117

    
118
    // Close the stream to the client
119
    out.close();
120
  }
121

    
122
  /** 
123
   * Handle the database query request and return a result set, possibly
124
   * transformed from XML into HTML
125
   */
126
  private void handleQueryAction(PrintWriter out, Hashtable params, 
127
               HttpServletResponse response) {
128
      // Run the query
129
      String query = ((String[])params.get("query"))[0]; 
130
      Hashtable nodelist = queryobj.findRootNodes(query);
131
 
132
      // Create a buffer to hold the xml result
133
      StringBuffer resultset = new StringBuffer();
134
 
135
      // Print the resulting root nodes
136
      long nodeid;
137
      resultset.append("<?xml version=\"1.0\"?>\n");
138
      resultset.append("<resultset>\n");
139
      resultset.append("  <query>" + query + "</query>");
140
      Enumeration rootlist = nodelist.keys(); 
141
      while (rootlist.hasMoreElements()) {
142
        nodeid = ((Long)rootlist.nextElement()).longValue();
143
        resultset.append("  <nodeid>" + nodeid + "</nodeid>");
144
      }
145
      resultset.append("</resultset>");
146

    
147
      String qformat = ((String[])params.get("qformat"))[0]; 
148
      if (qformat.equals("xml")) {
149
        // set content type and other response header fields first
150
        response.setContentType("text/xml");
151
        out.println(resultset.toString());
152
      } else if (qformat.equals("html")) {
153
        // set content type and other response header fields first
154
        response.setContentType("text/html");
155
        //out.println("Converting to HTML...");
156
        XMLDocumentFragment htmldoc = null;
157
        try {
158
          XSLStylesheet style = new XSLStylesheet(new URL(resultStyleURL), null);
159
          htmldoc = (new XSLProcessor()).processXSL(style, 
160
                     (Reader)(new StringReader(resultset.toString())),null);
161
          htmldoc.print(out);
162
        } catch (Exception e) {
163
          out.println("Error transforming document:\n" + e.getMessage());
164
        }
165
      }
166
  }
167

    
168
  /** 
169
   * Handle the database getdocument request and return a XML document, 
170
   * possibly transformed from XML into HTML
171
   */
172
  private void handleGetDocumentAction(PrintWriter out, Hashtable params, 
173
               HttpServletResponse response) {
174
      // Get the document indicated
175
      String docid = ((String[])params.get("docid"))[0]; 
176
      String doc = docreader.readXMLDocument((new Long(docid)).longValue());
177

    
178
      // set content type and other response header fields first
179
      response.setContentType("text/xml");
180
  
181
      out.println(doc);
182
  }
183
}
(11-11/18)