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: jones $'
10
 *     '$Date: 2000-11-27 13:55:08 -0800 (Mon, 27 Nov 2000) $'
11
 * '$Revision: 566 $'
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 parse the query part of a URL into parameters. This
232
   * method assumes the format of the query par tof the url is an 
233
   * ampersand separated list of name/value pairs, with equal signs separating
234
   * the name from the value (e.g., name=tom&zip=99801 ). Returns a
235
   * has of the name value pairs, hashed on name.
236
   */
237
  public static Hashtable parseQuery(String query) throws MalformedURLException
238
  {
239
    String[][] params = new String[200][2];
240
    Hashtable parameters = new Hashtable();
241

    
242
    String temp = "";
243
    boolean ampflag = true;
244
    boolean poundflag = false;
245
    int arrcount = 0;
246

    
247
    for (int i=0; i < query.length(); i++) { 
248

    
249
      // go throught the remainder of the query one character at a time.
250
      if (query.charAt(i) == '=') { 
251
        // if the current char is a # then the preceding should be a name
252
        if (!poundflag && ampflag) {
253
          params[arrcount][0] = temp.trim();
254
          temp = "";
255
        } else { 
256
          //if there are two #s or &s in a row throw an exception.
257
          throw new MalformedURLException("metacatURL: Two parameter names " +                                            "not allowed in sequence");
258
        }
259
        poundflag = true;
260
        ampflag = false;
261
      } else if (query.charAt(i) == '&' || i == query.length()-1) { 
262
        //the text preceding the & should be the param value.
263
        if (i == query.length() - 1) { 
264
          //if at the end of the string grab the last value and append it.
265
          if (query.charAt(i) != '=') { 
266
            //ignore an extra & on the end of the string
267
            temp += query.charAt(i);
268
          }
269
        }
270

    
271
        if (!ampflag && poundflag) {
272
          params[arrcount][1] = temp.trim();
273
          parameters.put(params[arrcount][0], params[arrcount][1]);
274
          temp = "";
275
          arrcount++; //increment the array to the next row.
276
        } else { 
277
          //if there are two =s or &s in a row through an exception
278
          throw new MalformedURLException("metacatURL: Two parameter values " +
279
                                          "not allowed in sequence");
280
        }
281
        poundflag = false;
282
        ampflag = true;
283
      } else { 
284
        //get the next character in the string
285
        temp += query.charAt(i);
286
      }
287
    }
288
    return parameters;
289
  }
290

    
291
  /** 
292
   * Utility method to print debugging messages
293
   *
294
   * @param flag an integer indicating the message number
295
   */
296
  public static void debugMessage(int flag) {
297
    if (debug) {
298
      System.err.println("DEBUG FLAG: " + flag);
299
    }
300
  }
301

    
302
  /** 
303
   * Utility method to print debugging messages
304
   *
305
   * @param flag an integer indicating the message number
306
   */
307
  public static void debugMessage(String msg) {
308
    if (debug) {
309
      System.err.println(msg);
310
    }
311
  }
312
}
(29-29/39)