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 1538 berkley
 *
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 1545 tao
import java.util.Stack;
40 887 berkley
import java.util.Vector;
41 50 jones
42 777 bojilova
import edu.ucsb.nceas.dbadapter.AbstractDatabase;
43 747 bojilova
44 50 jones
/**
45
 * A suite of utility classes for the metadata catalog server
46
 */
47
public class MetaCatUtil {
48
49 777 bojilova
  public static AbstractDatabase dbAdapter;
50 747 bojilova
  private static PropertyResourceBundle options = null;
51
  private static String propertiesFile = "edu.ucsb.nceas.metacat.metacat";
52 1394 tao
  private static boolean debug = true;
53 109 bojilova
54 1217 tao
  //private Hashtable connectionPool = new Hashtable();
55 747 bojilova
56 1538 berkley
  /**
57 747 bojilova
   * Determine our db adapter class and create an instance of that class
58
   */
59
  static {
60
    try {
61 777 bojilova
      dbAdapter = (AbstractDatabase)createObject(getOption("dbAdapter"));
62 747 bojilova
    } catch (Exception e) {
63
      System.err.println("Error in MetaCatUtil static block:" + e.getMessage());
64
    }
65
  }
66
67
68 1217 tao
69 184 jones
  /**
70 747 bojilova
   * Instantiate a class using the name of the class at runtime
71
   *
72
   * @param className the fully qualified name of the class to instantiate
73 184 jones
   */
74 747 bojilova
  public static Object createObject(String className) throws Exception {
75 1538 berkley
76 747 bojilova
    Object object = null;
77
    try {
78
      Class classDefinition = Class.forName(className);
79
      object = classDefinition.newInstance();
80
    } catch (InstantiationException e) {
81
      throw e;
82
    } catch (IllegalAccessException e) {
83
      throw e;
84
    } catch (ClassNotFoundException e) {
85
      throw e;
86
    }
87
    return object;
88
  }
89
90 1538 berkley
  /**
91 747 bojilova
   * Utility method to get an option value from the properties file
92
   *
93
   * @param optionName the name of the option requested
94
   */
95
  public static String getOption(String optionName) {
96
      // Get the configuration file information
97
      if (options == null) {
98
        options = (PropertyResourceBundle)
99 184 jones
          PropertyResourceBundle.getBundle(propertiesFile);
100 747 bojilova
      }
101
      String value = (String)options.handleGetObject(optionName);
102
      return value;
103 184 jones
  }
104 747 bojilova
105 1538 berkley
  /**
106 747 bojilova
   * Utility method to get an option value from a properties file
107
   *
108
   * @param optionName the name of the option requested
109
   * @param propFile the name of the file where to get the properties from
110 354 berkley
   */
111 747 bojilova
  public String getOption(String optionName, String propFile) {
112
    // Get the configuration file information
113
    PropertyResourceBundle options = (PropertyResourceBundle)
114
                                     PropertyResourceBundle.getBundle(propFile);
115
    String value = (String)options.handleGetObject(optionName);
116
    return value;
117 354 berkley
  }
118 184 jones
119 1538 berkley
120
121
122 185 jones
  /** Utility method to convert a file handle into a URL */
123
  public static URL fileToURL(File file)
124
  {
125
     String path = file.getAbsolutePath();
126
     String fSep = System.getProperty("file.separator");
127
     if (fSep != null && fSep.length() == 1)
128
       path = path.replace(fSep.charAt(0), '/');
129
     if (path.length() > 0 && path.charAt(0) != '/')
130
       path = '/' + path;
131
     try {
132
       return new URL("file", null, path);
133
     }
134
     catch (java.net.MalformedURLException e) {
135
       /* According to the spec this could only happen if the file
136
          protocol were not recognized. */
137
       throw new Error("unexpected MalformedURLException");
138
     }
139
  }
140
141 1538 berkley
  /**
142 566 jones
   * Utility method to parse the query part of a URL into parameters. This
143 1538 berkley
   * method assumes the format of the query par tof the url is an
144 566 jones
   * ampersand separated list of name/value pairs, with equal signs separating
145
   * the name from the value (e.g., name=tom&zip=99801 ). Returns a
146
   * has of the name value pairs, hashed on name.
147
   */
148
  public static Hashtable parseQuery(String query) throws MalformedURLException
149
  {
150
    String[][] params = new String[200][2];
151
    Hashtable parameters = new Hashtable();
152
153
    String temp = "";
154
    boolean ampflag = true;
155
    boolean poundflag = false;
156
    int arrcount = 0;
157
158 731 bojilova
    if ( query != null ) {
159 1538 berkley
      for (int i=0; i < query.length(); i++) {
160 566 jones
161 731 bojilova
        // go throught the remainder of the query one character at a time.
162 1538 berkley
        if (query.charAt(i) == '=') {
163 731 bojilova
          // if the current char is a # then the preceding should be a name
164
          if (!poundflag && ampflag) {
165
            params[arrcount][0] = temp.trim();
166
            temp = "";
167 1538 berkley
          } else {
168 731 bojilova
            //if there are two #s or &s in a row throw an exception.
169
            throw new MalformedURLException("metacatURL: Two parameter names "+
170
                                            "not allowed in sequence");
171
          }
172
          poundflag = true;
173
          ampflag = false;
174 1538 berkley
        } else if (query.charAt(i) == '&' || i == query.length()-1) {
175 731 bojilova
          //the text preceding the & should be the param value.
176 1538 berkley
          if (i == query.length() - 1) {
177 731 bojilova
            //if at the end of the string grab the last value and append it.
178 1538 berkley
            if (query.charAt(i) != '=') {
179 566 jones
            //ignore an extra & on the end of the string
180 731 bojilova
              temp += query.charAt(i);
181
            }
182 566 jones
          }
183 1538 berkley
184 731 bojilova
          if (!ampflag && poundflag) {
185
            params[arrcount][1] = temp.trim();
186
            parameters.put(params[arrcount][0], params[arrcount][1]);
187
            temp = "";
188
            arrcount++; //increment the array to the next row.
189 1538 berkley
          } else {
190 731 bojilova
            //if there are two =s or &s in a row through an exception
191
            throw new MalformedURLException("metacatURL: Two parameter values "+
192
                                            "not allowed in sequence");
193
          }
194
          poundflag = false;
195
          ampflag = true;
196 1538 berkley
        } else {
197 731 bojilova
          //get the next character in the string
198
          temp += query.charAt(i);
199 566 jones
        }
200
      }
201
    }
202
    return parameters;
203
  }
204
205 1538 berkley
   /**
206 1053 tao
   * Utility method to print debugging messages. User can set debug level
207
   * for this message. The number is fewer, the message is more important
208
   * @param msg, the content of the message
209
   * @param debugLevel, an integer indicating the message debug leve
210
   */
211 1538 berkley
  public static void debugMessage(String msg, int debugLevel)
212 1053 tao
  {
213 1394 tao
    if (debug)
214 1053 tao
    {
215 1394 tao
      int limit = 1;
216 1538 berkley
      try
217 1394 tao
      {
218
        limit=Integer.parseInt(getOption("debuglevel"));
219 1538 berkley
220 1394 tao
      }
221
      catch (Exception e)
222
      {
223
        System.out.println(e.getMessage());
224
      }
225
      //don't allow the user set debugLevel less than or equals 0
226
      if (debugLevel<=0)
227
      {
228
        debugLevel=1;
229
      }
230 1538 berkley
231
      if (debugLevel < limit)
232 1394 tao
      {
233 1538 berkley
        System.err.println("@debugprefix@ " +msg);
234 1394 tao
      }
235 1053 tao
    }
236
  }
237 1538 berkley
238
239 887 berkley
  public static Vector getOptionList(String optiontext)
240
  {
241
    Vector options = new Vector();
242
    if(optiontext.indexOf(",") == -1)
243
    {
244
      options.addElement(optiontext);
245
      return options;
246
    }
247 1538 berkley
248 887 berkley
    while(optiontext.indexOf(",") != -1)
249
    {
250
      String s = optiontext.substring(0, optiontext.indexOf(","));
251
      options.addElement(s.trim());
252 1538 berkley
      optiontext = optiontext.substring(optiontext.indexOf(",") + 1,
253 887 berkley
                                        optiontext.length());
254
      if(optiontext.indexOf(",") == -1)
255
      { //catch the last list entry
256
        options.addElement(optiontext.trim());
257
      }
258
    }
259
    return options;
260
  }
261 1538 berkley
262 894 berkley
  /** Normalizes the given string. Taken from configXML.java*/
263
  public static String normalize(String s)
264
  {
265
    StringBuffer str = new StringBuffer();
266
267
    int len = (s != null) ? s.length() : 0;
268
    for (int i = 0; i < len; i++)
269
    {
270
      char ch = s.charAt(i);
271
      switch (ch)
272
      {
273
      case '<':
274
      {
275
        str.append("&lt;");
276
        break;
277
      }
278
        case '>':
279
      {
280
        str.append("&gt;");
281
        break;
282
      }
283
      case '&':
284
      {
285
        str.append("&amp;");
286
        break;
287
      }
288
      case '"':
289
      {
290
        str.append("&quot;");
291
        break;
292
      }
293
      case '\r':
294
      case '\n':
295
      {
296
        // else, default append char
297
      }
298
      default:
299
      {
300
        str.append(ch);
301
      }
302
      }
303
    }
304
    return (str.toString());
305 1538 berkley
  }
306 1557 tao
307
  /**
308
   * Get docid from online/url string
309
   */
310
  public static String getDocIdWithRevFromOnlineURL(String url)
311
  {
312
    String docid = null;
313
    String DOCID = "docid";
314
    boolean find = false;
315
    char limited = '&';
316
    int  count = 0; //keep track how many & was found
317
    Vector list = new Vector();// keep index number for &
318
    if (url == null)
319
    {
320
      MetaCatUtil.debugMessage("url is null and null will be returned", 30);
321
      return docid;
322
    }
323
    // the first element in list is 0
324
    list.add(new Integer(0));
325
    for (int i=0; i< url.length(); i++)
326
    {
327
      if (url.charAt(i) == limited)
328
      {
329
        // count plus 1
330
        count++;
331
        list.add(new Integer(i));
332
        // get substring beween two &
333
        String str = url.substring(((Integer)list.elementAt(count-1)).intValue(), i);
334
        MetaCatUtil.debugMessage("substring between two & is: " + str, 30);
335
        //if the subString contains docid, we got it
336
        if (str.indexOf(DOCID) != -1)
337
        {
338
          //get index of '="
339
          int start = getIndexForGivenChar(str, '=')+1;
340
          int end   = str.length();
341
          docid = str.substring(start, end);
342
          find = true;
343
        }//if
344
      }//if
345
    }//for
346
    //if not find, we need check the subtring between the index of last & and
347
    // the end of string
348
    if (!find)
349
    {
350
      MetaCatUtil.debugMessage("Checking the last substring", 35);
351
      String str = url.substring(((Integer)list.elementAt(count)).intValue() +1,
352
                                 url.length());
353
      MetaCatUtil.debugMessage("Last substring is: " + str, 30);
354
      if (str.indexOf(DOCID) != -1)
355
      {
356
          //get index of '="
357
          int start = getIndexForGivenChar(str, '=')+1;
358
          int end   = str.length();
359
          docid = str.substring(start, end);
360
          find = true;
361
      }//if
362
    }//if
363
    MetaCatUtil.debugMessage("The docid from online url is:"+ docid, 30);
364
    return docid.trim();
365
  }
366
367
  private static int getIndexForGivenChar(String str, char character)
368
  {
369
    int index = -1;
370
    // make sure str is not null
371
    if(str == null)
372
    {
373
      MetaCatUtil.debugMessage("The given str is null and -1 will be returned",
374
                                30);
375
      return index;
376
    }
377
    // got though the string
378
    for (int i=0; i<str.length(); i++)
379
    {
380
      // find the first one then break the loop
381
      if (str.charAt(i) == character)
382
      {
383
        index = i;
384
        break;
385
      }//if
386
    }//for
387
    MetaCatUtil.debugMessage("the index for char "+ character +
388
                             " is: "+index, 30);
389
    return index;
390
  }
391
392 1538 berkley
  /**
393 942 tao
   * Utility method to get docid from a given string
394
   * @param string, the given string should be these two format:
395
   *              1) str1.str2  in this case docid= str1.str2
396
   *              2) str1.str2.str3, in this case docid =str1.str2
397
   * @param the sperator char
398
   */
399
  public static String getDocIdFromString(String str)
400
  {
401
    String docId = null;
402 1557 tao
    if (str == null)
403
    {
404
      MetaCatUtil.debugMessage("The given str is null and null will be returned"
405
                                +" in getDocIdfromString", 30);
406
      return docId;
407
    } //make sure docid is not null
408 942 tao
    int dotNumber = 0;//count how many dots in given string
409
    int indexOfLastDot = 0;
410 1538 berkley
411 942 tao
    //assume that seperator is one charactor string
412
    char seperator=getOption("accNumSeparator").charAt(0);
413 1538 berkley
414 942 tao
    for (int i=0; i<str.length(); i++)
415
    {
416
      if ( str.charAt(i)==seperator)
417
      {
418
        dotNumber++;//count how many dots
419
        indexOfLastDot=i;//keep the last dot postion
420
      }
421
    }//for
422 1538 berkley
423 942 tao
    //The string formatt is wrong, because it has more than two or less than
424
    //one seperator
425
    if ( dotNumber>2 || dotNumber < 1)
426
    {
427
      docId=null;
428
    }
429
    else if (dotNumber == 2) //the case for str1.str2.str3
430
    {
431
       docId=str.substring(0, indexOfLastDot);
432
    }
433
    else if (dotNumber == 1) //the case for str1.str2
434
    {
435
      docId=str;
436
    }
437 1538 berkley
438
    return docId;
439 942 tao
  }//getDocIdFromString
440
441 1538 berkley
  /**
442 942 tao
   * Utility method to get version number from a given string
443
   * @param string, the given string should be these two format:
444
   *              1) str1.str2(no version)  version =-1;
445
   *              2) str1.str2.str3, in this case version = str3;
446
   *              3) other, vresion =-2
447
   */
448
  public static int getVersionFromString(String str)
449
                                throws NumberFormatException
450
  {
451
    int version=-1;
452
    String versionString=null;
453
    int dotNumber = 0;//count how many dots in given string
454
    int indexOfLastDot = 0;
455 1538 berkley
456 942 tao
    //assume that seperator is one charactor string
457
    char seperator=getOption("accNumSeparator").charAt(0);
458 1538 berkley
459 942 tao
    for (int i=0; i<str.length(); i++)
460
    {
461
      if ( str.charAt(i)==seperator)
462
      {
463
        dotNumber++;//count how many dots
464
        indexOfLastDot=i;//keep the last dot postion
465
      }
466
    }//for
467 1538 berkley
468 942 tao
    //The string formatt is wrong, because it has more than two or less than
469
    //one seperator
470
    if ( dotNumber>2 || dotNumber < 1)
471
    {
472
      version=-2;
473
    }
474 1538 berkley
    else if (dotNumber == 2 && (indexOfLastDot != (str.length() -1)))
475 1292 tao
     //the case for str1.str2.str3
476 942 tao
    {
477
       versionString=str.substring((indexOfLastDot+1), str.length());
478
       version=Integer.parseInt(versionString);
479
    }
480
    else if (dotNumber == 1) //the case for str1.str2
481
    {
482
      version=-1;
483
    }
484 1538 berkley
485
    return version;
486 942 tao
  }//getVersionFromString
487 1538 berkley
488
489
  /**
490 1292 tao
   * Utility method to get version string from a given string
491
   * @param string, the given string should be these two format:
492
   *              1) str1.str2(no version)  version=null;
493
   *              2) str1.str2.str3, in this case version = str3;
494
   *              3) other, vresion =null;
495
   */
496
  public static String getRevisionStringFromString(String str)
497
                                throws NumberFormatException
498
  {
499
    // String to store the version
500
    String versionString=null;
501
    int dotNumber = 0;//count how many dots in given string
502
    int indexOfLastDot = 0;
503 1538 berkley
504 1292 tao
    //assume that seperator is one charactor string
505
    char seperator=getOption("accNumSeparator").charAt(0);
506 1538 berkley
507 1292 tao
    for (int i=0; i<str.length(); i++)
508
    {
509
      if ( str.charAt(i)==seperator)
510
      {
511
        dotNumber++;//count how many dots
512
        indexOfLastDot=i;//keep the last dot postion
513
      }
514
    }//for
515 1538 berkley
516 1292 tao
    //The string formatt is wrong, because it has more than two or less than
517
    //one seperator
518
    if ( dotNumber>2 || dotNumber < 1)
519
    {
520
      versionString = null;
521
    }
522 1538 berkley
    else if (dotNumber == 2 && (indexOfLastDot != (str.length() -1)))
523 1292 tao
    {
524
      //the case for str1.str2.str3
525
      // indexOfLastDot != (str.length() -1) means get rid of str1.str2.
526
      versionString=str.substring((indexOfLastDot+1), str.length());
527
    }
528
    else if (dotNumber == 1) //the case for str1.str2 or str1.str2.
529
    {
530
      versionString=null;
531
    }
532 1538 berkley
533
    return versionString;
534 1292 tao
  }//getVersionFromString
535 1538 berkley
536 1292 tao
  /**
537 1013 tao
   * Method to get the name of local replication server
538
   */
539 1060 tao
   public static String getLocalReplicationServerName()
540 1013 tao
   {
541
     String replicationServerName=null;
542
     String serverHost=null;
543
     serverHost=getOption("server");
544
     // append "context/servelet/replication" to the host name
545
     replicationServerName=serverHost+getOption("replicationpath");
546
     return replicationServerName;
547 1538 berkley
548 1013 tao
   }
549 1538 berkley
550 1484 tao
   /**
551
    * Method to get docidwithrev from eml2 inline data id
552
    * The eml inline data id would look like eml.200.2.3
553
    */
554 1491 tao
   public static String getDocIdWithoutRevFromInlineDataID(String inlineDataID)
555 1484 tao
   {
556 1491 tao
     String docidWithoutRev = null;
557
     if ( inlineDataID == null)
558
     {
559
       return docidWithoutRev;
560
     }
561 1484 tao
     String seperator = MetaCatUtil.getOption("accNumSeparator");
562 1491 tao
     char charSeperator = seperator.charAt(0);
563
     int targetNumberOfSeperator = 2;// we  want to know his index
564
     int numberOfSeperator = 0;
565
     for (int i = 0; i< inlineDataID.length(); i++)
566
     {
567
       // meet seperator, increase number of seperator
568
       if (inlineDataID.charAt(i) == charSeperator)
569
       {
570
         numberOfSeperator++;
571
       }
572
       // if number of seperator reach the target one, record the index(i)
573
       // and get substring and terminate the loop
574
       if ( numberOfSeperator == targetNumberOfSeperator)
575
       {
576
         docidWithoutRev = inlineDataID.substring(0, i);
577
         break;
578
       }
579
     }
580 1538 berkley
581
     MetaCatUtil.debugMessage("Docid without rev from inlinedata id: " +
582 1491 tao
                               docidWithoutRev, 35);
583
     return docidWithoutRev;
584 1538 berkley
585 1484 tao
   }
586 1545 tao
587
   /**
588
    * Revise stack change a stack to opposite order
589
    */
590
   public static Stack reviseStack(Stack stack)
591
   {
592
     Stack result = new Stack();
593
     // make sure the parameter is correct
594
     if (stack == null || stack.isEmpty())
595
     {
596
       result = stack;
597
       return result;
598
     }
599
600
     while (!stack.isEmpty())
601
     {
602
       Object obj = stack.pop();
603
       result.push(obj);
604
     }
605
     return result;
606
   }
607 1598 tao
608
  /** A method to replace whitespace in url*/
609
  public static String replaceWhiteSpaceForURL(String urlHasWhiteSpace)
610
  {
611
    StringBuffer newUrl = new StringBuffer();
612
    String whiteSpaceReplace ="%20";
613
    if (urlHasWhiteSpace == null || urlHasWhiteSpace.trim().equals(""))
614
    {
615
      return null;
616
    }
617 1538 berkley
618 1598 tao
    for (int i=0; i<urlHasWhiteSpace.length(); i++)
619
    {
620
       char ch = urlHasWhiteSpace.charAt(i);
621
       if ( !Character.isWhitespace(ch))
622
       {
623
          newUrl.append(ch);
624
       }
625
       else
626
       {
627
         //it is white sapce, replace it by %20
628
         newUrl = newUrl.append(whiteSpaceReplace);
629
       }
630
631
   }//for
632
   MetaCatUtil.debugMessage("The new string without space is:"+
633
                             newUrl.toString(), 35);
634
   return newUrl.toString();
635
636
  }// replaceWhiteSpaceForUR
637
638 50 jones
}