Project

General

Profile

« Previous | Next » 

Revision 309

Added by bojilova over 24 years ago

added Pool of Connections
DBQuery, DBReader, DBTransform, DBUtil are created on every request and use the connections from the Pool
same with DBWriter and DBValidate

View differences:

src/edu/ucsb/nceas/metacat/MetaCatUtil.java
3 3
 *    Purpose: A Class that implements utility methods for a metadata catalog
4 4
 *  Copyright: 2000 Regents of the University of California and the
5 5
 *             National Center for Ecological Analysis and Synthesis
6
 *    Authors: Matt Jones
6
 *    Authors: Matt Jones, Jivka Bojilova
7 7
 * 
8 8
 *   '$Author$'
9 9
 *     '$Date$'
......
19 19
import java.sql.DriverManager;
20 20
import java.sql.SQLException;
21 21
import java.util.PropertyResourceBundle;
22
import java.util.Hashtable;
23
import java.util.Enumeration;
22 24

  
23 25
/**
24 26
 * A suite of utility classes for the metadata catalog server
......
27 29

  
28 30
  private PropertyResourceBundle options = null;
29 31
  private static String propertiesFile = "edu.ucsb.nceas.metacat.metacat";
32
  private Hashtable connectionPool = new Hashtable();
30 33
  private static boolean debug = false;
31 34

  
32 35
  /**
......
82 85
      return value;
83 86
  }
84 87

  
88
  /* Utility method to create and return a pool of Connection objects */
89
  public Hashtable getConnectionPool()
90
                throws SQLException, ClassNotFoundException {
91

  
92
    int initConn = (new Integer(getOption("initialConnections"))).intValue();
93
    
94
    for ( int i = 0; i < initConn; i++ ) {
95
        connectionPool.put( openDBConnection(), Boolean.FALSE );
96
    }    
97
    
98
    return connectionPool;
99
  }
100
  
101
  /* Utility method to get a unused Connection object from the pool */
102
  public Connection getConnection()
103
                throws SQLException, ClassNotFoundException {
104

  
105
    Connection conn = null;
106
    Enumeration connections = connectionPool.keys();
107
    
108
    synchronized (connectionPool) {
109
      while (connections.hasMoreElements()) {
110
        conn = (Connection)connections.nextElement();
111
        Boolean b = (Boolean)connectionPool.get(conn);
112
        
113
        if (b == Boolean.FALSE) {
114
            // unused connection; test if it works and get it
115
            try {
116
                conn.setAutoCommit(true);
117
            } catch (SQLException e) {
118
                // problem with the connection, replace it
119
                conn = openDBConnection();
120
            }    
121
            // update the pool to show this one taken
122
            connectionPool.put(conn, Boolean.TRUE);    
123
            return conn;
124
        }    
125
      }  
126
    }    
127
    
128
    // If we get here, there no free connections;
129
    // we need to make more
130
    int incConn = (new Integer(getOption("incrementConnections"))).intValue();
131
    for ( int i = 0; i < incConn; i++ ) {
132
        connectionPool.put( openDBConnection(), Boolean.FALSE );
133
    }
134
    
135
    // Recurse to get one of the new connections
136
    return getConnection();
137
  }
138
  
139
  /* Utility method to give the connection back to the pool */
140
  public void returnConnection (Connection returned) {
141
    
142
    Connection conn;
143
    Enumeration connections = connectionPool.keys();
144
    
145
    while (connections.hasMoreElements()) {
146
        conn = (Connection)connections.nextElement();
147
        if ( conn == returned ) {
148
            connectionPool.put( conn, Boolean.FALSE );
149
            break;
150
        }    
151
    }    
152
  }
153
  
154
  
85 155
  /** Utility method to convert a file handle into a URL */
86 156
  public static URL fileToURL(File file)
87 157
  {
......
126 196

  
127 197
/**
128 198
 * '$Log$
199
 * 'Revision 1.10  2000/06/26 10:35:05  jones
200
 * 'Merged in substantial changes to DBWriter and associated classes and to
201
 * 'the MetaCatServlet in order to accomodate the new UPDATE and DELETE
202
 * 'functions.  The command line tools and the parameters for the
203
 * 'servlet have changed substantially.
204
 * '
129 205
 * 'Revision 1.9.2.4  2000/06/26 00:51:06  jones
130 206
 * 'If docid passed to DBWriter.write() is not unique, classes now generate
131 207
 * 'an AccessionNumberException containing the new docid generated as a
src/edu/ucsb/nceas/metacat/MetaCatServlet.java
3 3
 *    Purpose: A Class that implements a metadata catalog as a java Servlet
4 4
 *  Copyright: 2000 Regents of the University of California and the
5 5
 *             National Center for Ecological Analysis and Synthesis
6
 *    Authors: Matt Jones, Dan Higgins
6
 *    Authors: Matt Jones, Dan Higgins, Jivka Bojilova
7 7
 *
8 8
 *   '$Author$'
9 9
 *     '$Date$'
......
79 79

  
80 80
  private ServletConfig		config = null;
81 81
  private ServletContext	context = null;
82
  private Connection 		conn = null;
83
  private DBQuery		queryobj = null;
84
  private DBReader		docreader = null;
85
  private DBTransform		dbt = null;
86
  private DBUtil        dbutil = null;
82
  private Hashtable 		connectionPool = new Hashtable();
83
  //private connection  conn = null;
84
  //private DBQuery		queryobj = null;
85
  //private DBReader    docreader = null;
86
  //private DBTransform dbt = null;
87
  //private DBUtil      dbutil = null;
87 88
  private String 		resultStyleURL = null;
88 89
  private String 		xmlcatalogfile = null;
89 90
  private String 		saxparser = null;
90
  private String    		defaultdatapath = null; 
91
  private String        defaultdatapath = null; 
91 92
					// path to directory where data files 
92 93
					// that can be downloaded will be stored
93
  private String    		executescript  = null;  
94
  private String        executescript  = null;  
94 95
					// script to get data file and put it 
95
                                    	// in defaultdocpath dir
96
                    // in defaultdocpath dir
96 97
  private PropertyResourceBundle options = null;
97 98

  
98 99
  private MetaCatUtil util = null;
......
117 118
      executescript = util.getOption("executescript");
118 119

  
119 120
      try {
121
        // Open a pool of db connections
122
        connectionPool = util.getConnectionPool();
123
      } catch (Exception e) {
124
        System.err.println("Error creating pool of database connections");
125
        System.err.println(e.getMessage());
126
      }
127
/*
128
      try {
120 129
        // Open a connection to the database
121 130
        conn = util.openDBConnection();
122 131

  
......
126 135
        dbutil = new DBUtil(conn);
127 136

  
128 137
      } catch (Exception e) {
129
        System.err.println("Error opening database connection");
138
        System.err.println("Error creating pool of database connections");
139
        System.err.println(e.getMessage());
130 140
      }
141
*/
131 142
    } catch ( ServletException ex ) {
132 143
      throw ex;
133 144
    }
......
156 167
    HttpServletResponse response) 
157 168
    throws ServletException, IOException {
158 169

  
170
    if ( util == null ) {
171
        util = new MetaCatUtil(); 
172
    }
173
    if ( connectionPool == null ) {
174
      try {
175
        // Open a pool of db connections
176
        connectionPool = util.getConnectionPool();
177
      } catch (Exception e) {
178
        System.err.println("Error creating pool of database connections");
179
        System.err.println(e.getMessage());
180
      }
181
    }    
182
/*    
159 183
    if (conn == null) {
160 184
      System.err.println("Connection to database lost.  Reopening...");
161 185
      try {
......
171 195
        System.err.println("Error opening database connection");
172 196
      }
173 197
    }
174

  
198
*/
175 199
    // Get a handle to the output stream back to the client
176 200
    PrintWriter out = response.getWriter();
177 201
    //response.setContentType("text/html");
......
346 370
      String[] doctypeArr = null;
347 371
      String doctype = null;
348 372
      Reader xmlquery = null;
373
      Connection conn = null;
349 374

  
350 375
      // Run the query if it is a structured query
351 376
      // or, if it is a free-text, simple query,
......
368 393
        System.err.println("Error handling query -- illegal action value");
369 394
      }
370 395

  
396
      try {
397
        conn = util.getConnection();
398
        DBQuery queryobj = new DBQuery(conn, saxparser);
399
        doclist = queryobj.findDocuments(xmlquery);
400
      } catch (Exception e) {
401
        response.setContentType("text/html");
402
        out.println(e.getMessage());
403
        return;
404
      } finally {
405
        if ( conn != null ) { util.returnConnection(conn); }
406
      }    
407
/*
371 408
      if (queryobj != null) {
372 409
          doclist = queryobj.findDocuments(xmlquery);
373 410
      } else {
374 411
        out.println("Query Object Init failed.");
375 412
        return;
376 413
      }
377
 
414
*/
378 415
      // Create a buffer to hold the xml result
379 416
      StringBuffer resultset = new StringBuffer();
380 417
 
......
427 464
    String docidstr = null;
428 465
    String docid = null;
429 466
    String doc = null;
467
    Connection conn = null;
468
    
430 469
    try {
431 470
      // Find the document id number
432 471
      docidstr = ((String[])params.get("docid"))[0]; 
433 472
      //docid = (new Long(docidstr)).longValue();
434 473
      docid = docidstr;
435 474

  
475
      conn = util.getConnection();
476
      DBReader docreader = new DBReader(conn);
477
      DBTransform dbt = new DBTransform(conn);
478
      
436 479
      // Get the document indicated fromthe db
437 480
      doc = docreader.readXMLDocument(docid);
438
    } catch (NullPointerException npe) {
439
      response.setContentType("text/html");
440
      out.println("Error getting document ID: " + docidstr +" (" + docid + ")");
441
    }
442 481

  
443 482
      // Return the document in XML or HTML format
444 483
      String qformat = ((String[])params.get("qformat"))[0]; 
......
456 495
        // Transform the document to the new doctype
457 496
        dbt.transformXMLDocument(doc, sourcetype, "-//W3C//HTML//EN", out);
458 497
      }
498
    } catch (NullPointerException npe) {
499
      response.setContentType("text/html");
500
      out.println("Error getting document ID: " + docidstr +" (" + docid + ")");
501
    } catch (Exception e) {
502
      response.setContentType("text/html");
503
      out.println(e.getMessage());
504
    } finally {
505
      if ( conn != null ) { util.returnConnection(conn); }
506
    }    
507

  
459 508
  }
460 509

  
461 510
  /** 
......
465 514
  private void handleInsertOrUpdateAction(PrintWriter out, Hashtable params, 
466 515
               HttpServletResponse response) {
467 516

  
517
    Connection conn = null;
518

  
468 519
    try {
469 520
      // Get the document indicated
470 521
      String[] doctext = (String[])params.get("doctext");
......
483 534
          doAction = "UPDATE";
484 535
        }
485 536

  
486
        // write the document to the database
487
        DBWriter dbw = new DBWriter(conn, saxparser);
488

  
489 537
        try {
490
          String accNumber = docid[0];
491
          if (accNumber.equals("")) {
492
            accNumber = null;
493
          }
494
          newdocid = dbw.write(xml, doAction, accNumber);  
495
        } catch (NullPointerException npe) {
496
          newdocid = dbw.write(xml, doAction, null);  
497
        }
538
            // get a connection from the pool
539
            conn = util.getConnection();
540
            // write the document to the database
541
            DBWriter dbw = new DBWriter(conn, saxparser);
498 542

  
543
            try {
544
                String accNumber = docid[0];
545
                if (accNumber.equals("")) {
546
                    accNumber = null;
547
                }
548
                newdocid = dbw.write(xml, doAction, accNumber);  
549
            } catch (NullPointerException npe) {
550
              newdocid = dbw.write(xml, doAction, null);  
551
            }
552
        } catch (Exception e) {
553
          response.setContentType("text/html");
554
          out.println(e.getMessage());
555
        } finally {
556
          if ( conn != null ) { util.returnConnection(conn); }
557
        }    
558

  
499 559
        // set content type and other response header fields first
500 560
        response.setContentType("text/xml");
501 561
        out.println("<?xml version=\"1.0\"?>");
......
534 594
               HttpServletResponse response) {
535 595

  
536 596
    String[] docid = (String[])params.get("docid");
597
    Connection conn = null;
537 598

  
538 599
    // delete the document from the database
539 600
    try {
601
      // get a connection from the pool
602
      conn = util.getConnection();
540 603
      DBWriter dbw = new DBWriter(conn, saxparser);
541 604
                                      // NOTE -- NEED TO TEST HERE
542 605
                                      // FOR EXISTENCE OF PARAM
......
562 625
      out.println("<error>");
563 626
      out.println(e.getMessage()); 
564 627
      out.println("</error>");
565
    }
628
    } finally {
629
      if ( conn != null ) { util.returnConnection(conn); }
630
    }  
566 631
  }
567 632
  
568 633
  /** 
......
573 638

  
574 639
    // Get the document indicated
575 640
    String valtext = null;
641
    
576 642
    try {
577 643
      valtext = ((String[])params.get("valtext"))[0];
578 644
    } catch (Exception nullpe) {
579 645

  
646
      Connection conn = null;
580 647
      String docid = null;
581 648
      try {
582 649
        // Find the document id number
583 650
        docid = ((String[])params.get("docid"))[0]; 
584
  
585
        // Get the document indicated fromthe db
651

  
652
        // get a connection from the pool
653
        conn = util.getConnection();
654
        DBReader docreader = new DBReader(conn);
655
        // Get the document indicated from the db
586 656
        valtext = docreader.readXMLDocument(docid);
587 657

  
588 658
      } catch (NullPointerException npe) {
589 659
        response.setContentType("text/xml");
590 660
        out.println("<error>Error getting document ID: " + docid + "</error>");
591
      }
661
        return; // Jivka added
662
      } catch (Exception e) {
663
        response.setContentType("text/html");
664
        out.println(e.getMessage()); 
665
      } finally {
666
        if ( conn != null ) { util.returnConnection(conn); }
667
      }  
592 668
    }
593 669

  
670
    Connection conn = null;
594 671
    try {
672
      // get a connection from the pool
673
      conn = util.getConnection();
595 674
      DBValidate valobj = new DBValidate(saxparser,conn);
596 675
      boolean valid = valobj.validateString(valtext);
597 676

  
......
603 682
      // set content type and other response header fields first
604 683
      response.setContentType("text/xml");
605 684
      out.println("<error>Error validating document.</error>"); 
606
    }
685
    } catch (Exception e) {
686
      response.setContentType("text/html");
687
      out.println(e.getMessage()); 
688
    } finally {
689
      if ( conn != null ) { util.returnConnection(conn); }
690
    }  
607 691
  }
608 692

  
609 693
  /** 
......
669 753
  private void handleGetDoctypesAction(PrintWriter out, Hashtable params, 
670 754
                                       HttpServletResponse response) {
671 755

  
756
    Connection conn = null;
757
    
672 758
    try {
673 759

  
760
        // get connection from the pool
761
        conn = util.getConnection();
762
        DBUtil dbutil = new DBUtil(conn);
674 763
        String doctypes = dbutil.readDoctypes();
675 764
        out.println(doctypes);
676 765

  
......
679 768
      out.println("<error>");
680 769
      out.println(e.getMessage());
681 770
      out.println("</error>");
682
    }
771
    } finally {
772
      if ( conn != null ) { util.returnConnection(conn); }
773
    }  
683 774
    
684 775
  }
685 776

  
......
691 782
  private void handleGetDataGuideAction(PrintWriter out, Hashtable params, 
692 783
                                        HttpServletResponse response) {
693 784

  
785
    Connection conn = null;
786

  
694 787
    try {
695 788

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

  
......
701 797
      out.println("<error>");
702 798
      out.println(e.getMessage());
703 799
      out.println("</error>");
704
    }
800
    } finally {
801
      if ( conn != null ) { util.returnConnection(conn); }
802
    }  
705 803
    
706 804
  }
707 805

  
......
709 807

  
710 808
/**
711 809
 * '$Log$
810
 * 'Revision 1.54  2000/07/27 23:12:21  bojilova
811
 * 'Added "getdoctypes" and "getdataguide" action handlers
812
 * '
712 813
 * 'Revision 1.53  2000/07/26 20:48:29  bojilova
713 814
 * 'Added "Login Client" action for login from the Desktop Client
714 815
 * '

Also available in: Unified diff