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-14 11:11:38 -0700 (Mon, 14 Aug 2000) $'
10
 * '$Revision: 345 $'
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") || action.equals("Logout Client")) {
227
      HttpSession sess = request.getSession(false);
228
      if (sess != null) { sess.invalidate();  }    
229
      if (action.equals("Logout Client")) {
230
        out.println("<?xml version=\"1.0\"?>");
231
        out.println("<success>");
232
        out.println("User logout.");
233
        out.println("</success>");
234
        return;
235
      }    
236
      response.sendRedirect("/xmltodb/login.html"); 
237
    // aware of session expiration on every request  
238
    } else {   
239
      HttpSession sess = request.getSession(true);
240
      if (sess.isNew()) { 
241
        // session expired or has not been stored b/w user requests
242
        // redirect to default page for query only access
243
      //  response.sendRedirect("/xmltodb/sexpire.html"); 
244
      } 
245
    }    
246
// End of Jivka added
247

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

    
275
    // Close the stream to the client
276
    out.close();
277
  }
278

    
279
// Jivka added
280
  /** 
281
   * Handle the Login request. Create a new session object.
282
   * Make a user authentication through SRB RMI Connection.
283
   */
284

    
285
  private void handleLoginAction(PrintWriter out, Hashtable params, 
286
               HttpServletRequest request, HttpServletResponse response) {
287

    
288
    MetaCatSession sess = null;
289
    String un = ((String[])params.get("username"))[0];
290
    String pw = ((String[])params.get("password"))[0];
291
    String action = ((String[])params.get("action"))[0];
292
    
293
    try {
294
        sess = new MetaCatSession(request, un, pw);
295
    } catch (Exception e) {
296
      out.println(e.getMessage());
297
    }
298

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

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

    
364
  /**
365
    *Create the squery xml and return it as a String.
366
    * @param params is the Hashtable of parameters that should be included
367
    * in the squery.
368
    */
369
  private String handleSQuery(Hashtable params)
370
  {
371
    //create the squery and return it to be processed
372
    String doctype = null;
373
    String[] doctypeArr = null;
374
    doctypeArr = (String[])params.get("doctype");
375
    doctype = null;
376
    if (doctypeArr != null) 
377
    {
378
      doctype = ((String[])params.get("doctype"))[0]; 
379
    }
380
    else
381
    {
382
      doctype="ANY"; 
383
    }
384
    return DBQuery.createSQuery(params, doctype);
385
  }
386
  
387
   /**
388
    *Create the query xml and return it as a String.
389
    * @param query is the free text query parameter returned through the CGI.
390
    * @param doctype is the doctype parameter returned through the CGI. 
391
    * If no doctype filter is required, set it to null or "".
392
    */
393
  private String handleQuery(Hashtable params)
394
  {
395
    String doctype=null;
396
    String[] doctypeArr=null;
397
    String query = ((String[])params.get("query"))[0]; 
398
    doctypeArr = (String[])params.get("doctype");
399
    doctype = null;
400
    if (doctypeArr != null) 
401
    {
402
      doctype = ((String[])params.get("doctype"))[0]; 
403
    }
404
    else
405
    {
406
      doctype="ANY"; 
407
    }
408
    return DBQuery.createQuery(query,doctype);
409
  }
410
  
411
  /**
412
    * Run the query and return a hashtable of results.
413
    */
414
  private Hashtable runQuery(Reader xmlquery)
415
  {
416
    Hashtable doclist=null;
417
    Connection conn = null;
418
    try
419
    {
420
        conn = util.getConnection();
421
        DBQuery queryobj = new DBQuery(conn, saxparser);
422
        doclist = queryobj.findDocuments(xmlquery);
423
        util.returnConnection(conn);
424
        return doclist;
425
    } 
426
    catch (Exception e) 
427
    {
428
      if (conn != null) 
429
      {
430
        util.returnConnection(conn); 
431
      }
432
      util.debugMessage("Error in runQuery: " + e.getMessage());
433
      doclist = null;
434
      return doclist;
435
    }    
436
  }
437
  
438
  private void transformDocument(Hashtable doclist, String qformat, 
439
                                 String xmlquery, PrintWriter out,
440
                                 HttpServletResponse response)
441
  {
442
    // Create a buffer to hold the xml result
443
    StringBuffer resultset = new StringBuffer();
444
 
445
    // Print the resulting root nodes
446
    String docid = null;
447
    String document = null;
448
    resultset.append("<?xml version=\"1.0\"?>\n");
449
    resultset.append("<resultset>\n");
450
    resultset.append("  <query>" + xmlquery + "</query>");   
451
    Enumeration doclistkeys = doclist.keys(); 
452
    while (doclistkeys.hasMoreElements()) 
453
    {
454
      docid = (String)doclistkeys.nextElement();
455
      document = (String)doclist.get(docid);
456
      resultset.append("  <document>" + document + "</document>");
457
    }
458
    resultset.append("</resultset>");
459

    
460
    if(qformat.equals("xml")) 
461
    {
462
      // set content type and other response header fields first
463
      response.setContentType("text/xml");
464
      out.println(resultset.toString());
465
    } 
466
    else if(qformat.equals("html")) 
467
    {
468
      // set content type and other response header fields first
469
      response.setContentType("text/html");
470
      XMLDocumentFragment htmldoc = null;
471
      try 
472
      {
473
        XSLStylesheet style = new XSLStylesheet(
474
                              new URL(resultStyleURL), null);
475
        htmldoc = (new XSLProcessor()).processXSL(style, 
476
                  (Reader)(new StringReader(resultset.toString())),null);
477
        htmldoc.print(out);
478
      } 
479
      catch (Exception e) 
480
      {
481
        out.println("Error transforming document:\n" + e.getMessage());
482
      }
483
    }
484
  }
485
                              
486
  /** 
487
   * Handle the database query request and return a result set, possibly
488
   * transformed from XML into HTML
489
   */
490
  private void handleQueryAction(PrintWriter out, Hashtable params, 
491
                                 HttpServletResponse response) 
492
  {
493
      String action = ((String[])params.get("action"))[0];
494
      Hashtable doclist = null;
495
      String[] doctypeArr = null;
496
      String doctype = null;
497
      Reader xmlquery = null;
498
      Connection conn = null;
499

    
500
      if(action.equals("query"))
501
      {
502
        xmlquery = new StringReader(handleQuery(params)); 
503
      }
504
      else if(action.equals("squery"))
505
      {
506
        xmlquery = new StringReader(handleSQuery(params)); 
507
      }
508
      
509
      doclist = runQuery(xmlquery);
510
      
511
      String qformat = ((String[])params.get("qformat"))[0]; 
512
      transformDocument(doclist, qformat, xmlquery.toString(), out, response);
513
  }
514

    
515
  /** 
516
   * Handle the database getdocument request and return a XML document, 
517
   * possibly transformed from XML into HTML
518
   */
519
  private void handleGetDocumentAction(PrintWriter out, Hashtable params, 
520
               HttpServletResponse response) 
521
               throws ClassNotFoundException, IOException, SQLException {
522
    String docidstr = null;
523
    String docid = null;
524
    String doc = null;
525
    Connection conn = null;
526
    
527
    try {
528
      // Find the document id number
529
      docidstr = ((String[])params.get("docid"))[0]; 
530
      //docid = (new Long(docidstr)).longValue();
531
      docid = docidstr;
532

    
533
      conn = util.getConnection();
534
      DBReader docreader = new DBReader(conn);
535
      DBTransform dbt = new DBTransform(conn);
536
      
537
      // Get the document indicated fromthe db
538
      doc = docreader.readXMLDocument(docid);
539

    
540
      // Return the document in XML or HTML format
541
      String qformat = ((String[])params.get("qformat"))[0]; 
542
      if (qformat.equals("xml")) {
543
        // set content type and other response header fields first
544
        response.setContentType("text/xml");
545
        out.println(doc);
546
      } else if (qformat.equals("html")) {
547
        // set content type and other response header fields first
548
        response.setContentType("text/html");
549

    
550
        // Look up the document type
551
        String sourcetype = docreader.getDoctypeInfo(docid).getDoctype();
552

    
553
        // Transform the document to the new doctype
554
        dbt.transformXMLDocument(doc, sourcetype, "-//W3C//HTML//EN", out);
555
      }
556
    //} catch (NullPointerException npe) {
557
      //response.setContentType("text/html");
558
      //out.println("Error getting document ID: " + docidstr +" (" + docid + ")");
559
    } catch (McdbException e) {
560
      response.setContentType("text/xml");
561
      e.toXml(out);
562
    } catch (Throwable t) {
563
      response.setContentType("text/html");
564
      out.println(t.getMessage());
565
    } finally {
566
      util.returnConnection(conn);
567
    }    
568

    
569
  }
570

    
571
  /** 
572
   * Handle the database putdocument request and write an XML document 
573
   * to the database connection
574
   */
575
  private void handleInsertOrUpdateAction(PrintWriter out, Hashtable params, 
576
               HttpServletResponse response) {
577

    
578
    Connection conn = null;
579

    
580
    try {
581
      // Get the document indicated
582
      String[] doctext = (String[])params.get("doctext");
583
      StringReader xml = null;
584
      try {
585
        xml = new StringReader(doctext[0]);
586

    
587
        String[] action = (String[])params.get("action");
588
        String[] docid = (String[])params.get("docid");
589
        String newdocid = null;
590

    
591
        String doAction = null;
592
        if (action[0].equals("insert")) {
593
          doAction = "INSERT";
594
        } else if (action[0].equals("update")) {
595
          doAction = "UPDATE";
596
        }
597

    
598
        try {
599
            // get a connection from the pool
600
            conn = util.getConnection();
601
            // write the document to the database
602
            DBWriter dbw = new DBWriter(conn, saxparser);
603

    
604
            try {
605
                String accNumber = docid[0];
606
                if (accNumber.equals("")) {
607
                    accNumber = null;
608
                }
609
                newdocid = dbw.write(xml, doAction, accNumber);  
610
            } catch (NullPointerException npe) {
611
              newdocid = dbw.write(xml, doAction, null);  
612
            }
613
        } catch (Exception e) {
614
          response.setContentType("text/html");
615
          out.println(e.getMessage());
616
        } finally {
617
          util.returnConnection(conn);
618
        }    
619

    
620
        // set content type and other response header fields first
621
        response.setContentType("text/xml");
622
        out.println("<?xml version=\"1.0\"?>");
623
        out.println("<success>");
624
        out.println("<docid>" + newdocid + "</docid>"); 
625
        out.println("</success>");
626

    
627
      } catch (NullPointerException npe) {
628
        response.setContentType("text/xml");
629
        out.println("<?xml version=\"1.0\"?>");
630
        out.println("<error>");
631
        out.println(npe.getMessage()); 
632
        out.println("</error>");
633
      }
634
    } catch (Exception e) {
635
      response.setContentType("text/xml");
636
      out.println("<?xml version=\"1.0\"?>");
637
      out.println("<error>");
638
      out.println(e.getMessage()); 
639
      if (e instanceof SAXException) {
640
        Exception e2 = ((SAXException)e).getException();
641
        out.println("<error>");
642
        out.println(e2.getMessage()); 
643
        out.println("</error>");
644
      }
645
      //e.printStackTrace(out);
646
      out.println("</error>");
647
    }
648
  }
649

    
650
  /** 
651
   * Handle the database delete request and delete an XML document 
652
   * from the database connection
653
   */
654
  private void handleDeleteAction(PrintWriter out, Hashtable params, 
655
               HttpServletResponse response) {
656

    
657
    String[] docid = (String[])params.get("docid");
658
    Connection conn = null;
659

    
660
    // delete the document from the database
661
    try {
662
      // get a connection from the pool
663
      conn = util.getConnection();
664
      DBWriter dbw = new DBWriter(conn, saxparser);
665
                                      // NOTE -- NEED TO TEST HERE
666
                                      // FOR EXISTENCE OF PARAM
667
                                      // BEFORE ACCESSING ARRAY
668
      try {
669
        dbw.delete(docid[0]);
670
        response.setContentType("text/xml");
671
        out.println("<?xml version=\"1.0\"?>");
672
        out.println("<success>");
673
        out.println("Document deleted."); 
674
        out.println("</success>");
675
      } catch (AccessionNumberException ane) {
676
        response.setContentType("text/xml");
677
        out.println("<?xml version=\"1.0\"?>");
678
        out.println("<error>");
679
        out.println("Error deleting document!!!");
680
        out.println(ane.getMessage()); 
681
        out.println("</error>");
682
      }
683
    } catch (Exception e) {
684
      response.setContentType("text/xml");
685
      out.println("<?xml version=\"1.0\"?>");
686
      out.println("<error>");
687
      out.println(e.getMessage()); 
688
      out.println("</error>");
689
    } finally {
690
      util.returnConnection(conn);
691
    }  
692
  }
693
  
694
  /** 
695
   * Handle the validtion request and return the results to the requestor
696
   */
697
  private void handleValidateAction(PrintWriter out, Hashtable params, 
698
               HttpServletResponse response) {
699

    
700
    // Get the document indicated
701
    String valtext = null;
702
    
703
    try {
704
      valtext = ((String[])params.get("valtext"))[0];
705
    } catch (Exception nullpe) {
706

    
707
      Connection conn = null;
708
      String docid = null;
709
      try {
710
        // Find the document id number
711
        docid = ((String[])params.get("docid"))[0]; 
712

    
713
        // get a connection from the pool
714
        conn = util.getConnection();
715
        DBReader docreader = new DBReader(conn);
716
        // Get the document indicated from the db
717
        valtext = docreader.readXMLDocument(docid);
718

    
719
      } catch (NullPointerException npe) {
720
        response.setContentType("text/xml");
721
        out.println("<error>Error getting document ID: " + docid + "</error>");
722
        if ( conn != null ) { util.returnConnection(conn); }
723
        return; // Jivka added
724
      } catch (Exception e) {
725
        response.setContentType("text/html");
726
        out.println(e.getMessage()); 
727
      } finally {
728
        util.returnConnection(conn);
729
      }  
730
    }
731

    
732
    Connection conn = null;
733
    try {
734
      // get a connection from the pool
735
      conn = util.getConnection();
736
      DBValidate valobj = new DBValidate(saxparser,conn);
737
      boolean valid = valobj.validateString(valtext);
738

    
739
      // set content type and other response header fields first
740
      response.setContentType("text/xml");
741
      out.println(valobj.returnErrors());
742

    
743
    } catch (NullPointerException npe2) {
744
      // set content type and other response header fields first
745
      response.setContentType("text/xml");
746
      out.println("<error>Error validating document.</error>"); 
747
    } catch (Exception e) {
748
      response.setContentType("text/html");
749
      out.println(e.getMessage()); 
750
    } finally {
751
      util.returnConnection(conn);
752
    }  
753
  }
754

    
755
  /** 
756
   * Handle the document request and return the results 
757
   * to the requestor
758
   */
759
  private void handleGetDataDocumentAction(PrintWriter out, Hashtable params, 
760
               HttpServletResponse response) {
761
      boolean error_flag = false;
762
      String error_message = "";
763
      // Get the document indicated
764
      String[] datadoc = (String[])params.get("datadoc");
765
      // defaultdatapath = "C:\\Temp\\";    // for testing only!!!
766
      // executescript = "test.bat";        // for testing only!!!
767
      
768
      // set content type and other response header fields first
769
      response.setContentType("application/octet-stream");
770
      if (defaultdatapath!=null) {
771
        if(!defaultdatapath.endsWith(System.getProperty("file.separator"))) {
772
          defaultdatapath=defaultdatapath+System.getProperty("file.separator");
773
        }
774
        System.out.println("Path= "+defaultdatapath+datadoc[0]);
775
        if (executescript!=null) {
776
          String command = null;
777
          File scriptfile = new File(executescript);
778
          if (scriptfile.exists()) {
779
            command=executescript+" "+datadoc[0]; // script includes path
780
        } else {     // look in defaultdatapath
781
            // on Win98 one MUST include the .bat extender
782
            command = defaultdatapath+executescript+" "+datadoc[0];  
783
        }
784
      System.out.println(command);
785
      try {
786
      Process proc = Runtime.getRuntime().exec(command);
787
      proc.waitFor();
788
      }
789
      catch (Exception eee) {
790
        System.out.println("Error running process!");
791
        error_flag = true;
792
        error_message = "Error running process!";}
793
      } // end executescript not null if
794
      File datafile = new File(defaultdatapath+datadoc[0]);
795
      try {
796
      FileInputStream fw = new FileInputStream(datafile);
797
      int x;
798
      while ((x = fw.read())!=-1) {
799
        out.write(x); }
800
        fw.close();
801
      } catch (Exception e) {
802
        System.out.println("Error in returning file\n"+e.getMessage());
803
        error_flag=true;
804
        error_message = error_message+"\nError in returning file\n"+
805
                        e.getMessage();
806
      }
807
    } // end defaultdatapath not null if
808
  }
809
  
810
  /** 
811
   * Handle the getdoctypes Action.
812
   * Read all doctypes from db connection in XML format
813
   */
814

    
815
  private void handleGetDoctypesAction(PrintWriter out, Hashtable params, 
816
                                       HttpServletResponse response) {
817

    
818
    Connection conn = null;
819
    
820
    try {
821

    
822
        // get connection from the pool
823
        conn = util.getConnection();
824
        DBUtil dbutil = new DBUtil(conn);
825
        String doctypes = dbutil.readDoctypes();
826
        out.println(doctypes);
827

    
828
    } catch (Exception e) {
829
      out.println("<?xml version=\"1.0\"?>");
830
      out.println("<error>");
831
      out.println(e.getMessage());
832
      out.println("</error>");
833
    } finally {
834
      util.returnConnection(conn);
835
    }  
836
    
837
  }
838

    
839
  /** 
840
   * Handle the getdataguide Action.
841
   * Read Data Guide for a given doctype from db connection in XML format
842
   */
843

    
844
  private void handleGetDataGuideAction(PrintWriter out, Hashtable params, 
845
                                        HttpServletResponse response) {
846

    
847
    Connection conn = null;
848
    String doctype = null;
849
    String[] doctypeArr = (String[])params.get("doctype");
850

    
851
    // get only the first doctype specified in the list of doctypes
852
    // it could be done for all doctypes in that list
853
    if (doctypeArr != null) {
854
        doctype = ((String[])params.get("doctype"))[0]; 
855
    }
856

    
857
    try {
858

    
859
        // get connection from the pool
860
        conn = util.getConnection();
861
        DBUtil dbutil = new DBUtil(conn);
862
        String dataguide = dbutil.readDataGuide(doctype);
863
        out.println(dataguide);
864

    
865
    } catch (Exception e) {
866
      out.println("<?xml version=\"1.0\"?>");
867
      out.println("<error>");
868
      out.println(e.getMessage());
869
      out.println("</error>");
870
    } finally {
871
      util.returnConnection(conn);
872
    }  
873
    
874
  }
875

    
876
}
877

    
878
/**
879
 * '$Log$
880
 * 'Revision 1.64  2000/08/11 22:20:04  jones
881
 * 'Changed exception handling mechanisms for DBReader
882
 * '
883
 * 'Revision 1.63  2000/08/11 18:25:26  berkley
884
 * 'broke up handleQueryAction into handleQuery, handleSQuery, runQuery and transformDocument
885
 * '
886
 * 'Revision 1.61  2000/08/10 18:56:48  bojilova
887
 * 'added "anonymous" user connection
888
 * '
889
 * 'Revision 1.60  2000/08/09 00:39:47  jones
890
 * '-Reorganized xmltodb module to support new install process for the new
891
 * 'linux server (dev.nceas.ucsb.edu).  Added "build.sh" shell script that
892
 * 'calls ant withthe proper umask set for installation.  Use:
893
 * '
894
 * '  ./build.sh install
895
 * '
896
 * 'to post a new copy of the servlet and its supporting files to the install
897
 * 'directory defined in build.xml.
898
 * '
899
 * '-Updated the servlet to use a new servlet prefix that we'll use with the
900
 * 'Tomcat servlet engine.
901
 * '
902
 * '-Update bin dir shell scripts to reflect new locations of relevant jar files.
903
 * '
904
 * 'Revision 1.59  2000/08/08 00:31:20  bojilova
905
 * 'rearrange html pages for login and metacat access
906
 * '
907
 * 'Revision 1.58  2000/08/04 23:34:09  bojilova
908
 * 'more precise handling of the Connection Pool
909
 * '
910
 * 'Revision 1.57  2000/08/03 23:20:31  bojilova
911
 * 'Changes related to "getdataguide" action
912
 * '
913
 * 'Revision 1.55  2000/08/01 18:26:50  bojilova
914
 * 'added Pool of Connections
915
 * 'DBQuery, DBReader, DBTransform, DBUtil are created on every request and use the connections from the Pool
916
 * 'same with DBWriter and DBValidate
917
 * '
918
 * 'Revision 1.54  2000/07/27 23:12:21  bojilova
919
 * 'Added "getdoctypes" and "getdataguide" action handlers
920
 * '
921
 * 'Revision 1.53  2000/07/26 20:48:29  bojilova
922
 * 'Added "Login Client" action for login from the Desktop Client
923
 * '
924
 * 'Revision 1.52  2000/07/26 20:38:40  higgins
925
 * 'no message
926
 * '
927
 * 'Revision 1.51  2000/07/01 01:09:44  jones
928
 * 'MetaCatServlet.java
929
 * '
930
 * 'Revision 1.50  2000/06/30 23:42:33  bojilova
931
 * 'finished user auth & session tracking
932
 * '
933
 * 'Revision 1.49  2000/06/29 23:27:08  jones
934
 * 'Fixed bug in DBEntityResolver so that it now properly delegates to
935
 * 'the system id found inthe database.
936
 * 'Changed DBValidate to use DBEntityResolver, rather than the OASIS
937
 * 'catalog, and to return validation results in XML format.
938
 * '
939
 * 'Revision 1.48  2000/06/29 20:04:51  bojilova
940
 * 'testing login
941
 * '
942
 * 'Revision 1.36  2000/06/28 02:36:26  jones
943
 * 'Added feature to now ouput COMMENTs and PIs when the document is
944
 * 'read from the database with DBReader.
945
 * '
946
 * 'Revision 1.35  2000/06/28 00:00:47  bojilova
947
 * 'changed to
948
 * 'response.sendRedirect(response.encodeRedirectUrl("/xmltodb/lib/index.html"));
949
 * '
950
 * 'Revision 1.33  2000/06/27 04:50:33  jones
951
 * 'Updated javadoc documentation.
952
 * '
953
 * 'Revision 1.32  2000/06/27 04:31:07  jones
954
 * 'Fixed bugs associated with the new UPDATE and DELETE functions of
955
 * 'DBWriter.  There were problematic interactions between some static
956
 * 'variables used in DBEntityResolver and the way in which the
957
 * 'Servlet objects are re-used across multiple client invocations.
958
 * '
959
 * 'Generally cleaned up error reporting.  Now all errors and success
960
 * 'results are reported as XML documents from MetaCatServlet.  Need
961
 * 'to make the command line tools do the same.
962
 * '
963
 * 'Revision 1.31  2000/06/26 10:35:05  jones
964
 * 'Merged in substantial changes to DBWriter and associated classes and to
965
 * 'the MetaCatServlet in order to accomodate the new UPDATE and DELETE
966
 * 'functions.  The command line tools and the parameters for the
967
 * 'servlet have changed substantially.
968
 * '
969
 * 'Revision 1.30.2.6  2000/06/26 10:18:06  jones
970
 * 'Partial fix for MetaCatServlet INSERT?UPDATE bug.  Only will work on
971
 * 'the first call to the servlet.  Subsequent calls fail.  Seems to be
972
 * 'related to exception handling.  Multiple successive DELETE actions
973
 * 'work fine.
974
 * '
975
 * 'Revision 1.30.2.5  2000/06/26 09:09:53  jones
976
 * 'Modified MetaCatServlet and associated files to handle the UPDATE
977
 * 'and DELETE actions for DBWriter.
978
 * '
979
 * 'Revision 1.30.2.4  2000/06/26 00:51:06  jones
980
 * 'If docid passed to DBWriter.write() is not unique, classes now generate
981
 * 'an AccessionNumberException containing the new docid generated as a
982
 * 'replacement.  The docid is then extracted from the exception and
983
 * 'returned to the calling application for user feedback or client processing.
984
 * '
985
 * 'Revision 1.30.2.3  2000/06/25 23:38:17  jones
986
 * 'Added RCSfile keyword
987
 * '
988
 * 'Revision 1.30.2.2  2000/06/25 23:34:18  jones
989
 * 'Changed documentation formatting, added log entries at bottom of source files
990
 * ''
991
 */
(21-21/27)