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: tao $'
10
 *     '$Date: 2002-06-13 11:54:51 -0700 (Thu, 13 Jun 2002) $'
11
 * '$Revision: 1217 $'
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
import java.util.Vector;
40

    
41
import edu.ucsb.nceas.dbadapter.AbstractDatabase;
42

    
43
/**
44
 * A suite of utility classes for the metadata catalog server
45
 */
46
public class MetaCatUtil {
47

    
48
  public static AbstractDatabase dbAdapter;
49
  private static PropertyResourceBundle options = null;
50
  private static String propertiesFile = "edu.ucsb.nceas.metacat.metacat";
51
  private static boolean debug = false;
52

    
53
  //private Hashtable connectionPool = new Hashtable();
54

    
55
  /** 
56
   * Determine our db adapter class and create an instance of that class
57
   */
58
  static {
59
    try {
60
      dbAdapter = (AbstractDatabase)createObject(getOption("dbAdapter"));
61
    } catch (Exception e) {
62
      System.err.println("Error in MetaCatUtil static block:" + e.getMessage());
63
    }
64
  }
65

    
66

    
67

    
68
  /**
69
   * 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
   */
73
  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
          PropertyResourceBundle.getBundle(propertiesFile);
99
      }
100
      String value = (String)options.handleGetObject(optionName);
101
      return value;
102
  }
103

    
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
   */
110
  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
  }
117

    
118
 
119
  
120
  
121
  /** 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
   * 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
    if ( query != null ) {
158
      for (int i=0; i < query.length(); i++) { 
159

    
160
        // 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
            //ignore an extra & on the end of the string
179
              temp += query.charAt(i);
180
            }
181
          }
182
  
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
        } else { 
196
          //get the next character in the string
197
          temp += query.charAt(i);
198
        }
199
      }
200
    }
201
    return parameters;
202
  }
203

    
204
   /** 
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
  /** 
235
   * Utility method to print debugging messages
236
   *
237
   * @param flag an integer indicating the message number
238
   */
239
  public static void debugMessage(int flag) {
240
    if (debug) {
241
      System.err.println("DEBUG FLAG: " + flag);
242
    }
243
  }
244

    
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
  
256
  public static void debug(String msg)
257
  {
258
    if(debug)
259
    {
260
      System.err.println(msg);
261
    }
262
  }
263
  
264
  
265
  
266
  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
  
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
  /** 
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
   * @param the sperator char
384
   */
385
  public static int getVersionFromString(String str)
386
                                throws NumberFormatException
387
  {
388
    int version=-1;
389
    String versionString=null;
390
    int dotNumber = 0;//count how many dots in given string
391
    int indexOfLastDot = 0;
392
    
393
    //assume that seperator is one charactor string
394
    char seperator=getOption("accNumSeparator").charAt(0);
395
    
396
    for (int i=0; i<str.length(); i++)
397
    {
398
      if ( str.charAt(i)==seperator)
399
      {
400
        dotNumber++;//count how many dots
401
        indexOfLastDot=i;//keep the last dot postion
402
      }
403
    }//for
404
    
405
    //The string formatt is wrong, because it has more than two or less than
406
    //one seperator
407
    if ( dotNumber>2 || dotNumber < 1)
408
    {
409
      version=-2;
410
    }
411
    else if (dotNumber == 2) //the case for str1.str2.str3
412
    {
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
   /**
425
   * Method to get the name of local replication server
426
   */
427
   public static String getLocalReplicationServerName()
428
   {
429
     String replicationServerName=null;
430
     String serverHost=null;
431
     serverHost=getOption("server");
432
     // append "context/servelet/replication" to the host name
433
     replicationServerName=serverHost+getOption("replicationpath");
434
     return replicationServerName;
435
       
436
   }
437
  
438
}
(33-33/43)