Project

General

Profile

1 51 jones
/**
2 203 jones
 *  '$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 309 bojilova
 *    Authors: Matt Jones, Jivka Bojilova
7 349 jones
 *    Release: @release@
8 51 jones
 *
9 203 jones
 *   '$Author$'
10
 *     '$Date$'
11
 * '$Revision$'
12 669 jones
 *
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 51 jones
 */
27
28
package edu.ucsb.nceas.metacat;
29
30 185 jones
import java.io.File;
31
import java.net.URL;
32
import java.net.MalformedURLException;
33 50 jones
import java.sql.Connection;
34
import java.sql.DriverManager;
35
import java.sql.SQLException;
36 184 jones
import java.util.PropertyResourceBundle;
37 309 bojilova
import java.util.Hashtable;
38
import java.util.Enumeration;
39 887 berkley
import java.util.Vector;
40 50 jones
41 777 bojilova
import edu.ucsb.nceas.dbadapter.AbstractDatabase;
42 747 bojilova
43 50 jones
/**
44
 * A suite of utility classes for the metadata catalog server
45
 */
46
public class MetaCatUtil {
47
48 777 bojilova
  public static AbstractDatabase dbAdapter;
49 747 bojilova
  private static PropertyResourceBundle options = null;
50
  private static String propertiesFile = "edu.ucsb.nceas.metacat.metacat";
51 1002 berkley
  private static boolean debug = false;
52 109 bojilova
53 1217 tao
  //private Hashtable connectionPool = new Hashtable();
54 747 bojilova
55
  /**
56
   * Determine our db adapter class and create an instance of that class
57
   */
58
  static {
59
    try {
60 777 bojilova
      dbAdapter = (AbstractDatabase)createObject(getOption("dbAdapter"));
61 747 bojilova
    } catch (Exception e) {
62
      System.err.println("Error in MetaCatUtil static block:" + e.getMessage());
63
    }
64
  }
65
66
67 1217 tao
68 184 jones
  /**
69 747 bojilova
   * Instantiate a class using the name of the class at runtime
70
   *
71
   * @param className the fully qualified name of the class to instantiate
72 184 jones
   */
73 747 bojilova
  public static Object createObject(String className) throws Exception {
74
75
    Object object = null;
76
    try {
77
      Class classDefinition = Class.forName(className);
78
      object = classDefinition.newInstance();
79
    } catch (InstantiationException e) {
80
      throw e;
81
    } catch (IllegalAccessException e) {
82
      throw e;
83
    } catch (ClassNotFoundException e) {
84
      throw e;
85
    }
86
    return object;
87
  }
88
89
  /**
90
   * Utility method to get an option value from the properties file
91
   *
92
   * @param optionName the name of the option requested
93
   */
94
  public static String getOption(String optionName) {
95
      // Get the configuration file information
96
      if (options == null) {
97
        options = (PropertyResourceBundle)
98 184 jones
          PropertyResourceBundle.getBundle(propertiesFile);
99 747 bojilova
      }
100
      String value = (String)options.handleGetObject(optionName);
101
      return value;
102 184 jones
  }
103 747 bojilova
104
  /**
105
   * Utility method to get an option value from a properties file
106
   *
107
   * @param optionName the name of the option requested
108
   * @param propFile the name of the file where to get the properties from
109 354 berkley
   */
110 747 bojilova
  public String getOption(String optionName, String propFile) {
111
    // Get the configuration file information
112
    PropertyResourceBundle options = (PropertyResourceBundle)
113
                                     PropertyResourceBundle.getBundle(propFile);
114
    String value = (String)options.handleGetObject(optionName);
115
    return value;
116 354 berkley
  }
117 184 jones
118 1217 tao
119 309 bojilova
120
121 185 jones
  /** Utility method to convert a file handle into a URL */
122
  public static URL fileToURL(File file)
123
  {
124
     String path = file.getAbsolutePath();
125
     String fSep = System.getProperty("file.separator");
126
     if (fSep != null && fSep.length() == 1)
127
       path = path.replace(fSep.charAt(0), '/');
128
     if (path.length() > 0 && path.charAt(0) != '/')
129
       path = '/' + path;
130
     try {
131
       return new URL("file", null, path);
132
     }
133
     catch (java.net.MalformedURLException e) {
134
       /* According to the spec this could only happen if the file
135
          protocol were not recognized. */
136
       throw new Error("unexpected MalformedURLException");
137
     }
138
  }
139
140
  /**
141 566 jones
   * Utility method to parse the query part of a URL into parameters. This
142
   * method assumes the format of the query par tof the url is an
143
   * ampersand separated list of name/value pairs, with equal signs separating
144
   * the name from the value (e.g., name=tom&zip=99801 ). Returns a
145
   * has of the name value pairs, hashed on name.
146
   */
147
  public static Hashtable parseQuery(String query) throws MalformedURLException
148
  {
149
    String[][] params = new String[200][2];
150
    Hashtable parameters = new Hashtable();
151
152
    String temp = "";
153
    boolean ampflag = true;
154
    boolean poundflag = false;
155
    int arrcount = 0;
156
157 731 bojilova
    if ( query != null ) {
158
      for (int i=0; i < query.length(); i++) {
159 566 jones
160 731 bojilova
        // go throught the remainder of the query one character at a time.
161
        if (query.charAt(i) == '=') {
162
          // if the current char is a # then the preceding should be a name
163
          if (!poundflag && ampflag) {
164
            params[arrcount][0] = temp.trim();
165
            temp = "";
166
          } else {
167
            //if there are two #s or &s in a row throw an exception.
168
            throw new MalformedURLException("metacatURL: Two parameter names "+
169
                                            "not allowed in sequence");
170
          }
171
          poundflag = true;
172
          ampflag = false;
173
        } else if (query.charAt(i) == '&' || i == query.length()-1) {
174
          //the text preceding the & should be the param value.
175
          if (i == query.length() - 1) {
176
            //if at the end of the string grab the last value and append it.
177
            if (query.charAt(i) != '=') {
178 566 jones
            //ignore an extra & on the end of the string
179 731 bojilova
              temp += query.charAt(i);
180
            }
181 566 jones
          }
182 731 bojilova
183
          if (!ampflag && poundflag) {
184
            params[arrcount][1] = temp.trim();
185
            parameters.put(params[arrcount][0], params[arrcount][1]);
186
            temp = "";
187
            arrcount++; //increment the array to the next row.
188
          } else {
189
            //if there are two =s or &s in a row through an exception
190
            throw new MalformedURLException("metacatURL: Two parameter values "+
191
                                            "not allowed in sequence");
192
          }
193
          poundflag = false;
194
          ampflag = true;
195 566 jones
        } else {
196 731 bojilova
          //get the next character in the string
197
          temp += query.charAt(i);
198 566 jones
        }
199
      }
200
    }
201
    return parameters;
202
  }
203
204 1053 tao
   /**
205
   * Utility method to print debugging messages. User can set debug level
206
   * for this message. The number is fewer, the message is more important
207
   * @param msg, the content of the message
208
   * @param debugLevel, an integer indicating the message debug leve
209
   */
210
  public static void debugMessage(String msg, int debugLevel)
211
  {
212
    int limit = 1;
213
    try
214
    {
215
      limit=Integer.parseInt(getOption("debuglevel"));
216
217
    }
218
    catch (Exception e)
219
    {
220
      System.out.println(e.getMessage());
221
    }
222
    //don't allow the user set debugLevel less than or equals 0
223
    if (debugLevel<=0)
224
    {
225
      debugLevel=1;
226
    }
227
228
    if (debugLevel < limit)
229
    {
230
      System.err.println(msg);
231
    }
232
  }
233
234 566 jones
  /**
235 185 jones
   * Utility method to print debugging messages
236
   *
237
   * @param flag an integer indicating the message number
238
   */
239 203 jones
  public static void debugMessage(int flag) {
240
    if (debug) {
241
      System.err.println("DEBUG FLAG: " + flag);
242
    }
243 185 jones
  }
244 203 jones
245
  /**
246
   * Utility method to print debugging messages
247
   *
248
   * @param flag an integer indicating the message number
249
   */
250
  public static void debugMessage(String msg) {
251
    if (debug) {
252
      System.err.println(msg);
253
    }
254
  }
255 887 berkley
256 1000 berkley
  public static void debug(String msg)
257
  {
258
    if(debug)
259
    {
260
      System.err.println(msg);
261
    }
262
  }
263
264 1053 tao
265
266 887 berkley
  public static Vector getOptionList(String optiontext)
267
  {
268
    Vector options = new Vector();
269
    if(optiontext.indexOf(",") == -1)
270
    {
271
      options.addElement(optiontext);
272
      return options;
273
    }
274
275
    while(optiontext.indexOf(",") != -1)
276
    {
277
      String s = optiontext.substring(0, optiontext.indexOf(","));
278
      options.addElement(s.trim());
279
      optiontext = optiontext.substring(optiontext.indexOf(",") + 1,
280
                                        optiontext.length());
281
      if(optiontext.indexOf(",") == -1)
282
      { //catch the last list entry
283
        options.addElement(optiontext.trim());
284
      }
285
    }
286
    return options;
287
  }
288 894 berkley
289
  /** Normalizes the given string. Taken from configXML.java*/
290
  public static String normalize(String s)
291
  {
292
    StringBuffer str = new StringBuffer();
293
294
    int len = (s != null) ? s.length() : 0;
295
    for (int i = 0; i < len; i++)
296
    {
297
      char ch = s.charAt(i);
298
      switch (ch)
299
      {
300
      case '<':
301
      {
302
        str.append("&lt;");
303
        break;
304
      }
305
        case '>':
306
      {
307
        str.append("&gt;");
308
        break;
309
      }
310
      case '&':
311
      {
312
        str.append("&amp;");
313
        break;
314
      }
315
      case '"':
316
      {
317
        str.append("&quot;");
318
        break;
319
      }
320
      case '\r':
321
      case '\n':
322
      {
323
        // else, default append char
324
      }
325
      default:
326
      {
327
        str.append(ch);
328
      }
329
      }
330
    }
331
    return (str.toString());
332
  }
333
334 942 tao
  /**
335
   * Utility method to get docid from a given string
336
   * @param string, the given string should be these two format:
337
   *              1) str1.str2  in this case docid= str1.str2
338
   *              2) str1.str2.str3, in this case docid =str1.str2
339
   * @param the sperator char
340
   */
341
  public static String getDocIdFromString(String str)
342
  {
343
    String docId = null;
344
    int dotNumber = 0;//count how many dots in given string
345
    int indexOfLastDot = 0;
346
347
    //assume that seperator is one charactor string
348
    char seperator=getOption("accNumSeparator").charAt(0);
349
350
    for (int i=0; i<str.length(); i++)
351
    {
352
      if ( str.charAt(i)==seperator)
353
      {
354
        dotNumber++;//count how many dots
355
        indexOfLastDot=i;//keep the last dot postion
356
      }
357
    }//for
358
359
    //The string formatt is wrong, because it has more than two or less than
360
    //one seperator
361
    if ( dotNumber>2 || dotNumber < 1)
362
    {
363
      docId=null;
364
    }
365
    else if (dotNumber == 2) //the case for str1.str2.str3
366
    {
367
       docId=str.substring(0, indexOfLastDot);
368
    }
369
    else if (dotNumber == 1) //the case for str1.str2
370
    {
371
      docId=str;
372
    }
373
374
    return docId;
375
  }//getDocIdFromString
376
377
  /**
378
   * Utility method to get version number from a given string
379
   * @param string, the given string should be these two format:
380
   *              1) str1.str2(no version)  version =-1;
381
   *              2) str1.str2.str3, in this case version = str3;
382
   *              3) other, vresion =-2
383
   */
384
  public static int getVersionFromString(String str)
385
                                throws NumberFormatException
386
  {
387
    int version=-1;
388
    String versionString=null;
389
    int dotNumber = 0;//count how many dots in given string
390
    int indexOfLastDot = 0;
391
392
    //assume that seperator is one charactor string
393
    char seperator=getOption("accNumSeparator").charAt(0);
394
395
    for (int i=0; i<str.length(); i++)
396
    {
397
      if ( str.charAt(i)==seperator)
398
      {
399
        dotNumber++;//count how many dots
400
        indexOfLastDot=i;//keep the last dot postion
401
      }
402
    }//for
403
404
    //The string formatt is wrong, because it has more than two or less than
405
    //one seperator
406
    if ( dotNumber>2 || dotNumber < 1)
407
    {
408
      version=-2;
409
    }
410 1292 tao
    else if (dotNumber == 2 && (indexOfLastDot != (str.length() -1)))
411
     //the case for str1.str2.str3
412 942 tao
    {
413
       versionString=str.substring((indexOfLastDot+1), str.length());
414
       version=Integer.parseInt(versionString);
415
    }
416
    else if (dotNumber == 1) //the case for str1.str2
417
    {
418
      version=-1;
419
    }
420
421
    return version;
422
  }//getVersionFromString
423
424 1292 tao
425
  /**
426
   * Utility method to get version string from a given string
427
   * @param string, the given string should be these two format:
428
   *              1) str1.str2(no version)  version=null;
429
   *              2) str1.str2.str3, in this case version = str3;
430
   *              3) other, vresion =null;
431
   */
432
  public static String getRevisionStringFromString(String str)
433
                                throws NumberFormatException
434
  {
435
    // String to store the version
436
    String versionString=null;
437
    int dotNumber = 0;//count how many dots in given string
438
    int indexOfLastDot = 0;
439
440
    //assume that seperator is one charactor string
441
    char seperator=getOption("accNumSeparator").charAt(0);
442
443
    for (int i=0; i<str.length(); i++)
444
    {
445
      if ( str.charAt(i)==seperator)
446
      {
447
        dotNumber++;//count how many dots
448
        indexOfLastDot=i;//keep the last dot postion
449
      }
450
    }//for
451
452
    //The string formatt is wrong, because it has more than two or less than
453
    //one seperator
454
    if ( dotNumber>2 || dotNumber < 1)
455
    {
456
      versionString = null;
457
    }
458
    else if (dotNumber == 2 && (indexOfLastDot != (str.length() -1)))
459
    {
460
      //the case for str1.str2.str3
461
      // indexOfLastDot != (str.length() -1) means get rid of str1.str2.
462
      versionString=str.substring((indexOfLastDot+1), str.length());
463
    }
464
    else if (dotNumber == 1) //the case for str1.str2 or str1.str2.
465
    {
466
      versionString=null;
467
    }
468
469
    return versionString;
470
  }//getVersionFromString
471
472
  /**
473 1013 tao
   * Method to get the name of local replication server
474
   */
475 1060 tao
   public static String getLocalReplicationServerName()
476 1013 tao
   {
477
     String replicationServerName=null;
478
     String serverHost=null;
479
     serverHost=getOption("server");
480
     // append "context/servelet/replication" to the host name
481
     replicationServerName=serverHost+getOption("replicationpath");
482
     return replicationServerName;
483
484
   }
485
486 50 jones
}