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-08 14:40:46 -0700 (Tue, 08 May 2001) $'
11
 * '$Revision: 739 $'
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 || conn.isClosed()) {
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
    try {
193
      if ( (returned != null) && !(returned.isClosed()) ) {
194
        while (connections.hasMoreElements()) {
195
          conn = (Connection)connections.nextElement();
196
          if ( conn == returned ) {
197
            connectionPool.put( conn, Boolean.FALSE );
198
            break;
199
          }    
200
        }    
201
      }
202
    } catch (SQLException e) {}    
203
  }
204

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

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

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

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

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

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

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