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: 2001-05-01 16:42:22 -0700 (Tue, 01 May 2001) $'
11
 * '$Revision: 731 $'
12
 *
13
 * This program is free software; you can redistribute it and/or modify
14
 * it under the terms of the GNU General Public License as published by
15
 * the Free Software Foundation; either version 2 of the License, or
16
 * (at your option) any later version.
17
 *
18
 * This program is distributed in the hope that it will be useful,
19
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21
 * GNU General Public License for more details.
22
 *
23
 * You should have received a copy of the GNU General Public License
24
 * along with this program; if not, write to the Free Software
25
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
26
 */
27

    
28
package edu.ucsb.nceas.metacat;
29

    
30
import java.io.File;
31
import java.net.URL;
32
import java.net.MalformedURLException;
33
import java.sql.Connection;
34
import java.sql.DriverManager;
35
import java.sql.SQLException;
36
import java.util.PropertyResourceBundle;
37
import java.util.Hashtable;
38
import java.util.Enumeration;
39

    
40
/**
41
 * A suite of utility classes for the metadata catalog server
42
 */
43
public class MetaCatUtil {
44

    
45
  private PropertyResourceBundle options = null;
46
  private String propertiesFile = "edu.ucsb.nceas.metacat.metacat";
47
  private Hashtable connectionPool = new Hashtable();
48
  private static boolean debug = false;
49

    
50
  /**
51
   * Construct an instance of the utility class
52
   */
53
  public MetaCatUtil() {
54
    options = (PropertyResourceBundle)
55
          PropertyResourceBundle.getBundle(propertiesFile);
56
  }
57
  
58
  /**
59
   * This constructor allows the usage of a different properties file
60
   * @param propFile the properties file that you wish to use.
61
   */
62
  public MetaCatUtil(String propFile)
63
  {
64
    propertiesFile = propFile;
65
  }
66

    
67
  /** 
68
   * Utility method to establish a JDBC database connection using connection
69
   * info from the properties file
70
   */
71
  public Connection openDBConnection()
72
                throws SQLException, ClassNotFoundException {
73
    return openDBConnection(getOption("dbDriver"), getOption("defaultDB"),
74
                     getOption("user"), getOption("password"));
75
  }
76

    
77
  /** 
78
   * Utility method to establish a JDBC database connection 
79
   *
80
   * @param dbDriver the string representing the database driver
81
   * @param connection the string representing the database connectin parameters
82
   * @param user name of the user to use for database connection
83
   * @param password password for the user to use for database connection
84
   */
85
  public static Connection openDBConnection(String dbDriver, String connection,
86
                String user, String password)
87
                throws SQLException, ClassNotFoundException {
88

    
89
     // Load the Oracle JDBC driver
90
     Class.forName (dbDriver);
91

    
92
     debugMessage("Opening connection: " + connection);
93
     // Connect to the database
94
     Connection conn = DriverManager.getConnection( connection, user, password);
95
     return conn;
96
  }
97

    
98
  /** 
99
   * Utility method to get an option value from the properties file
100
   *
101
   * @param option_name the name of the option requested
102
   */
103
  public String getOption(String option_name) {
104
      // Get the configuration file information
105
      if (options == null) {
106
        options = (PropertyResourceBundle)
107
          PropertyResourceBundle.getBundle(propertiesFile);
108
      }
109
      String value = (String)options.handleGetObject(option_name);
110
      return value;
111
  }
112

    
113
  /* Utility method to create and return a pool of Connection objects */
114
  public Hashtable getConnectionPool()
115
                throws SQLException, ClassNotFoundException {
116

    
117
    int initConn = (new Integer(getOption("initialConnections"))).intValue();
118
    
119
    for ( int i = 0; i < initConn; i++ ) {
120
        connectionPool.put( openDBConnection(), Boolean.FALSE );
121
    }    
122
    
123
    return connectionPool;
124
  }
125
  
126
  /* Utility method to get a unused Connection object from the pool */
127
  public Connection getConnection()
128
                throws SQLException, ClassNotFoundException, Exception {
129

    
130
    Connection conn = null;
131
    Enumeration connections = connectionPool.keys();
132
    
133
    synchronized (connectionPool) {
134
      while (connections.hasMoreElements()) {
135

    
136
        conn = (Connection)connections.nextElement();
137
        Boolean b = (Boolean)connectionPool.get(conn);
138

    
139
        if (conn == null) {
140
            // closed connection; replace it
141
            conn = openDBConnection();
142
            // update the pool to show this one taken
143
            connectionPool.put(conn, Boolean.TRUE);  
144
            
145
            return conn;
146
        } else if (b == Boolean.FALSE) {
147
            // unused connection; test if it works and get it
148
            try {
149
                conn.setAutoCommit(true);
150
            } catch (SQLException e) {
151
                // problem with the connection, replace it
152
                conn = openDBConnection();
153
            }    
154
            // update the pool to show this one taken
155
            connectionPool.put(conn, Boolean.TRUE);    
156

    
157
            return conn;
158
        }    
159
      }  
160
    }   
161
    
162
    // If we get here, there no free connections;
163
    // we need to make more
164
    int incConn = (new Integer(getOption("incrementConnections"))).intValue();
165
    int maxConn = (new Integer(getOption("maximumConnections"))).intValue();
166
    int k = connectionPool.size();
167
    if ( k >= maxConn ) {
168
        throw new Exception("The maximum of " + maxConn + 
169
                            " open db connections is reached." +
170
                            " New db connection to MetaCat" +
171
                            " cannot be established.");
172
    }    
173

    
174
    // decide how many new connections to open; no more than the maximum
175
    if ( incConn > maxConn - k ) { incConn = maxConn - k; }
176
    
177
    // get them
178
    for ( int i = 0; i < incConn; i++ ) {
179
        connectionPool.put( openDBConnection(), Boolean.FALSE );
180
    }
181

    
182
    // Recurse to get one of the new connections
183
    return getConnection();
184
  }
185
  
186
  /* Utility method to give the connection back to the pool */
187
  public void returnConnection (Connection returned) {
188
    
189
    Connection conn;
190
    Enumeration connections = connectionPool.keys();
191
    
192
    if (returned != null) {
193
      while (connections.hasMoreElements()) {
194
        conn = (Connection)connections.nextElement();
195
        if ( conn == returned ) {
196
            connectionPool.put( conn, Boolean.FALSE );
197
            break;
198
        }    
199
      }    
200
    }
201
  }
202

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

    
244
  /** 
245
   * Utility method to parse the query part of a URL into parameters. This
246
   * method assumes the format of the query par tof the url is an 
247
   * ampersand separated list of name/value pairs, with equal signs separating
248
   * the name from the value (e.g., name=tom&zip=99801 ). Returns a
249
   * has of the name value pairs, hashed on name.
250
   */
251
  public static Hashtable parseQuery(String query) throws MalformedURLException
252
  {
253
    String[][] params = new String[200][2];
254
    Hashtable parameters = new Hashtable();
255

    
256
    String temp = "";
257
    boolean ampflag = true;
258
    boolean poundflag = false;
259
    int arrcount = 0;
260

    
261
    if ( query != null ) {
262
      for (int i=0; i < query.length(); i++) { 
263

    
264
        // go throught the remainder of the query one character at a time.
265
        if (query.charAt(i) == '=') { 
266
          // if the current char is a # then the preceding should be a name
267
          if (!poundflag && ampflag) {
268
            params[arrcount][0] = temp.trim();
269
            temp = "";
270
          } else { 
271
            //if there are two #s or &s in a row throw an exception.
272
            throw new MalformedURLException("metacatURL: Two parameter names "+
273
                                            "not allowed in sequence");
274
          }
275
          poundflag = true;
276
          ampflag = false;
277
        } else if (query.charAt(i) == '&' || i == query.length()-1) { 
278
          //the text preceding the & should be the param value.
279
          if (i == query.length() - 1) { 
280
            //if at the end of the string grab the last value and append it.
281
            if (query.charAt(i) != '=') { 
282
            //ignore an extra & on the end of the string
283
              temp += query.charAt(i);
284
            }
285
          }
286
  
287
          if (!ampflag && poundflag) {
288
            params[arrcount][1] = temp.trim();
289
            parameters.put(params[arrcount][0], params[arrcount][1]);
290
            temp = "";
291
            arrcount++; //increment the array to the next row.
292
          } else { 
293
            //if there are two =s or &s in a row through an exception
294
            throw new MalformedURLException("metacatURL: Two parameter values "+
295
                                            "not allowed in sequence");
296
          }
297
          poundflag = false;
298
          ampflag = true;
299
        } else { 
300
          //get the next character in the string
301
          temp += query.charAt(i);
302
        }
303
      }
304
    }
305
    return parameters;
306
  }
307

    
308
  /** 
309
   * Utility method to print debugging messages
310
   *
311
   * @param flag an integer indicating the message number
312
   */
313
  public static void debugMessage(int flag) {
314
    if (debug) {
315
      System.err.println("DEBUG FLAG: " + flag);
316
    }
317
  }
318

    
319
  /** 
320
   * Utility method to print debugging messages
321
   *
322
   * @param flag an integer indicating the message number
323
   */
324
  public static void debugMessage(String msg) {
325
    if (debug) {
326
      System.err.println(msg);
327
    }
328
  }
329
}
(33-33/43)