Project

General

Profile

1
/**
2
 *  '$RCSfile$'
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, Dan Higgins, Jivka Bojilova
7
 *
8
 *   '$Author: bojilova $'
9
 *     '$Date: 2000-08-10 14:47:21 -0700 (Thu, 10 Aug 2000) $'
10
 * '$Revision: 336 $'
11
 */
12

    
13
package edu.ucsb.nceas.metacat;
14

    
15
import java.io.PrintWriter;
16
import java.io.IOException;
17
import java.io.Reader;
18
import java.io.StringReader;
19
import java.io.BufferedReader;
20
import java.io.File;
21
import java.io.FileInputStream;
22
import java.util.Enumeration;
23
import java.util.Hashtable;
24
import java.util.ResourceBundle;
25
import java.util.PropertyResourceBundle;
26
import java.net.URL;
27
import java.net.MalformedURLException;
28
import java.sql.PreparedStatement;
29
import java.sql.ResultSet;
30
import java.sql.Connection;
31
import java.sql.SQLException;
32

    
33
import javax.servlet.ServletConfig;
34
import javax.servlet.ServletContext;
35
import javax.servlet.ServletException;
36
import javax.servlet.ServletInputStream;
37
import javax.servlet.http.HttpServlet;
38
import javax.servlet.http.HttpServletRequest;
39
import javax.servlet.http.HttpServletResponse;
40
import javax.servlet.http.HttpSession;
41
import javax.servlet.http.HttpUtils;
42

    
43
import oracle.xml.parser.v2.XSLStylesheet;
44
import oracle.xml.parser.v2.XSLException;
45
import oracle.xml.parser.v2.XMLDocumentFragment;
46
import oracle.xml.parser.v2.XSLProcessor;
47

    
48
import org.xml.sax.SAXException;
49

    
50
/**
51
 * A metadata catalog server implemented as a Java Servlet
52
 *
53
 * <p>Valid parameters are:<br>
54
 * action=query -- query the values of all elements and attributes
55
 *                     and return a result set of nodes<br>
56
 * action=squery -- structured query (see pathquery.dtd)<br>
57
 * action=insert -- insert an XML document into the database store<br>
58
 * action=update -- update an XML document that is in the database store<br>
59
 * action=delete --  delete an XML document from the database store<br>
60
 * action=validate -- vallidate the xml contained in valtext<br>
61
 * action=getdocument -- display an XML document in XML or HTML<br>
62
 * doctype -- document type list returned by the query (publicID)<br>
63
 * qformat=xml -- display resultset from query in XML<br>
64
 * qformat=html -- display resultset from query in HTML<br>
65
 * docid=34 -- display the document with the document ID number 34<br>
66
 * doctext -- XML text of the document to load into the database<br>
67
 * query -- actual query text (to go with 'action=query' or 'action=squery')<br>
68
 * valtext -- XML text to be validated<br>
69
 * action=getdatadoc -- retreive a stored datadocument<br>
70
 * action=getdoctypes -- retreive all doctypes (publicID)<br>
71
 * action=getdataguide -- retreive a Data Guide<br>
72
 * datadoc -- data document name (id)<br>
73
 * <p>
74
 * The particular combination of parameters that are valid for each 
75
 * particular action value is quite specific.  This documentation
76
 * will be reorganized to reflect this information.
77
 */
78
public class MetaCatServlet extends HttpServlet {
79

    
80
  private ServletConfig		config = null;
81
  private ServletContext	context = null;
82
  private Hashtable 		connectionPool = new Hashtable();
83
  private String 		resultStyleURL = null;
84
  private String 		xmlcatalogfile = null;
85
  private String 		saxparser = null;
86
  private String        defaultdatapath = null; 
87
					// path to directory where data files 
88
					// that can be downloaded will be stored
89
  private String        executescript  = null;  
90
					// script to get data file and put it 
91
                    // in defaultdocpath dir
92
  private PropertyResourceBundle options = null;
93

    
94
  private MetaCatUtil util = null;
95

    
96
  /**
97
   * Initialize the servlet by creating appropriate database connections
98
   */
99
  public void init( ServletConfig config ) throws ServletException {
100
    try {
101
      super.init( config );
102
      this.config = config;
103
      this.context = config.getServletContext(); 
104
      System.out.println("MetaCatServlet Initialize");
105

    
106
      util = new MetaCatUtil();
107

    
108
      // Get the configuration file information
109
      resultStyleURL = util.getOption("resultStyleURL");
110
      xmlcatalogfile = util.getOption("xmlcatalogfile");
111
      saxparser = util.getOption("saxparser");
112
      defaultdatapath = util.getOption("defaultdatapath");
113
      executescript = util.getOption("executescript");
114

    
115
      try {
116
        // Open a pool of db connections
117
        connectionPool = util.getConnectionPool();
118
      } catch (Exception e) {
119
        System.err.println("Error creating pool of database connections");
120
        System.err.println(e.getMessage());
121
      }
122
    } catch ( ServletException ex ) {
123
      throw ex;
124
    }
125
  }
126

    
127
  /**
128
   * Close all db connections from the pool
129
   */
130
  public void destroy() {
131
    
132
    if (util != null) {
133
        util.closeConnections();
134
    }
135
  }
136

    
137
  /** Handle "GET" method requests from HTTP clients */
138
  public void doGet (HttpServletRequest request, HttpServletResponse response)
139
    throws ServletException, IOException {
140

    
141
    // Process the data and send back the response
142
    handleGetOrPost(request, response);
143
  }
144

    
145
  /** Handle "POST" method requests from HTTP clients */
146
  public void doPost( HttpServletRequest request, HttpServletResponse response)
147
    throws ServletException, IOException {
148

    
149
    // Process the data and send back the response
150
    handleGetOrPost(request, response);
151
  }
152

    
153
  /**
154
   * Control servlet response depending on the action parameter specified
155
   */
156
  private void handleGetOrPost(HttpServletRequest request, 
157
    HttpServletResponse response) 
158
    throws ServletException, IOException {
159

    
160
    if ( util == null ) {
161
        util = new MetaCatUtil(); 
162
    }
163
    if ( connectionPool == null ) {
164
      try {
165
        // Open a pool of db connections
166
        connectionPool = util.getConnectionPool();
167
      } catch (Exception e) {
168
        System.err.println("Error creating pool of database connections");
169
        System.err.println(e.getMessage());
170
      }
171
    }    
172
    // Get a handle to the output stream back to the client
173
    PrintWriter out = response.getWriter();
174
    //response.setContentType("text/html");
175
  
176
    String name = null;
177
    String[] value = null;
178
    String[] docid = new String[3];
179
    Hashtable params = new Hashtable();
180
    Enumeration paramlist = request.getParameterNames();
181
    while (paramlist.hasMoreElements()) {
182
      name = (String)paramlist.nextElement();
183
      value = request.getParameterValues(name);
184

    
185
      // Decode the docid and mouse click information
186
      if (name.endsWith(".y")) {
187
        docid[0] = name.substring(0,name.length()-2);
188
        //out.println("docid => " + docid[0]);
189
        params.put("docid", docid);
190
        name = "ypos";
191
      }
192
      if (name.endsWith(".x")) {
193
        name = "xpos";
194
      }
195

    
196
      //out.println(name + " => " + value[0]);
197
      params.put(name,value);
198
    }
199

    
200
    // Determine what type of request the user made
201
    // if the action parameter is set, use it as a default
202
    // but if the ypos param is set, calculate the action needed
203
    String action = ((String[])params.get("action"))[0];
204
    long ypos = 0;
205
    try {
206
      ypos = (new Long(((String[])params.get("ypos"))[0]).longValue());
207
      //out.println("<P>YPOS IS " + ypos);
208
      if (ypos <= 13) {
209
        action = "getdocument";
210
      } else if (ypos > 13 && ypos <= 27) {
211
        action = "validate";
212
      } else if (ypos > 27) {
213
        action = "transform";
214
      //} else {
215
      //  action = "";
216
      }
217
    } catch (Exception npe) {
218
      //out.println("<P>Caught exception looking for Y value.");
219
    }
220

    
221
// Jivka added  
222
    // handle login action
223
    if (action.equals("Login") || action.equals("Login Client")) {
224
      handleLoginAction(out, params, request, response);
225
    // handle logout action  
226
    } else if (action.equals("Logout")) {
227
      HttpSession sess = request.getSession(false);
228
      if (sess != null) { sess.invalidate();  }    
229
      response.sendRedirect("/xmltodb/login.html"); 
230
    // aware of session expiration on every request  
231
    } else {    
232
      HttpSession sess = request.getSession(true);
233
      if (sess.isNew()) { 
234
        // session expired or has not been stored b/w user requests
235
        // redirect to default page for query only access
236
        response.sendRedirect("/xmltodb/sexpire.html"); 
237
      } 
238
    }    
239
// End of Jivka added
240

    
241
    if (action.equals("query") || action.equals("squery")) {
242
      handleQueryAction(out, params, response);
243
    } else if (action.equals("getdocument")) {
244
      try {
245
        handleGetDocumentAction(out, params, response);
246
      } catch (ClassNotFoundException e) {
247
        out.println(e.getMessage());
248
      } catch (SQLException se) {
249
        out.println(se.getMessage());
250
      }
251
    } else if (action.equals("insert") || action.equals("update")) {
252
      handleInsertOrUpdateAction(out, params, response);
253
    } else if (action.equals("delete")) {
254
      handleDeleteAction(out, params, response);
255
    } else if (action.equals("validate")) {
256
      handleValidateAction(out, params, response);  
257
    } else if (action.equals("getdatadoc")) {
258
      handleGetDataDocumentAction(out, params, response);  
259
    } else if (action.equals("getdoctypes")) {
260
      handleGetDoctypesAction(out, params, response);  
261
    } else if (action.equals("getdataguide")) {
262
      handleGetDataGuideAction(out, params, response);  
263
    } else if (action.equals("Login") || action.equals("Login Client")) {
264
    } else {
265
      out.println("Error: action not registered.  Please report this error.");
266
    }
267

    
268
    // Close the stream to the client
269
    out.close();
270
  }
271

    
272
// Jivka added
273
  /** 
274
   * Handle the Login request. Create a new session object.
275
   * Make a user authentication through SRB RMI Connection.
276
   */
277

    
278
  private void handleLoginAction(PrintWriter out, Hashtable params, 
279
               HttpServletRequest request, HttpServletResponse response) {
280

    
281
    MetaCatSession sess = null;
282
    String un = ((String[])params.get("username"))[0];
283
    String pw = ((String[])params.get("password"))[0];
284
    String action = ((String[])params.get("action"))[0];
285
    
286
    try {
287
        sess = new MetaCatSession(request, un, pw);
288
    } catch (Exception e) {
289
      out.println(e.getMessage());
290
    }
291

    
292
    if ( un.equals("anonymous") ) {
293
            try {
294
                if (action.equals("Login Client")) {
295
                    out.println("<?xml version=\"1.0\"?>");
296
                    out.println("<success>");
297
                    out.println("User Authentication successful.");
298
                    out.println("</success>");
299
                    return;
300
                } else {
301
                    response.sendRedirect(
302
                    response.encodeRedirectUrl("/xmltodb/index.html"));
303
                }    
304
            } catch ( java.io.IOException ioe) {
305
                sess.disconnect();            
306
                out.println("<?xml version=\"1.0\"?>");
307
                out.println("<error>");
308
                out.println("MetaCatServlet.handleLoginAction() - " +
309
                            "Error on redirect of HttpServletResponse: " + 
310
                            ioe.getMessage());
311
                out.println("</error>");
312
                return;
313
            }                
314
    }    
315

    
316
    try { 
317
        if (sess.userAuth(un, pw)) {
318
            try {
319
                if (action.equals("Login Client")) {
320
                    out.println("<?xml version=\"1.0\"?>");
321
                    out.println("<success>");
322
                    out.println("User Authentication successful.");
323
                    out.println("</success>");
324
                } else {
325
                    response.sendRedirect(
326
                    response.encodeRedirectUrl("/xmltodb/metacat.html"));
327
                }    
328
            } catch ( java.io.IOException ioe) {
329
                sess.disconnect();            
330
                out.println("<?xml version=\"1.0\"?>");
331
                out.println("<error>");
332
                out.println("MetaCatServlet.handleLoginAction() - " +
333
                            "Error on redirect of HttpServletResponse: " + 
334
                            ioe.getMessage());
335
                out.println("</error>");
336
            }                
337
                
338
        } else {
339
            sess.disconnect();            
340
            out.println("<?xml version=\"1.0\"?>");
341
            out.println("<error>");
342
            out.println("SRB Connection failed. " +
343
                        "SRB RMI Server is not running now or " +
344
                        "user " + un + 
345
                        " has not been authenticated to use the system.");
346
            out.println("</error>");
347
        }    
348
    } catch ( java.rmi.RemoteException re) {
349
            sess.disconnect();            
350
            out.println("<?xml version=\"1.0\"?>");
351
            out.println("<error>");
352
            out.println("SRB Connection failed. " + re.getMessage());
353
            out.println("</error>");
354
    }        
355
  }
356

    
357
  /** 
358
   * Handle the database query request and return a result set, possibly
359
   * transformed from XML into HTML
360
   */
361
  private void handleQueryAction(PrintWriter out, Hashtable params, 
362
               HttpServletResponse response) {
363
      String action = ((String[])params.get("action"))[0];
364
      String query = ((String[])params.get("query"))[0]; 
365
      Hashtable doclist = null;
366
      String[] doctypeArr = null;
367
      String doctype = null;
368
      Reader xmlquery = null;
369
      Connection conn = null;
370

    
371
      // Run the query if it is a structured query
372
      // or, if it is a free-text, simple query,
373
      // format it first as a structured query and then run it
374
      if (action.equals("query")) {
375
        doctypeArr = (String[])params.get("doctype");
376
        doctype = null;
377
        if (doctypeArr != null) {
378
          doctype = ((String[])params.get("doctype"))[0]; 
379
        }
380

    
381
        if (doctype != null) {
382
          xmlquery = new StringReader(DBQuery.createQuery(query,doctype));
383
        } else {
384
          xmlquery = new StringReader(DBQuery.createQuery(query));
385
        }
386
      } else if (action.equals("squery")) {
387
        xmlquery = new StringReader(query);
388
      } else {
389
        System.err.println("Error handling query -- illegal action value");
390
      }
391

    
392
      try {
393

    
394
        conn = util.getConnection();
395
        DBQuery queryobj = new DBQuery(conn, saxparser);
396
        doclist = queryobj.findDocuments(xmlquery);
397
        util.returnConnection(conn);
398

    
399
      } catch (Exception e) {
400
        if ( conn != null ) { util.returnConnection(conn); }
401
        response.setContentType("text/html");
402
        out.println(e.getMessage());
403
        return;
404
      }    
405

    
406
      // Create a buffer to hold the xml result
407
      StringBuffer resultset = new StringBuffer();
408
 
409
      // Print the resulting root nodes
410
      String docid;
411
      String document = null;
412
      resultset.append("<?xml version=\"1.0\"?>\n");
413
      //resultset.append("<!DOCTYPE resultset PUBLIC " +
414
      //               "\"-//NCEAS//resultset//EN\" \"resultset.dtd\">\n");
415
      resultset.append("<resultset>\n");
416
  // following line removed by Dan Higgins to avoid insertion of query XML inside returned XML doc
417
  //    resultset.append("  <query>" + query + "</query>");   
418
      Enumeration doclistkeys = doclist.keys(); 
419
      while (doclistkeys.hasMoreElements()) {
420
        docid = (String)doclistkeys.nextElement();
421
        document = (String)doclist.get(docid);
422
        resultset.append("  <document>" + document + "</document>");
423
      }
424
      resultset.append("</resultset>");
425

    
426
      String qformat = ((String[])params.get("qformat"))[0]; 
427
      if (qformat.equals("xml")) {
428
        // set content type and other response header fields first
429
        response.setContentType("text/xml");
430
        out.println(resultset.toString());
431
      } else if (qformat.equals("html")) {
432
        // set content type and other response header fields first
433
        response.setContentType("text/html");
434
        //out.println("Converting to HTML...");
435
        XMLDocumentFragment htmldoc = null;
436
        try {
437
          XSLStylesheet style = new XSLStylesheet(
438
                                    new URL(resultStyleURL), null);
439
          htmldoc = (new XSLProcessor()).processXSL(style, 
440
                     (Reader)(new StringReader(resultset.toString())),null);
441
          htmldoc.print(out);
442
        } catch (Exception e) {
443
          out.println("Error transforming document:\n" + e.getMessage());
444
        }
445
      }
446
  }
447

    
448
  /** 
449
   * Handle the database getdocument request and return a XML document, 
450
   * possibly transformed from XML into HTML
451
   */
452
  private void handleGetDocumentAction(PrintWriter out, Hashtable params, 
453
               HttpServletResponse response) 
454
               throws ClassNotFoundException, IOException, SQLException {
455
    String docidstr = null;
456
    String docid = null;
457
    String doc = null;
458
    Connection conn = null;
459
    
460
    try {
461
      // Find the document id number
462
      docidstr = ((String[])params.get("docid"))[0]; 
463
      //docid = (new Long(docidstr)).longValue();
464
      docid = docidstr;
465

    
466
      conn = util.getConnection();
467
      DBReader docreader = new DBReader(conn);
468
      DBTransform dbt = new DBTransform(conn);
469
      
470
      // Get the document indicated fromthe db
471
      doc = docreader.readXMLDocument(docid);
472

    
473
      // Return the document in XML or HTML format
474
      String qformat = ((String[])params.get("qformat"))[0]; 
475
      if (qformat.equals("xml")) {
476
        // set content type and other response header fields first
477
        response.setContentType("text/xml");
478
        out.println(doc);
479
      } else if (qformat.equals("html")) {
480
        // set content type and other response header fields first
481
        response.setContentType("text/html");
482

    
483
        // Look up the document type
484
        String sourcetype = docreader.getDoctypeInfo(docid).getDoctype();
485

    
486
        // Transform the document to the new doctype
487
        dbt.transformXMLDocument(doc, sourcetype, "-//W3C//HTML//EN", out);
488
      }
489
    } catch (NullPointerException npe) {
490
      response.setContentType("text/html");
491
      out.println("Error getting document ID: " + docidstr +" (" + docid + ")");
492
    } catch (Exception e) {
493
      response.setContentType("text/html");
494
      out.println(e.getMessage());
495
    } finally {
496
      util.returnConnection(conn);
497
    }    
498

    
499
  }
500

    
501
  /** 
502
   * Handle the database putdocument request and write an XML document 
503
   * to the database connection
504
   */
505
  private void handleInsertOrUpdateAction(PrintWriter out, Hashtable params, 
506
               HttpServletResponse response) {
507

    
508
    Connection conn = null;
509

    
510
    try {
511
      // Get the document indicated
512
      String[] doctext = (String[])params.get("doctext");
513
      StringReader xml = null;
514
      try {
515
        xml = new StringReader(doctext[0]);
516

    
517
        String[] action = (String[])params.get("action");
518
        String[] docid = (String[])params.get("docid");
519
        String newdocid = null;
520

    
521
        String doAction = null;
522
        if (action[0].equals("insert")) {
523
          doAction = "INSERT";
524
        } else if (action[0].equals("update")) {
525
          doAction = "UPDATE";
526
        }
527

    
528
        try {
529
            // get a connection from the pool
530
            conn = util.getConnection();
531
            // write the document to the database
532
            DBWriter dbw = new DBWriter(conn, saxparser);
533

    
534
            try {
535
                String accNumber = docid[0];
536
                if (accNumber.equals("")) {
537
                    accNumber = null;
538
                }
539
                newdocid = dbw.write(xml, doAction, accNumber);  
540
            } catch (NullPointerException npe) {
541
              newdocid = dbw.write(xml, doAction, null);  
542
            }
543
        } catch (Exception e) {
544
          response.setContentType("text/html");
545
          out.println(e.getMessage());
546
        } finally {
547
          util.returnConnection(conn);
548
        }    
549

    
550
        // set content type and other response header fields first
551
        response.setContentType("text/xml");
552
        out.println("<?xml version=\"1.0\"?>");
553
        out.println("<success>");
554
        out.println("<docid>" + newdocid + "</docid>"); 
555
        out.println("</success>");
556

    
557
      } catch (NullPointerException npe) {
558
        response.setContentType("text/xml");
559
        out.println("<?xml version=\"1.0\"?>");
560
        out.println("<error>");
561
        out.println(npe.getMessage()); 
562
        out.println("</error>");
563
      }
564
    } catch (Exception e) {
565
      response.setContentType("text/xml");
566
      out.println("<?xml version=\"1.0\"?>");
567
      out.println("<error>");
568
      out.println(e.getMessage()); 
569
      if (e instanceof SAXException) {
570
        Exception e2 = ((SAXException)e).getException();
571
        out.println("<error>");
572
        out.println(e2.getMessage()); 
573
        out.println("</error>");
574
      }
575
      //e.printStackTrace(out);
576
      out.println("</error>");
577
    }
578
  }
579

    
580
  /** 
581
   * Handle the database delete request and delete an XML document 
582
   * from the database connection
583
   */
584
  private void handleDeleteAction(PrintWriter out, Hashtable params, 
585
               HttpServletResponse response) {
586

    
587
    String[] docid = (String[])params.get("docid");
588
    Connection conn = null;
589

    
590
    // delete the document from the database
591
    try {
592
      // get a connection from the pool
593
      conn = util.getConnection();
594
      DBWriter dbw = new DBWriter(conn, saxparser);
595
                                      // NOTE -- NEED TO TEST HERE
596
                                      // FOR EXISTENCE OF PARAM
597
                                      // BEFORE ACCESSING ARRAY
598
      try {
599
        dbw.delete(docid[0]);
600
        response.setContentType("text/xml");
601
        out.println("<?xml version=\"1.0\"?>");
602
        out.println("<success>");
603
        out.println("Document deleted."); 
604
        out.println("</success>");
605
      } catch (AccessionNumberException ane) {
606
        response.setContentType("text/xml");
607
        out.println("<?xml version=\"1.0\"?>");
608
        out.println("<error>");
609
        out.println("Error deleting document!!!");
610
        out.println(ane.getMessage()); 
611
        out.println("</error>");
612
      }
613
    } catch (Exception e) {
614
      response.setContentType("text/xml");
615
      out.println("<?xml version=\"1.0\"?>");
616
      out.println("<error>");
617
      out.println(e.getMessage()); 
618
      out.println("</error>");
619
    } finally {
620
      util.returnConnection(conn);
621
    }  
622
  }
623
  
624
  /** 
625
   * Handle the validtion request and return the results to the requestor
626
   */
627
  private void handleValidateAction(PrintWriter out, Hashtable params, 
628
               HttpServletResponse response) {
629

    
630
    // Get the document indicated
631
    String valtext = null;
632
    
633
    try {
634
      valtext = ((String[])params.get("valtext"))[0];
635
    } catch (Exception nullpe) {
636

    
637
      Connection conn = null;
638
      String docid = null;
639
      try {
640
        // Find the document id number
641
        docid = ((String[])params.get("docid"))[0]; 
642

    
643
        // get a connection from the pool
644
        conn = util.getConnection();
645
        DBReader docreader = new DBReader(conn);
646
        // Get the document indicated from the db
647
        valtext = docreader.readXMLDocument(docid);
648

    
649
      } catch (NullPointerException npe) {
650
        response.setContentType("text/xml");
651
        out.println("<error>Error getting document ID: " + docid + "</error>");
652
        if ( conn != null ) { util.returnConnection(conn); }
653
        return; // Jivka added
654
      } catch (Exception e) {
655
        response.setContentType("text/html");
656
        out.println(e.getMessage()); 
657
      } finally {
658
        util.returnConnection(conn);
659
      }  
660
    }
661

    
662
    Connection conn = null;
663
    try {
664
      // get a connection from the pool
665
      conn = util.getConnection();
666
      DBValidate valobj = new DBValidate(saxparser,conn);
667
      boolean valid = valobj.validateString(valtext);
668

    
669
      // set content type and other response header fields first
670
      response.setContentType("text/xml");
671
      out.println(valobj.returnErrors());
672

    
673
    } catch (NullPointerException npe2) {
674
      // set content type and other response header fields first
675
      response.setContentType("text/xml");
676
      out.println("<error>Error validating document.</error>"); 
677
    } catch (Exception e) {
678
      response.setContentType("text/html");
679
      out.println(e.getMessage()); 
680
    } finally {
681
      util.returnConnection(conn);
682
    }  
683
  }
684

    
685
  /** 
686
   * Handle the document request and return the results 
687
   * to the requestor
688
   */
689
  private void handleGetDataDocumentAction(PrintWriter out, Hashtable params, 
690
               HttpServletResponse response) {
691
      boolean error_flag = false;
692
      String error_message = "";
693
      // Get the document indicated
694
      String[] datadoc = (String[])params.get("datadoc");
695
      // defaultdatapath = "C:\\Temp\\";    // for testing only!!!
696
      // executescript = "test.bat";        // for testing only!!!
697
      
698
      // set content type and other response header fields first
699
      response.setContentType("application/octet-stream");
700
      if (defaultdatapath!=null) {
701
        if(!defaultdatapath.endsWith(System.getProperty("file.separator"))) {
702
          defaultdatapath=defaultdatapath+System.getProperty("file.separator");
703
        }
704
        System.out.println("Path= "+defaultdatapath+datadoc[0]);
705
        if (executescript!=null) {
706
          String command = null;
707
          File scriptfile = new File(executescript);
708
          if (scriptfile.exists()) {
709
            command=executescript+" "+datadoc[0]; // script includes path
710
        } else {     // look in defaultdatapath
711
            // on Win98 one MUST include the .bat extender
712
            command = defaultdatapath+executescript+" "+datadoc[0];  
713
        }
714
      System.out.println(command);
715
      try {
716
      Process proc = Runtime.getRuntime().exec(command);
717
      proc.waitFor();
718
      }
719
      catch (Exception eee) {
720
        System.out.println("Error running process!");
721
        error_flag = true;
722
        error_message = "Error running process!";}
723
      } // end executescript not null if
724
      File datafile = new File(defaultdatapath+datadoc[0]);
725
      try {
726
      FileInputStream fw = new FileInputStream(datafile);
727
      int x;
728
      while ((x = fw.read())!=-1) {
729
        out.write(x); }
730
        fw.close();
731
      } catch (Exception e) {
732
        System.out.println("Error in returning file\n"+e.getMessage());
733
        error_flag=true;
734
        error_message = error_message+"\nError in returning file\n"+
735
                        e.getMessage();
736
      }
737
    } // end defaultdatapath not null if
738
  }
739
  
740
  /** 
741
   * Handle the getdoctypes Action.
742
   * Read all doctypes from db connection in XML format
743
   */
744

    
745
  private void handleGetDoctypesAction(PrintWriter out, Hashtable params, 
746
                                       HttpServletResponse response) {
747

    
748
    Connection conn = null;
749
    
750
    try {
751

    
752
        // get connection from the pool
753
        conn = util.getConnection();
754
        DBUtil dbutil = new DBUtil(conn);
755
        String doctypes = dbutil.readDoctypes();
756
        out.println(doctypes);
757

    
758
    } catch (Exception e) {
759
      out.println("<?xml version=\"1.0\"?>");
760
      out.println("<error>");
761
      out.println(e.getMessage());
762
      out.println("</error>");
763
    } finally {
764
      util.returnConnection(conn);
765
    }  
766
    
767
  }
768

    
769
  /** 
770
   * Handle the getdataguide Action.
771
   * Read Data Guide for a given doctype from db connection in XML format
772
   */
773

    
774
  private void handleGetDataGuideAction(PrintWriter out, Hashtable params, 
775
                                        HttpServletResponse response) {
776

    
777
    Connection conn = null;
778
    String doctype = null;
779
    String[] doctypeArr = (String[])params.get("doctype");
780

    
781
    // get only the first doctype specified in the list of doctypes
782
    // it could be done for all doctypes in that list
783
    if (doctypeArr != null) {
784
        doctype = ((String[])params.get("doctype"))[0]; 
785
    }
786

    
787
    try {
788

    
789
        // get connection from the pool
790
        conn = util.getConnection();
791
        DBUtil dbutil = new DBUtil(conn);
792
        String dataguide = dbutil.readDataGuide(doctype);
793
        out.println(dataguide);
794

    
795
    } catch (Exception e) {
796
      out.println("<?xml version=\"1.0\"?>");
797
      out.println("<error>");
798
      out.println(e.getMessage());
799
      out.println("</error>");
800
    } finally {
801
      util.returnConnection(conn);
802
    }  
803
    
804
  }
805

    
806
}
807

    
808
/**
809
 * '$Log$
810
 * 'Revision 1.60  2000/08/09 00:39:47  jones
811
 * '-Reorganized xmltodb module to support new install process for the new
812
 * 'linux server (dev.nceas.ucsb.edu).  Added "build.sh" shell script that
813
 * 'calls ant withthe proper umask set for installation.  Use:
814
 * '
815
 * '  ./build.sh install
816
 * '
817
 * 'to post a new copy of the servlet and its supporting files to the install
818
 * 'directory defined in build.xml.
819
 * '
820
 * '-Updated the servlet to use a new servlet prefix that we'll use with the
821
 * 'Tomcat servlet engine.
822
 * '
823
 * '-Update bin dir shell scripts to reflect new locations of relevant jar files.
824
 * '
825
 * 'Revision 1.59  2000/08/08 00:31:20  bojilova
826
 * 'rearrange html pages for login and metacat access
827
 * '
828
 * 'Revision 1.58  2000/08/04 23:34:09  bojilova
829
 * 'more precise handling of the Connection Pool
830
 * '
831
 * 'Revision 1.57  2000/08/03 23:20:31  bojilova
832
 * 'Changes related to "getdataguide" action
833
 * '
834
 * 'Revision 1.55  2000/08/01 18:26:50  bojilova
835
 * 'added Pool of Connections
836
 * 'DBQuery, DBReader, DBTransform, DBUtil are created on every request and use the connections from the Pool
837
 * 'same with DBWriter and DBValidate
838
 * '
839
 * 'Revision 1.54  2000/07/27 23:12:21  bojilova
840
 * 'Added "getdoctypes" and "getdataguide" action handlers
841
 * '
842
 * 'Revision 1.53  2000/07/26 20:48:29  bojilova
843
 * 'Added "Login Client" action for login from the Desktop Client
844
 * '
845
 * 'Revision 1.52  2000/07/26 20:38:40  higgins
846
 * 'no message
847
 * '
848
 * 'Revision 1.51  2000/07/01 01:09:44  jones
849
 * 'MetaCatServlet.java
850
 * '
851
 * 'Revision 1.50  2000/06/30 23:42:33  bojilova
852
 * 'finished user auth & session tracking
853
 * '
854
 * 'Revision 1.49  2000/06/29 23:27:08  jones
855
 * 'Fixed bug in DBEntityResolver so that it now properly delegates to
856
 * 'the system id found inthe database.
857
 * 'Changed DBValidate to use DBEntityResolver, rather than the OASIS
858
 * 'catalog, and to return validation results in XML format.
859
 * '
860
 * 'Revision 1.48  2000/06/29 20:04:51  bojilova
861
 * 'testing login
862
 * '
863
 * 'Revision 1.36  2000/06/28 02:36:26  jones
864
 * 'Added feature to now ouput COMMENTs and PIs when the document is
865
 * 'read from the database with DBReader.
866
 * '
867
 * 'Revision 1.35  2000/06/28 00:00:47  bojilova
868
 * 'changed to
869
 * 'response.sendRedirect(response.encodeRedirectUrl("/xmltodb/lib/index.html"));
870
 * '
871
 * 'Revision 1.33  2000/06/27 04:50:33  jones
872
 * 'Updated javadoc documentation.
873
 * '
874
 * 'Revision 1.32  2000/06/27 04:31:07  jones
875
 * 'Fixed bugs associated with the new UPDATE and DELETE functions of
876
 * 'DBWriter.  There were problematic interactions between some static
877
 * 'variables used in DBEntityResolver and the way in which the
878
 * 'Servlet objects are re-used across multiple client invocations.
879
 * '
880
 * 'Generally cleaned up error reporting.  Now all errors and success
881
 * 'results are reported as XML documents from MetaCatServlet.  Need
882
 * 'to make the command line tools do the same.
883
 * '
884
 * 'Revision 1.31  2000/06/26 10:35:05  jones
885
 * 'Merged in substantial changes to DBWriter and associated classes and to
886
 * 'the MetaCatServlet in order to accomodate the new UPDATE and DELETE
887
 * 'functions.  The command line tools and the parameters for the
888
 * 'servlet have changed substantially.
889
 * '
890
 * 'Revision 1.30.2.6  2000/06/26 10:18:06  jones
891
 * 'Partial fix for MetaCatServlet INSERT?UPDATE bug.  Only will work on
892
 * 'the first call to the servlet.  Subsequent calls fail.  Seems to be
893
 * 'related to exception handling.  Multiple successive DELETE actions
894
 * 'work fine.
895
 * '
896
 * 'Revision 1.30.2.5  2000/06/26 09:09:53  jones
897
 * 'Modified MetaCatServlet and associated files to handle the UPDATE
898
 * 'and DELETE actions for DBWriter.
899
 * '
900
 * 'Revision 1.30.2.4  2000/06/26 00:51:06  jones
901
 * 'If docid passed to DBWriter.write() is not unique, classes now generate
902
 * 'an AccessionNumberException containing the new docid generated as a
903
 * 'replacement.  The docid is then extracted from the exception and
904
 * 'returned to the calling application for user feedback or client processing.
905
 * '
906
 * 'Revision 1.30.2.3  2000/06/25 23:38:17  jones
907
 * 'Added RCSfile keyword
908
 * '
909
 * 'Revision 1.30.2.2  2000/06/25 23:34:18  jones
910
 * 'Changed documentation formatting, added log entries at bottom of source files
911
 * ''
912
 */
(19-19/25)