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-02 16:26:35 -0700 (Wed, 02 Aug 2000) $'
10
 * '$Revision: 311 $'
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
  /** Handle "GET" method requests from HTTP clients */
128
  public void doGet (HttpServletRequest request, HttpServletResponse response)
129
    throws ServletException, IOException {
130

    
131
    // Process the data and send back the response
132
    handleGetOrPost(request, response);
133
  }
134

    
135
  /** Handle "POST" method requests from HTTP clients */
136
  public void doPost( HttpServletRequest request, HttpServletResponse response)
137
    throws ServletException, IOException {
138

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

    
143
  /**
144
   * Control servlet response depending on the action parameter specified
145
   */
146
  private void handleGetOrPost(HttpServletRequest request, 
147
    HttpServletResponse response) 
148
    throws ServletException, IOException {
149

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

    
175
      // Decode the docid and mouse click information
176
      if (name.endsWith(".y")) {
177
        docid[0] = name.substring(0,name.length()-2);
178
        //out.println("docid => " + docid[0]);
179
        params.put("docid", docid);
180
        name = "ypos";
181
      }
182
      if (name.endsWith(".x")) {
183
        name = "xpos";
184
      }
185

    
186
      //out.println(name + " => " + value[0]);
187
      params.put(name,value);
188
    }
189

    
190
    // Determine what type of request the user made
191
    // if the action parameter is set, use it as a default
192
    // but if the ypos param is set, calculate the action needed
193
    String action = ((String[])params.get("action"))[0];
194
    long ypos = 0;
195
    try {
196
      ypos = (new Long(((String[])params.get("ypos"))[0]).longValue());
197
      //out.println("<P>YPOS IS " + ypos);
198
      if (ypos <= 13) {
199
        action = "getdocument";
200
      } else if (ypos > 13 && ypos <= 27) {
201
        action = "validate";
202
      } else if (ypos > 27) {
203
        action = "transform";
204
      //} else {
205
      //  action = "";
206
      }
207
    } catch (Exception npe) {
208
      //out.println("<P>Caught exception looking for Y value.");
209
    }
210

    
211
// Jivka added  
212
    String username = null;
213
    // handle login action
214
    if (action.equals("Login") || action.equals("Login Client")) {
215
      handleLoginAction(out, params, request, response);
216
    // handle logout action  
217
    } else if (action.equals("Logout")) {
218
      HttpSession sess = request.getSession(false);
219
      if (sess != null) { sess.invalidate();  }    
220
      response.sendRedirect("/xmltodb/lib/login.html"); 
221
    // aware of session expiration on every request  
222
    } else {    
223
      HttpSession sess = request.getSession(false);
224
      //HttpSession sess = request.getSession(true);
225
      if (sess == null) { 
226
        // session expired or has not been stored b/w user requests
227
        // redirect to session expiration message page
228
        response.sendRedirect("/xmltodb/lib/sexpire.html"); 
229
      }
230
      username = (String)sess.getValue("username");
231
    }    
232
// End of Jivka added
233

    
234
    if (action.equals("query") || action.equals("squery")) {
235
      handleQueryAction(out, params, response);
236
    } else if (action.equals("getdocument")) {
237
      try {
238
        handleGetDocumentAction(out, params, response);
239
      } catch (ClassNotFoundException e) {
240
        out.println(e.getMessage());
241
      } catch (SQLException se) {
242
        out.println(se.getMessage());
243
      }
244
    } else if (action.equals("insert") || action.equals("update")) {
245
      if ( username == "anonymous" ) {
246
        out.println("You are not authorized to use that option.");
247
      } else {
248
        handleInsertOrUpdateAction(out, params, response);
249
      }
250
    } else if (action.equals("delete")) {
251
      if ( username == "anonymous" ) {
252
        out.println("You are not authorized to use that option");
253
      } else {
254
        handleDeleteAction(out, params, response);
255
      }
256
    } else if (action.equals("validate")) {
257
      if ( username == "anonymous" ) {
258
        out.println("You are not authorized to use that option");
259
      } else {
260
        handleValidateAction(out, params, response);  
261
      }
262
    } else if (action.equals("getdatadoc")) {
263
      handleGetDataDocumentAction(out, params, response);  
264
    } else if (action.equals("getdoctypes")) {
265
      handleGetDoctypesAction(out, params, response);  
266
    } else if (action.equals("getdataguide")) {
267
      handleGetDataGuideAction(out, params, response);  
268
    } else if (action.equals("Login") || action.equals("Login Client")) {
269
    } else {
270
      out.println("Error: action not registered.  Please report this error.");
271
    }
272

    
273
    // Close the stream to the client
274
    out.close();
275
  }
276

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

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

    
286
    MetaCatSession sess = null;
287
    String un = ((String[])params.get("username"))[0];
288
    String pw = ((String[])params.get("password"))[0];
289
    String action = ((String[])params.get("action"))[0];
290

    
291
    try {
292
        sess = new MetaCatSession(request, un, pw);
293
    } catch (Exception e) {
294
      out.println(e.getMessage());
295
    }
296

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

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

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

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

    
388
      try {
389
        conn = util.getConnection();
390
        DBQuery queryobj = new DBQuery(conn, saxparser);
391
        doclist = queryobj.findDocuments(xmlquery);
392
      } catch (Exception e) {
393
        response.setContentType("text/html");
394
        out.println(e.getMessage());
395
        return;
396
      } finally {
397
        if ( conn != null ) { util.returnConnection(conn); }
398
      }    
399
/*
400
      if (queryobj != null) {
401
          doclist = queryobj.findDocuments(xmlquery);
402
      } else {
403
        out.println("Query Object Init failed.");
404
        return;
405
      }
406
*/
407
      // Create a buffer to hold the xml result
408
      StringBuffer resultset = new StringBuffer();
409
 
410
      // Print the resulting root nodes
411
      String docid;
412
      String document = null;
413
      resultset.append("<?xml version=\"1.0\"?>\n");
414
      //resultset.append("<!DOCTYPE resultset PUBLIC " +
415
      //               "\"-//NCEAS//resultset//EN\" \"resultset.dtd\">\n");
416
      resultset.append("<resultset>\n");
417
  // following line removed by Dan Higgins to avoid insertion of query XML inside returned XML doc
418
  //    resultset.append("  <query>" + query + "</query>");   
419
      Enumeration doclistkeys = doclist.keys(); 
420
      while (doclistkeys.hasMoreElements()) {
421
        docid = (String)doclistkeys.nextElement();
422
        document = (String)doclist.get(docid);
423
        resultset.append("  <document>" + document + "</document>");
424
      }
425
      resultset.append("</resultset>");
426

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

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

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

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

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

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

    
500
  }
501

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

    
509
    Connection conn = null;
510

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
779
    try {
780

    
781
        // get connection from the pool
782
        conn = util.getConnection();
783
        DBUtil dbutil = new DBUtil(conn);
784
        String dataguide = dbutil.readDataGuide("");
785
        out.println(dataguide);
786

    
787
    } catch (Exception e) {
788
      out.println("<?xml version=\"1.0\"?>");
789
      out.println("<error>");
790
      out.println(e.getMessage());
791
      out.println("</error>");
792
    } finally {
793
      if ( conn != null ) { util.returnConnection(conn); }
794
    }  
795
    
796
  }
797

    
798
}
799

    
800
/**
801
 * '$Log$
802
 * 'Revision 1.55  2000/08/01 18:26:50  bojilova
803
 * 'added Pool of Connections
804
 * 'DBQuery, DBReader, DBTransform, DBUtil are created on every request and use the connections from the Pool
805
 * 'same with DBWriter and DBValidate
806
 * '
807
 * 'Revision 1.54  2000/07/27 23:12:21  bojilova
808
 * 'Added "getdoctypes" and "getdataguide" action handlers
809
 * '
810
 * 'Revision 1.53  2000/07/26 20:48:29  bojilova
811
 * 'Added "Login Client" action for login from the Desktop Client
812
 * '
813
 * 'Revision 1.52  2000/07/26 20:38:40  higgins
814
 * 'no message
815
 * '
816
 * 'Revision 1.51  2000/07/01 01:09:44  jones
817
 * 'MetaCatServlet.java
818
 * '
819
 * 'Revision 1.50  2000/06/30 23:42:33  bojilova
820
 * 'finished user auth & session tracking
821
 * '
822
 * 'Revision 1.49  2000/06/29 23:27:08  jones
823
 * 'Fixed bug in DBEntityResolver so that it now properly delegates to
824
 * 'the system id found inthe database.
825
 * 'Changed DBValidate to use DBEntityResolver, rather than the OASIS
826
 * 'catalog, and to return validation results in XML format.
827
 * '
828
 * 'Revision 1.48  2000/06/29 20:04:51  bojilova
829
 * 'testing login
830
 * '
831
 * 'Revision 1.36  2000/06/28 02:36:26  jones
832
 * 'Added feature to now ouput COMMENTs and PIs when the document is
833
 * 'read from the database with DBReader.
834
 * '
835
 * 'Revision 1.35  2000/06/28 00:00:47  bojilova
836
 * 'changed to
837
 * 'response.sendRedirect(response.encodeRedirectUrl("/xmltodb/lib/index.html"));
838
 * '
839
 * 'Revision 1.33  2000/06/27 04:50:33  jones
840
 * 'Updated javadoc documentation.
841
 * '
842
 * 'Revision 1.32  2000/06/27 04:31:07  jones
843
 * 'Fixed bugs associated with the new UPDATE and DELETE functions of
844
 * 'DBWriter.  There were problematic interactions between some static
845
 * 'variables used in DBEntityResolver and the way in which the
846
 * 'Servlet objects are re-used across multiple client invocations.
847
 * '
848
 * 'Generally cleaned up error reporting.  Now all errors and success
849
 * 'results are reported as XML documents from MetaCatServlet.  Need
850
 * 'to make the command line tools do the same.
851
 * '
852
 * 'Revision 1.31  2000/06/26 10:35:05  jones
853
 * 'Merged in substantial changes to DBWriter and associated classes and to
854
 * 'the MetaCatServlet in order to accomodate the new UPDATE and DELETE
855
 * 'functions.  The command line tools and the parameters for the
856
 * 'servlet have changed substantially.
857
 * '
858
 * 'Revision 1.30.2.6  2000/06/26 10:18:06  jones
859
 * 'Partial fix for MetaCatServlet INSERT?UPDATE bug.  Only will work on
860
 * 'the first call to the servlet.  Subsequent calls fail.  Seems to be
861
 * 'related to exception handling.  Multiple successive DELETE actions
862
 * 'work fine.
863
 * '
864
 * 'Revision 1.30.2.5  2000/06/26 09:09:53  jones
865
 * 'Modified MetaCatServlet and associated files to handle the UPDATE
866
 * 'and DELETE actions for DBWriter.
867
 * '
868
 * 'Revision 1.30.2.4  2000/06/26 00:51:06  jones
869
 * 'If docid passed to DBWriter.write() is not unique, classes now generate
870
 * 'an AccessionNumberException containing the new docid generated as a
871
 * 'replacement.  The docid is then extracted from the exception and
872
 * 'returned to the calling application for user feedback or client processing.
873
 * '
874
 * 'Revision 1.30.2.3  2000/06/25 23:38:17  jones
875
 * 'Added RCSfile keyword
876
 * '
877
 * 'Revision 1.30.2.2  2000/06/25 23:34:18  jones
878
 * 'Changed documentation formatting, added log entries at bottom of source files
879
 * ''
880
 */
(19-19/25)