Project

General

Profile

« Previous | Next » 

Revision 295

Added by berkley almost 24 years ago

Added marine files to metacat package

View differences:

lib/marine/marine.xsl
1
<?xml version="1.0"?>
2
<!--
3
  * marine.xsl
4
  *
5
  *      Authors: Matt Jones, Chad Berkley
6
  *    Copyright: 2000 Regents of the University of California and the 
7
  *               National Center for Ecological Analysis and Synthesis
8
  *  For Details: http://www.nceas.ucsb.edu/
9
  *      Created: 2000 July 20
10
  *    File Info: '$Id$'
11
  *
12
  * This is an XSLT (http://www.w3.org/TR/xslt) stylesheet designed to
13
  * convert an XML file showing the resultset of a query
14
  * into an HTML format suitable for rendering with modern web browsers.
15
  * This stylesheet formats .
16
-->
17
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
18

  
19
  <xsl:output method="html"/>
20

  
21
  <xsl:template match="/">
22
    <html>
23
      <head>
24
	<link rel="stylesheet" type="text/css" href="/xmltodb/lib/rowcol.css" />
25
      </head>
26
      <body class="emlbody">
27
	<center>
28
          <u><h2>Query Results</h2></u>
29
        </center>
30
        
31
        <form action="/servlets/marineServlet" method="POST">
32
        <input type="hidden" name="action" value="getdocument"/>
33

  
34
        <xsl:text>Output Format: </xsl:text>
35
        <select name="qformat">
36
          <option value="html">HTML</option>
37
          <option value="xml">XML</option>
38
        </select>
39

  
40
        <table width="100%">
41
        <tr class="rowodd">
42
        <th>&nbsp;</th>
43
        <th><xsl:text>Title</xsl:text></th>
44
        <th><xsl:text>Resource Name</xsl:text></th>
45
<!--        <th><xsl:text>Document Type</xsl:text></th> -->
46
        </tr>
47

  
48
        <xsl:for-each select="resultset/document">
49
          <tr valign="top">
50
            <xsl:attribute name="class">
51
              <xsl:choose>
52
                <xsl:when test="position() mod 2 = 1">rowwhite</xsl:when>
53
                <xsl:when test="position() mod 2 = 0">rowlight</xsl:when>
54
              </xsl:choose>
55
            </xsl:attribute>
56

  
57
          <td>
58
<!--
59
              <input type="radio" name="docid">
60
                <xsl:attribute name="value">
61
                  <xsl:value-of select="./docid"/>
62
                </xsl:attribute>
63
              </input>
64
              <input type="submit" value="Display"/>
65
-->
66
              <input border="0" type="image">
67
                <xsl:attribute name="src">
68
                  <xsl:choose>
69
                    <xsl:when test="position() 
70
                         mod 2 = 1">/xmltodb/images/bttns-white.png</xsl:when>
71
                    <xsl:when test="position() 
72
                         mod 2 = 0">/xmltodb/images/bttns-blue.jpg</xsl:when>
73
                  </xsl:choose>
74
                </xsl:attribute>
75
                <xsl:attribute name="name">
76
                  <xsl:value-of select="./docid"/>
77
                </xsl:attribute>
78
              </input>
79
          </td>
80
          <td><xsl:value-of select="./doctitle"/>
81
              <xsl:text>&nbsp;</xsl:text>
82
         </td>
83
          <td>
84
              <xsl:value-of select="./docname"/> 
85
              <xsl:text> </xsl:text>
86
<!--              <xsl:value-of select="./docid"/>
87
              <xsl:text>&nbsp;</xsl:text>
88
-->
89
          </td>
90
<!--          <td><xsl:value-of select="./doctype"/>
91
              <xsl:text>&nbsp;</xsl:text>
92
         </td> 
93
-->
94
          </tr>
95
        </xsl:for-each>
96
        </table>
97
        </form>
98

  
99
      </body>
100
    </html>
101
  </xsl:template>
102

  
103
</xsl:stylesheet>
0 104

  
lib/marine/marine.properties
1
#
2
# Properties file defining options for the MetaCatServlet.java servlet
3
# Matt Jones, Dan Higgins
4
# '$Id$'
5
#
6
user=jones
7
password=kinkaj0u
8
defaultDB=jdbc:oracle:thin:@24.237.20.124:1521:test
9
dbDriver=oracle.jdbc.driver.OracleDriver
10
resultStyleURL=file:///home/httpd/html/marine/marine.xsl
11
xmlcatalogfile=/home/httpd/html/xmltodb/lib/catalog.txt
12
defaultdatapath=C:\Temp\
13
executescript=test.bat
14
defaultGlobalName=NCEAS
15
accNumberSeparator=:
16
saxparser=org.apache.xerces.parsers.SAXParser
0 17

  
lib/marine/index.html
1
<!-- MARINE UI Test main page
2
     Author: Chad Berkley
3
     Date: 6/26/00
4
     Comments: Test User Interface for MARINE Scientists
5
-->
6
     
7
<html>
8
  <head>
9
  <title>MetaCat MARINE Interface</title>
10
  </head>
11
  <frameset cols="*" frameborder=1 border=1>
12

  
13
    <frameset rows="400,*"  frameborder=1 border=1>
14
    
15
    <frame src="marinetest.html" border=1 border="top">
16

  
17
    <frame src="http://alpha.nceas.ucsb.edu/servlets/marineServlet?action=query&query=NCEAS%25&qformat=html&doctype=-//NCEAS//eml-dataset//EN" border=1 name="bottom">
18

  
19
    </frameset>
20
  </frameset>
21
</html>
0 22

  
lib/marine/marinetest.html
1
<!--
2
  * marinetest.html 
3
  * Test MetaCat MARINE UI    
4
  * Author: Chad Berkley       
5
  * Copyright: 2000 Regents of the University of California and the
6
  *               National Center for Ecological Analysis and Synthesis
7
  * For Details: http://www.nceas.ucsb.edu/
8
  * Date: 6/23/00 
9
  *  
10
-->
11

  
12
<html>
13
<head>
14
<title>Test MetaCat MARINE Interface</title>
15
</head>
16
<body bgcolor="white">
17
<h1>MARINE Query</h1>
18
<p>
19
Query engine for MARINE formatted data.
20
</p>
21
<table border="2" align="top">
22
<tr>
23
<td align="center" valign="top" width="300">
24

  
25
<h2>Structured Query</h2>
26
<hr>
27
<form
28
action="http://alpha.nceas.ucsb.edu/servlets/marineServlet" target="bottom" method="POST">
29

  
30
  <h3>Originator:</h3>
31
  First Name: <input type = "text" name = "given_name"><br>
32
  Last Name: <input type = "text" name = "surname"><br>
33
  Email Address: <input type = "text" name = "email"><br>
34
  Postal Code: <input type = "text" name = "postal_code"><br>
35
  <hr>
36
  <h3>Other Resource Information</h3>
37
  Organization: <input type = "text" name = "party_org"><br>
38
  Keywords: <input type = "text" name = "keyword"><br>
39
  Title: <input type = "text" name = "title"><br>
40
  <input type="hidden" name="query" value="">
41
<!--  <input type="hidden" name="qformat" value="html"> -->
42
  <input type="hidden" name="action" value="squery">
43
  <input type="hidden" name="doctype" value="ANY">
44
  Output Type:
45
  <select name = "qformat">
46
    <option value="html">HTML</option>
47
    <option value="xml">XML</option>
48
  </select><br>
49
  Boolean Operator:
50
  <select name = "operator">
51
    <option value="UNION">OR</option>
52
    <option value="INTERSECT">AND</option>
53
  </select><br>
54
  <input type="submit" value="Query">
55
</form>
56

  
57
</td>
58
<td align="center" valign = "top" width="300">
59
<h2>Free Text Query</h2>
60
<hr>
61
<form
62
action="http://alpha.nceas.ucsb.edu/servlets/marineServlet" target="bottom" method="POST">
63
Keywords: <input type="text" name="query"><br> 
64
  <input type="hidden" name="qformat" value="html">
65
  <input type="hidden" name="action" value="query">
66
  <input type="hidden" name="doctype" value="ANY">
67
  <input type="submit" value="Query">
68
</form>
69

  
70
</td>
71
</tr>
72
</table>
73
</form>
74

  
75
</body>
76
</html>
0 77

  
src/edu/ucsb/nceas/metacat/marine/marineServlet.java
1
package edu.ucsb.nceas.metacat.marine;
2

  
3
import java.io.*;
4
import java.util.*;
5
import javax.servlet.*;
6
import javax.servlet.http.*;
7
import java.net.*;
8
import java.sql.*;
9
import oracle.xml.parser.v2.*;
10
import org.xml.sax.*;
11
import org.xml.sax.helpers.*;
12
// import edu.ucsb.nceas.metacat.*;
13
import oracle.jdbc.driver.*;
14
import oracle.xml.parser.v2.*;
15
import oracle.xml.parser.v2.XMLParser;
16

  
17
public class marineServlet extends HttpServlet 
18
{
19
	private marineUtil util;
20
	private String resultStyleURL;
21
	private String xmlcatalogfile;
22
	private String saxparser;
23
	private String defaultdatapath;
24
	private String executescript;
25
	private DBQuery queryobj;
26
	private DBReader docreader;
27
	private DBTransform dbt;
28
	private Connection conn;
29
	private PropertyResourceBundle options;
30
	private String msg;
31
	private String queryname;
32
	
33
	public void init(PrintWriter out) 
34
	{
35
		util = new marineUtil();
36
		resultStyleURL = util.getOption("resultStyleURL");
37
		xmlcatalogfile = util.getOption("xmlcatalogfile");
38
      		saxparser = util.getOption("saxparser");
39
      		defaultdatapath = util.getOption("defaultdatapath");
40
      		executescript = util.getOption("executescript");
41
      		
42
      	
43
      		try
44
      		{
45
      			conn = util.openDBConnection();
46
      			queryobj = new DBQuery(conn,saxparser);
47
        		docreader = new DBReader(conn);
48
        		dbt = new DBTransform(conn);
49
        		/*
50
        		msg = new String(conn.toString());
51
      			msg += "\n" + saxparser;
52
      			msg += "\n" + queryobj;
53
      			msg += "\n" + docreader;
54
      			msg += "\n" + dbt;
55
      			*/
56
      		}
57
      		catch(Exception e)
58
      		{
59
      			msg = new String("Error in init\n " 
60
      			      + e.fillInStackTrace().toString() );
61
      		}
62
	}
63

  
64
	public void doGet (HttpServletRequest request, 
65
	                   HttpServletResponse response)
66
    			throws ServletException, IOException 
67
    	{
68
    		handleGetOrPost(request, response);
69
    	}
70
    	
71
    	public void doPost (HttpServletRequest request, 
72
    	                    HttpServletResponse response)
73
    			throws ServletException, IOException 
74
    	{
75
    		handleGetOrPost(request, response);
76
    	}
77
    	
78
    	private void handleGetOrPost(HttpServletRequest request, 
79
    			HttpServletResponse response) 
80
    			throws ServletException, IOException 
81
    	{
82
    		
83
    		response.setContentType("text/html");
84
    		PrintWriter out = response.getWriter();
85
    		
86
    		try
87
    		{
88
    			init(out); // remove this when init() 
89
    			           //actually works
90
		}
91
    		catch(Exception e)
92
      		{
93
      			out.println("Exception in handleGetOrPost: ");
94
      			out.println(e.toString());
95
      			out.println(msg);
96
      		}
97
      		
98
    		if (conn == null) 
99
    		{
100
      			System.err.println("Connection to database lost"+  
101
      			                    "...Reopening...");
102
      			try 
103
      			{
104
        			conn = util.openDBConnection();
105
        			queryobj = new DBQuery(conn, saxparser);
106
        			docreader = new DBReader(conn);
107
        			dbt = new DBTransform(conn);
108
      			}
109
      			catch (Exception e) 
110
      			{
111
        			System.err.println("Error opening" +
112
        			                   " database connection");
113
      			}
114
    		}   	
115
    		
116
    		String name = null;
117
    		String[] value = null;
118
    		String[] docid = new String[3];
119
    		Hashtable params = new Hashtable();
120
    		Enumeration paramlist = request.getParameterNames();
121
    		while (paramlist.hasMoreElements()) 
122
    		{
123
      			name = (String)paramlist.nextElement();
124
      			value = request.getParameterValues(name);
125

  
126
      			// Decode the docid and mouse click information
127
      			if (name.endsWith(".y")) 
128
      			{
129
        			docid[0] = name.substring(0,name.length()-2);
130
        			//out.println("docid => " + docid[0]);
131
        			params.put("docid", docid);
132
        			name = "ypos";
133
      			}
134
      			if (name.endsWith(".x")) 
135
      			{
136
        			name = "xpos";
137
      			}
138

  
139
      			//out.println(name + " => " + value[0]);
140
      			params.put(name,value);
141
    		}
142
		
143
		// Determine what type of request the user made
144
    		// if the action parameter is set, use it as a default
145
    		// but if the ypos param is set, calculate the action
146
    		// needed
147
    		String action = ((String[])params.get("action"))[0];
148
    		long ypos = 0;
149
    		try 
150
    		{
151
      			ypos = (new Long(
152
      			((String[])params.get("ypos"))[0]).longValue());
153
      			
154
      			//out.println("<P>YPOS IS " + ypos);
155
      			if (ypos <= 13) 
156
      			{
157
        			action = "getdocument";
158
      			} 
159
      			else if (ypos > 13 && ypos <= 27) 
160
      			{
161
        			action = "validate";
162
      			} 
163
      			else if (ypos > 27) 
164
      			{
165
        			action = "transform";
166
      			}
167
    		} 
168
    		catch (Exception npe) 
169
    		{
170
      			//out.println("<P>Caught exception looking for Y value.");
171
    		}
172
    		
173
    		//Jivka's login code should go here!
174
    		
175
    		if (action.equals("query") || action.equals("squery")) 
176
    		{
177
      			handleQueryAction(out, params, response);
178
    		} 
179
   		else if (action.equals("getdocument")) 
180
    		{
181
      			try 
182
      			{
183
        			handleGetDocumentAction(out, params, response);
184
      			} 
185
      			catch(ClassNotFoundException e) 
186
      			{
187
        			out.println(e.getMessage());
188
      			} 
189
      			catch 
190
      			(SQLException se) 
191
      			{
192
        			out.println(se.getMessage());
193
      			}
194
    		} 
195
    		else if(action.equals("insert") || action.equals("update")) 
196
    		{
197
      			handleInsertOrUpdateAction(out, params, response);
198
    		} 
199
    		else if(action.equals("delete")) 
200
    		{
201
      			handleDeleteAction(out, params, response);
202
    		} 
203
    		else if(action.equals("validate")) 
204
    		{
205
      			handleValidateAction(out, params, response);  
206
    		} 
207
    		else if (action.equals("getdatadoc")) 
208
    		{
209
      			handleGetDataDocumentAction(out, params, response);  
210
    		} 
211
    		else if (action.equals("Login")) 
212
    		{
213
    		} 
214
    		else 
215
    		{
216
      			out.println("Error: action not registered" +
217
      			  "Please report this error.");
218
    		}
219
		
220
		//out.print("msg:<br> ");
221
		//out.println(msg);
222
		//out.println("<br><br>marineServlet says: ok");
223
		out.close();
224
    	}
225
/** 
226
   * Handle the database query request and return a result set, possibly
227
   * transformed from XML into HTML
228
   */
229
  	private void handleQueryAction(PrintWriter out, Hashtable params, 
230
               HttpServletResponse response)
231
        {
232
        	String query = ((String[])params.get("query"))[0];
233
      		String action = ((String[])params.get("action"))[0];
234
      		Hashtable doclist = null;
235
      		String[] doctypeArr = null;
236
      		String doctype = null;
237
      		Reader xmlquery = null;
238
		
239
      		// Run the query if it is a structured query
240
      		// or, if it is a free-text, simple query,
241
      		// format it first as a structured query and then run it
242
      		if (action.equals("query")) 
243
      		{
244
      		     
245
       	 		doctypeArr = (String[])params.get("doctype");
246
        		doctype = null;
247
        		if (doctypeArr != null) 
248
        		{
249
          			doctype = ((String[])params.get("doctype"))[0]; 
250
        		}
251

  
252
        		if (doctype != null) 
253
        		{
254
          			xmlquery = new StringReader(DBQuery.createQuery(query,doctype));
255
        		} 
256
        		else 
257
        		{
258
          			xmlquery = new StringReader(DBQuery.createQuery(query));
259
        		}
260
      		} 
261
      		else if (action.equals("squery")) 
262
      		{ 
263
      			doctypeArr = (String[])params.get("doctype");
264
        		doctype = null;
265
        		if (doctypeArr != null) 
266
        		{
267
          			doctype = ((String[])params.get("doctype"))[0]; 
268
        		}
269
        		// for some reason the doctype="ANY" wildcard is not working
270
        		//correctly. For this reason, I have ommited the doctype
271
        		//here for the time being (7/20). 
272
        		xmlquery = new StringReader(createSQuery(params));
273
        		//msg = createSQuery(params);
274
      		} 
275
      		else 
276
      		{
277
        		msg = "Error handling query -- illegal action value";
278
      		}
279
      
280
      		if (queryobj != null) 
281
      		{
282
      			doclist = queryobj.findDocuments(xmlquery);
283
      		} 
284
      		else 
285
      		{
286
        		out.println("Query Object Init failed.");
287
        		return;
288
      		}
289
 
290
      		// Create a buffer to hold the xml result
291
      		StringBuffer resultset = new StringBuffer();
292
 
293
      		// Print the resulting root nodes
294
      		String docid;
295
      		String document = null;
296
      		resultset.append("<?xml version=\"1.0\"?>\n");
297
      		//resultset.append("<!DOCTYPE resultset PUBLIC " +
298
      		//               "\"-//NCEAS//resultset//EN\" \"resultset.dtd\">\n");
299
      		resultset.append("<resultset>\n");
300
      		resultset.append("  <query>" + queryname + "</query>");
301
      		Enumeration doclistkeys = doclist.keys(); 
302
      		while(doclistkeys.hasMoreElements()) 
303
      		{
304
        		docid = (String)doclistkeys.nextElement();
305
        		document = (String)doclist.get(docid);
306
        		resultset.append("  <document>" + document + 
307
        		                 "</document>");
308
      		}
309
      		resultset.append("</resultset>");
310

  
311
      		String qformat = ((String[])params.get("qformat"))[0]; 
312
      		if (qformat.equals("xml")) 
313
      		{
314
        		// set content type and other response 
315
        		// header fields first
316
        		response.setContentType("text/xml");
317
        		out.println(resultset.toString());
318
      		} 
319
      		else if(qformat.equals("html")) 
320
      		{
321
        		// set content type and other response header
322
        		// fields first
323
        		response.setContentType("text/html");
324
        		//out.println("Converting to HTML...");
325
        		XMLDocumentFragment htmldoc = null;
326
        		
327
        		try 
328
        		{
329
          			XSLStylesheet style = new XSLStylesheet(
330
                                    new URL(resultStyleURL), null);
331
          			htmldoc = (new XSLProcessor()).processXSL(style, 
332
                                   (Reader)(new StringReader
333
                                   (resultset.toString())),null);
334
          			htmldoc.print(out);
335
        		} 
336
        		catch (Exception e) 
337
        		{
338
          			out.println("Error transforming document:\n" 
339
          			             + e.fillInStackTrace().toString());
340
          			out.println("<p>msg: " + msg + "</p>");
341
        		}
342
      		}
343
      	}
344
      	
345
      	/** takes in the parameter list from the input source and 
346
      	    a doctype and returns a structured xml query based
347
      	    on the parameters.
348
      	**/
349
      	private String createSQuery(Hashtable params, String doctype)
350
	{
351
    		String query;
352
    		Enumeration elements;
353
    		Enumeration keys;
354
    		Object nextkey;
355
    		Object nextelement;
356
    		query = "<?xml version=\"1.0\"?>";
357
		query += "<!DOCTYPE pathquery PUBLIC \"-//NCEAS//pathquery-1.0//EN\" " + 
358
          		    "\"http://alpha.nceas.ucsb.edu/dtd/misc/pathquery.dtd\" >";
359
    		query += "<pathquery version=\"1.0\"><meta_file_id>";
360
    		if(params.containsKey("meta_file_id"))
361
    		{
362
    			query += ((String[])params.get("meta_file_id"))[0];
363
    			query += "</meta_file_id>";
364
    		}
365
    		else
366
    		{
367
    			query += "unspecified</meta_file_id>";
368
    		}
369
    		query += "<querytitle>";
370
    		if(params.containsKey("querytitle"))
371
    		{
372
    			query += ((String[])params.get("querytitle"))[0];
373
    			query += "</querytitle>";
374
    		}
375
    		else
376
    		{
377
    			query += "unspecified</querytitle>";
378
    		}
379
    		if(!doctype.equals(""))
380
    		{
381
    			query += "<returndoctype>" + doctype + "</returndoctype>";
382
    		}
383
    		query += "<querygroup operator=\"" + ((String[])params.get("operator"))[0] + "\">";
384
    		
385
    		elements = params.elements();
386
    		keys = params.keys();
387
    		queryname = " ";
388
    		while(keys.hasMoreElements() && elements.hasMoreElements())
389
    		{
390
    			nextkey = keys.nextElement();
391
    			nextelement = elements.nextElement();
392
    			//msg += " " + nextkey.toString() + "=" +
393
    			//       ((String[])elements.nextElement())[0];
394
    			if(!nextkey.toString().equals("doctype") && 
395
    			   !nextkey.toString().equals("action")  &&
396
    			   !nextkey.toString().equals("qformat") && 
397
    			   !(((String[])nextelement)[0].equals("")) )
398
    			{
399
    				query += "<queryterm casesensitive=\"false\" " + 
400
    				         "searchmode=\"contains\">";
401
    				query += "<value>";
402
    				query += ((String[])nextelement)[0];
403
    				//queryname += ((String[])nextelement)[0] + " " + 
404
    				//             ((String[])params.get("operator"))[0] +
405
    				//             " ";
406
    				query += "</value><pathexpr>" + 
407
    				         nextkey.toString() + 
408
    				         "</pathexpr></queryterm>";
409
    				
410
    				//query += "</value></queryterm>";
411
    			}
412
    		}
413
    		query += "</querygroup></pathquery>";
414
    		return query;
415
        } 
416
        
417
        /**same as createSQuery(Hashtable, String) except
418
           no doctyp is required.
419
        **/
420
        private String createSQuery(Hashtable params)
421
        {
422
        	return createSQuery(params, "");
423
        } 
424

  
425
/***************************************************************
426
  The following code is taken directly from MetaCatServlet.java
427
****************************************************************/
428
 /** 
429
   * Handle the database getdocument request and return a XML document, 
430
   * possibly transformed from XML into HTML
431
   */
432
  private void handleGetDocumentAction(PrintWriter out, Hashtable params, 
433
               HttpServletResponse response) 
434
               throws ClassNotFoundException, IOException, SQLException {
435
    String docidstr = null;
436
    String docid = null;
437
    String doc = null;
438
    try {
439
      // Find the document id number
440
      docidstr = ((String[])params.get("docid"))[0]; 
441
      //docid = (new Long(docidstr)).longValue();
442
      docid = docidstr;
443

  
444
      // Get the document indicated fromthe db
445
      doc = docreader.readXMLDocument(docid);
446
    } catch (NullPointerException npe) {
447
      response.setContentType("text/html");
448
      out.println("Error getting document ID: " + docidstr +" (" + docid + ")");
449
    }
450

  
451
      // Return the document in XML or HTML format
452
      String qformat = ((String[])params.get("qformat"))[0]; 
453
      if (qformat.equals("xml")) {
454
        // set content type and other response header fields first
455
        response.setContentType("text/xml");
456
        out.println(doc);
457
      } else if (qformat.equals("html")) {
458
        // set content type and other response header fields first
459
        response.setContentType("text/html");
460

  
461
        // Look up the document type
462
        String sourcetype = docreader.getDoctypeInfo(docid).getDoctype();
463

  
464
        // Transform the document to the new doctype
465
        dbt.transformXMLDocument(doc, sourcetype, "-//W3C//HTML//EN", out);
466
      }
467
  }
468

  
469
  /** 
470
   * Handle the database putdocument request and write an XML document 
471
   * to the database connection
472
   */
473
  private void handleInsertOrUpdateAction(PrintWriter out, Hashtable params, 
474
               HttpServletResponse response) {
475

  
476
    try {
477
      // Get the document indicated
478
      String[] doctext = (String[])params.get("doctext");
479
      StringReader xml = null;
480
      try {
481
        xml = new StringReader(doctext[0]);
482

  
483
        String[] action = (String[])params.get("action");
484
        String[] docid = (String[])params.get("docid");
485
        String newdocid = null;
486

  
487
        String doAction = null;
488
        if (action[0].equals("insert")) {
489
          doAction = "INSERT";
490
        } else if (action[0].equals("update")) {
491
          doAction = "UPDATE";
492
        }
493

  
494
        // write the document to the database
495
        DBWriter dbw = new DBWriter(conn, saxparser);
496

  
497
        try {
498
          String accNumber = docid[0];
499
          if (accNumber.equals("")) {
500
            accNumber = null;
501
          }
502
          newdocid = dbw.write(xml, doAction, accNumber);  
503
        } catch (NullPointerException npe) {
504
          newdocid = dbw.write(xml, doAction, null);  
505
        }
506

  
507
        // set content type and other response header fields first
508
        response.setContentType("text/xml");
509
        out.println("<?xml version=\"1.0\"?>");
510
        out.println("<success>");
511
        out.println("<docid>" + newdocid + "</docid>"); 
512
        out.println("</success>");
513

  
514
      } catch (NullPointerException npe) {
515
        response.setContentType("text/xml");
516
        out.println("<?xml version=\"1.0\"?>");
517
        out.println("<error>");
518
        out.println(npe.getMessage()); 
519
        out.println("</error>");
520
      }
521
    } catch (Exception e) {
522
      response.setContentType("text/xml");
523
      out.println("<?xml version=\"1.0\"?>");
524
      out.println("<error>");
525
      out.println(e.getMessage()); 
526
      if (e instanceof SAXException) {
527
        Exception e2 = ((SAXException)e).getException();
528
        out.println("<error>");
529
        out.println(e2.getMessage()); 
530
        out.println("</error>");
531
      }
532
      //e.printStackTrace(out);
533
      out.println("</error>");
534
    }
535
  }
536

  
537
  /** 
538
   * Handle the database delete request and delete an XML document 
539
   * from the database connection
540
   */
541
  private void handleDeleteAction(PrintWriter out, Hashtable params, 
542
               HttpServletResponse response) {
543

  
544
    String[] docid = (String[])params.get("docid");
545

  
546
    // delete the document from the database
547
    try {
548
      DBWriter dbw = new DBWriter(conn, saxparser);
549
                                      // NOTE -- NEED TO TEST HERE
550
                                      // FOR EXISTENCE OF PARAM
551
                                      // BEFORE ACCESSING ARRAY
552
      try {
553
        dbw.delete(docid[0]);
554
        response.setContentType("text/xml");
555
        out.println("<?xml version=\"1.0\"?>");
556
        out.println("<success>");
557
        out.println("Document deleted."); 
558
        out.println("</success>");
559
      } catch (AccessionNumberException ane) {
560
        response.setContentType("text/xml");
561
        out.println("<?xml version=\"1.0\"?>");
562
        out.println("<error>");
563
        out.println("Error deleting document!!!");
564
        out.println(ane.getMessage()); 
565
        out.println("</error>");
566
      }
567
    } catch (Exception e) {
568
      response.setContentType("text/xml");
569
      out.println("<?xml version=\"1.0\"?>");
570
      out.println("<error>");
571
      out.println(e.getMessage()); 
572
      out.println("</error>");
573
    }
574
  }
575
  
576
  /** 
577
   * Handle the validtion request and return the results to the requestor
578
   */
579
  private void handleValidateAction(PrintWriter out, Hashtable params, 
580
               HttpServletResponse response) {
581

  
582
    // Get the document indicated
583
    String valtext = null;
584
    try {
585
      valtext = ((String[])params.get("valtext"))[0];
586
    } catch (Exception nullpe) {
587

  
588
      String docid = null;
589
      try {
590
        // Find the document id number
591
        docid = ((String[])params.get("docid"))[0]; 
592
  
593
        // Get the document indicated fromthe db
594
        valtext = docreader.readXMLDocument(docid);
595

  
596
      } catch (NullPointerException npe) {
597
        response.setContentType("text/xml");
598
        out.println("<error>Error getting document ID: " + docid + "</error>");
599
      }
600
    }
601

  
602
    try {
603
      DBValidate valobj = new DBValidate(saxparser,conn);
604
      boolean valid = valobj.validateString(valtext);
605

  
606
      // set content type and other response header fields first
607
      response.setContentType("text/xml");
608
      out.println(valobj.returnErrors());
609

  
610
    } catch (NullPointerException npe2) {
611
      // set content type and other response header fields first
612
      response.setContentType("text/xml");
613
      out.println("<error>Error validating document.</error>"); 
614
    }
615
  }
616

  
617
  /** 
618
   * Handle the document request and return the results 
619
   * to the requestor
620
   */
621
  private void handleGetDataDocumentAction(PrintWriter out, Hashtable params, 
622
               HttpServletResponse response) {
623
      boolean error_flag = false;
624
      String error_message = "";
625
      // Get the document indicated
626
      String[] datadoc = (String[])params.get("datadoc");
627
      // defaultdatapath = "C:\\Temp\\";    // for testing only!!!
628
      // executescript = "test.bat";        // for testing only!!!
629
      
630
      // set content type and other response header fields first
631
      response.setContentType("application/octet-stream");
632
      if (defaultdatapath!=null) {
633
        if(!defaultdatapath.endsWith(System.getProperty("file.separator"))) {
634
          defaultdatapath=defaultdatapath+System.getProperty("file.separator");
635
        }
636
        System.out.println("Path= "+defaultdatapath+datadoc[0]);
637
        if (executescript!=null) {
638
          String command = null;
639
          File scriptfile = new File(executescript);
640
          if (scriptfile.exists()) {
641
            command=executescript+" "+datadoc[0]; // script includes path
642
        } else {     // look in defaultdatapath
643
            // on Win98 one MUST include the .bat extender
644
            command = defaultdatapath+executescript+" "+datadoc[0];  
645
        }
646
      System.out.println(command);
647
      try {
648
      Process proc = Runtime.getRuntime().exec(command);
649
      proc.waitFor();
650
      }
651
      catch (Exception eee) {
652
        System.out.println("Error running process!");
653
        error_flag = true;
654
        error_message = "Error running process!";}
655
      } // end executescript not null if
656
      File datafile = new File(defaultdatapath+datadoc[0]);
657
      try {
658
      FileInputStream fw = new FileInputStream(datafile);
659
      int x;
660
      while ((x = fw.read())!=-1) {
661
        out.write(x); }
662
        fw.close();
663
      } catch (Exception e) {
664
        System.out.println("Error in returning file\n"+e.getMessage());
665
        error_flag=true;
666
        error_message = error_message+"\nError in returning file\n"+
667
                        e.getMessage();
668
      }
669
    } // end defaultdatapath not null if
670
  }	
671
/**********************************************
672
    END code taken from MetaCatServlet.java
673
***********************************************/
674

  
675
}
0 676

  
src/edu/ucsb/nceas/metacat/marine/marineUtil.java
1
/**
2
 *  '$RCSfile$'
3
 *    Purpose: A Class that implements utility methods for a metadata catalog
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
 *   '$Author$'
9
 *     '$Date$'
10
 * '$Revision$'
11
 */
12

  
13
import java.io.File;
14
import java.net.URL;
15
import java.net.MalformedURLException;
16
import java.sql.Connection;
17
import java.sql.DriverManager;
18
import java.sql.SQLException;
19
import java.util.PropertyResourceBundle;
20
import oracle.jdbc.driver.*;
21

  
22
/**
23
 * A suite of utility classes for the metadata catalog server
24
 */
25
public class marineUtil {
26

  
27
  private PropertyResourceBundle options = null;
28
  private static String propertiesFile = "marine";
29
  private static boolean debug = false;
30

  
31
  /**
32
   * Construct an instance of the utility class
33
   */
34
  public marineUtil() {
35
    options = (PropertyResourceBundle)
36
          PropertyResourceBundle.getBundle(propertiesFile);
37
  }
38

  
39
  /** 
40
   * Utility method to establish a JDBC database connection using connection
41
   * info from the properties file
42
   */
43
  public Connection openDBConnection()
44
                throws SQLException, ClassNotFoundException {
45
    return openDBConnection(getOption("dbDriver"), getOption("defaultDB"),
46
                     getOption("user"), getOption("password"));
47
  }
48

  
49
  /** 
50
   * Utility method to establish a JDBC database connection 
51
   *
52
   * @param dbDriver the string representing the database driver
53
   * @param connection the string representing the database connectin parameters
54
   * @param user name of the user to use for database connection
55
   * @param password password for the user to use for database connection
56
   */
57
  public static Connection openDBConnection(String dbDriver, String connection,
58
                String user, String password)
59
                throws SQLException, ClassNotFoundException {
60

  
61
     // Load the Oracle JDBC driver
62
     Class.forName (dbDriver);
63

  
64
     // Connect to the database
65
     Connection conn = DriverManager.getConnection( connection, user, password);
66
     return conn;
67
  }
68

  
69
  /** 
70
   * Utility method to get an option value from the properties file
71
   *
72
   * @param option_name the name of the option requested
73
   */
74
  public String getOption(String option_name) {
75
      // Get the configuration file information
76
      if (options == null) {
77
        options = (PropertyResourceBundle)
78
          PropertyResourceBundle.getBundle(propertiesFile);
79
      }
80
      String value = (String)options.handleGetObject(option_name);
81
      return value;
82
  }
83

  
84
  /** Utility method to convert a file handle into a URL */
85
  public static URL fileToURL(File file)
86
  {
87
     String path = file.getAbsolutePath();
88
     String fSep = System.getProperty("file.separator");
89
     if (fSep != null && fSep.length() == 1)
90
       path = path.replace(fSep.charAt(0), '/');
91
     if (path.length() > 0 && path.charAt(0) != '/')
92
       path = '/' + path;
93
     try {
94
       return new URL("file", null, path);
95
     }
96
     catch (java.net.MalformedURLException e) {
97
       /* According to the spec this could only happen if the file
98
          protocol were not recognized. */
99
       throw new Error("unexpected MalformedURLException");
100
     }
101
  }
102

  
103
  /** 
104
   * Utility method to print debugging messages
105
   *
106
   * @param flag an integer indicating the message number
107
   */
108
  public static void debugMessage(int flag) {
109
    if (debug) {
110
      System.err.println("DEBUG FLAG: " + flag);
111
    }
112
  }
113

  
114
  /** 
115
   * Utility method to print debugging messages
116
   *
117
   * @param flag an integer indicating the message number
118
   */
119
  public static void debugMessage(String msg) {
120
    if (debug) {
121
      System.err.println(msg);
122
    }
123
  }
124
}
125

  
0 126

  

Also available in: Unified diff