Project

General

Profile

1
/**
2
 *  '$RCSfile$'
3
 *    Purpose: A Class that implements utility methods for a metadata catalog
4
 *  Copyright: 2000 Regents of the University of California and the
5
 *             National Center for Ecological Analysis and Synthesis
6
 *    Authors: Matt Jones, Jivka Bojilova
7
 *    Release: @release@
8
 * 
9
 *   '$Author: bojilova $'
10
 *     '$Date: 2000-09-26 13:03:30 -0700 (Tue, 26 Sep 2000) $'
11
 * '$Revision: 464 $'
12
 */
13

    
14
package edu.ucsb.nceas.metacat;
15

    
16
import java.io.File;
17
import java.net.URL;
18
import java.net.MalformedURLException;
19
import java.sql.Connection;
20
import java.sql.DriverManager;
21
import java.sql.SQLException;
22
import java.util.PropertyResourceBundle;
23
import java.util.Hashtable;
24
import java.util.Enumeration;
25

    
26
/**
27
 * A suite of utility classes for the metadata catalog server
28
 */
29
public class MetaCatUtil {
30

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

    
36
  /**
37
   * Construct an instance of the utility class
38
   */
39
  public MetaCatUtil() {
40
    options = (PropertyResourceBundle)
41
          PropertyResourceBundle.getBundle(propertiesFile);
42
  }
43
  
44
  /**
45
   * This constructor allows the usage of a different properties file
46
   * @param propFile the properties file that you wish to use.
47
   */
48
  public MetaCatUtil(String propFile)
49
  {
50
    propertiesFile = propFile;
51
  }
52

    
53
  /** 
54
   * Utility method to establish a JDBC database connection using connection
55
   * info from the properties file
56
   */
57
  public Connection openDBConnection()
58
                throws SQLException, ClassNotFoundException {
59
    return openDBConnection(getOption("dbDriver"), getOption("defaultDB"),
60
                     getOption("user"), getOption("password"));
61
  }
62

    
63
  /** 
64
   * Utility method to establish a JDBC database connection 
65
   *
66
   * @param dbDriver the string representing the database driver
67
   * @param connection the string representing the database connectin parameters
68
   * @param user name of the user to use for database connection
69
   * @param password password for the user to use for database connection
70
   */
71
  public static Connection openDBConnection(String dbDriver, String connection,
72
                String user, String password)
73
                throws SQLException, ClassNotFoundException {
74

    
75
     // Load the Oracle JDBC driver
76
     Class.forName (dbDriver);
77

    
78
     debugMessage("Opening connection: " + connection);
79
     // Connect to the database
80
     Connection conn = DriverManager.getConnection( connection, user, password);
81
     return conn;
82
  }
83

    
84
  /** 
85
   * Utility method to get an option value from the properties file
86
   *
87
   * @param option_name the name of the option requested
88
   */
89
  public String getOption(String option_name) {
90
      // Get the configuration file information
91
      if (options == null) {
92
        options = (PropertyResourceBundle)
93
          PropertyResourceBundle.getBundle(propertiesFile);
94
      }
95
      String value = (String)options.handleGetObject(option_name);
96
      return value;
97
  }
98

    
99
  /* Utility method to create and return a pool of Connection objects */
100
  public Hashtable getConnectionPool()
101
                throws SQLException, ClassNotFoundException {
102

    
103
    int initConn = (new Integer(getOption("initialConnections"))).intValue();
104
    
105
    for ( int i = 0; i < initConn; i++ ) {
106
        connectionPool.put( openDBConnection(), Boolean.FALSE );
107
    }    
108
    
109
    return connectionPool;
110
  }
111
  
112
  /* Utility method to get a unused Connection object from the pool */
113
  public Connection getConnection()
114
                throws SQLException, ClassNotFoundException, Exception {
115

    
116
    Connection conn = null;
117
    Enumeration connections = connectionPool.keys();
118
    
119
    synchronized (connectionPool) {
120
      while (connections.hasMoreElements()) {
121

    
122
        conn = (Connection)connections.nextElement();
123
        Boolean b = (Boolean)connectionPool.get(conn);
124

    
125
        if (conn == null) {
126
            // closed connection; replace it
127
            conn = openDBConnection();
128
            // update the pool to show this one taken
129
            connectionPool.put(conn, Boolean.TRUE);  
130
            
131
            return conn;
132
        } else if (b == Boolean.FALSE) {
133
            // unused connection; test if it works and get it
134
            try {
135
                conn.setAutoCommit(true);
136
            } catch (SQLException e) {
137
                // problem with the connection, replace it
138
                conn = openDBConnection();
139
            }    
140
            // update the pool to show this one taken
141
            connectionPool.put(conn, Boolean.TRUE);    
142

    
143
            return conn;
144
        }    
145
      }  
146
    }   
147
    
148
    // If we get here, there no free connections;
149
    // we need to make more
150
    int incConn = (new Integer(getOption("incrementConnections"))).intValue();
151
    int maxConn = (new Integer(getOption("maximumConnections"))).intValue();
152
    int k = connectionPool.size();
153
    if ( k >= maxConn ) {
154
        throw new Exception("The maximum of " + maxConn + 
155
                            " open db connections is reached." +
156
                            " New db connection to MetaCat" +
157
                            " cannot be established.");
158
    }    
159

    
160
    // decide how many new connections to open; no more than the maximum
161
    if ( incConn > maxConn - k ) { incConn = maxConn - k; }
162
    
163
    // get them
164
    for ( int i = 0; i < incConn; i++ ) {
165
        connectionPool.put( openDBConnection(), Boolean.FALSE );
166
    }
167

    
168
    // Recurse to get one of the new connections
169
    return getConnection();
170
  }
171
  
172
  /* Utility method to give the connection back to the pool */
173
  public void returnConnection (Connection returned) {
174
    
175
    Connection conn;
176
    Enumeration connections = connectionPool.keys();
177
    
178
    if (returned != null) {
179
      while (connections.hasMoreElements()) {
180
        conn = (Connection)connections.nextElement();
181
        if ( conn == returned ) {
182
            connectionPool.put( conn, Boolean.FALSE );
183
            break;
184
        }    
185
      }    
186
    }
187
  }
188

    
189
  /* Return the size of the pool */
190
  public int getPoolSize() {
191
    return connectionPool.size();
192
  }
193
  
194
  /* Utility method to close all the connection from the pool */
195
  public void closeConnections() {
196
    
197
    Connection conn;
198
    Enumeration connections = connectionPool.keys();
199
    
200
    while (connections.hasMoreElements()) {
201
        conn = (Connection)connections.nextElement();
202
        if ( conn != null ) {
203
            try {
204
                conn.close();
205
            } catch (SQLException e) {}    
206
        }    
207
    }
208
  }
209
  
210
  
211
  /** Utility method to convert a file handle into a URL */
212
  public static URL fileToURL(File file)
213
  {
214
     String path = file.getAbsolutePath();
215
     String fSep = System.getProperty("file.separator");
216
     if (fSep != null && fSep.length() == 1)
217
       path = path.replace(fSep.charAt(0), '/');
218
     if (path.length() > 0 && path.charAt(0) != '/')
219
       path = '/' + path;
220
     try {
221
       return new URL("file", null, path);
222
     }
223
     catch (java.net.MalformedURLException e) {
224
       /* According to the spec this could only happen if the file
225
          protocol were not recognized. */
226
       throw new Error("unexpected MalformedURLException");
227
     }
228
  }
229

    
230
  /** 
231
   * Utility method to print debugging messages
232
   *
233
   * @param flag an integer indicating the message number
234
   */
235
  public static void debugMessage(int flag) {
236
    if (debug) {
237
      System.err.println("DEBUG FLAG: " + flag);
238
    }
239
  }
240

    
241
  /** 
242
   * Utility method to print debugging messages
243
   *
244
   * @param flag an integer indicating the message number
245
   */
246
  public static void debugMessage(String msg) {
247
    if (debug) {
248
      System.err.println(msg);
249
    }
250
  }
251
}
252

    
253
/**
254
 * '$Log$
255
 * 'Revision 1.15  2000/08/14 22:31:13  berkley
256
 * 'added new constructor to allow the creation of a metacatutil object that uses a properties file other than edu.ucsb.nceas.metacat.metacat.
257
 * '
258
 * 'Revision 1.14  2000/08/14 20:53:34  jones
259
 * 'Added "release" keyword to all metacat source files so that the release
260
 * 'number will be evident in software distributions.
261
 * '
262
 * 'Revision 1.13  2000/08/09 00:39:47  jones
263
 * '-Reorganized xmltodb module to support new install process for the new
264
 * 'linux server (dev.nceas.ucsb.edu).  Added "build.sh" shell script that
265
 * 'calls ant withthe proper umask set for installation.  Use:
266
 * '
267
 * '  ./build.sh install
268
 * '
269
 * 'to post a new copy of the servlet and its supporting files to the install
270
 * 'directory defined in build.xml.
271
 * '
272
 * '-Updated the servlet to use a new servlet prefix that we'll use with the
273
 * 'Tomcat servlet engine.
274
 * '
275
 * '-Update bin dir shell scripts to reflect new locations of relevant jar files.
276
 * '
277
 * 'Revision 1.12  2000/08/04 23:34:10  bojilova
278
 * 'more precise handling of the Connection Pool
279
 * '
280
 * 'Revision 1.11  2000/08/01 18:26:50  bojilova
281
 * 'added Pool of Connections
282
 * 'DBQuery, DBReader, DBTransform, DBUtil are created on every request and use the connections from the Pool
283
 * 'same with DBWriter and DBValidate
284
 * '
285
 * 'Revision 1.10  2000/06/26 10:35:05  jones
286
 * 'Merged in substantial changes to DBWriter and associated classes and to
287
 * 'the MetaCatServlet in order to accomodate the new UPDATE and DELETE
288
 * 'functions.  The command line tools and the parameters for the
289
 * 'servlet have changed substantially.
290
 * '
291
 * 'Revision 1.9.2.4  2000/06/26 00:51:06  jones
292
 * 'If docid passed to DBWriter.write() is not unique, classes now generate
293
 * 'an AccessionNumberException containing the new docid generated as a
294
 * 'replacement.  The docid is then extracted from the exception and
295
 * 'returned to the calling application for user feedback or client processing.
296
 * '
297
 * 'Revision 1.9.2.3  2000/06/25 23:38:17  jones
298
 * 'Added RCSfile keyword
299
 * '
300
 * 'Revision 1.9.2.2  2000/06/25 23:34:18  jones
301
 * 'Changed documentation formatting, added log entries at bottom of source files
302
 * ''
303
 */
(21-21/28)