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: 2003-04-22 09:51:34 -0700 (Tue, 22 Apr 2003) $'
11
 * '$Revision: 1598 $'
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.Stack;
40
import java.util.Vector;
41

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

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

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

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

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

    
67

    
68

    
69
  /**
70
   * 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
   */
74
  public static Object createObject(String className) throws Exception {
75

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

    
105
  /**
106
   * 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
   */
111
  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
  }
118

    
119

    
120

    
121

    
122
  /** 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
  /**
142
   * Utility method to parse the query part of a URL into parameters. This
143
   * method assumes the format of the query par tof the url is an
144
   * 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
    if ( query != null ) {
159
      for (int i=0; i < query.length(); i++) {
160

    
161
        // go throught the remainder of the query one character at a time.
162
        if (query.charAt(i) == '=') {
163
          // 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
          } else {
168
            //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
        } else if (query.charAt(i) == '&' || i == query.length()-1) {
175
          //the text preceding the & should be the param value.
176
          if (i == query.length() - 1) {
177
            //if at the end of the string grab the last value and append it.
178
            if (query.charAt(i) != '=') {
179
            //ignore an extra & on the end of the string
180
              temp += query.charAt(i);
181
            }
182
          }
183

    
184
          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
          } else {
190
            //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
        } else {
197
          //get the next character in the string
198
          temp += query.charAt(i);
199
        }
200
      }
201
    }
202
    return parameters;
203
  }
204

    
205
   /**
206
   * 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
  public static void debugMessage(String msg, int debugLevel)
212
  {
213
    if (debug)
214
    {
215
      int limit = 1;
216
      try
217
      {
218
        limit=Integer.parseInt(getOption("debuglevel"));
219

    
220
      }
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

    
231
      if (debugLevel < limit)
232
      {
233
        System.err.println("@debugprefix@ " +msg);
234
      }
235
    }
236
  }
237

    
238

    
239
  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

    
248
    while(optiontext.indexOf(",") != -1)
249
    {
250
      String s = optiontext.substring(0, optiontext.indexOf(","));
251
      options.addElement(s.trim());
252
      optiontext = optiontext.substring(optiontext.indexOf(",") + 1,
253
                                        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

    
262
  /** 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
  }
306
  
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
  /**
393
   * 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
    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
    int dotNumber = 0;//count how many dots in given string
409
    int indexOfLastDot = 0;
410

    
411
    //assume that seperator is one charactor string
412
    char seperator=getOption("accNumSeparator").charAt(0);
413

    
414
    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

    
423
    //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

    
438
    return docId;
439
  }//getDocIdFromString
440

    
441
  /**
442
   * 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

    
456
    //assume that seperator is one charactor string
457
    char seperator=getOption("accNumSeparator").charAt(0);
458

    
459
    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

    
468
    //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
    else if (dotNumber == 2 && (indexOfLastDot != (str.length() -1)))
475
     //the case for str1.str2.str3
476
    {
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

    
485
    return version;
486
  }//getVersionFromString
487

    
488

    
489
  /**
490
   * 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

    
504
    //assume that seperator is one charactor string
505
    char seperator=getOption("accNumSeparator").charAt(0);
506

    
507
    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

    
516
    //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
    else if (dotNumber == 2 && (indexOfLastDot != (str.length() -1)))
523
    {
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

    
533
    return versionString;
534
  }//getVersionFromString
535

    
536
  /**
537
   * Method to get the name of local replication server
538
   */
539
   public static String getLocalReplicationServerName()
540
   {
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

    
548
   }
549

    
550
   /**
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
   public static String getDocIdWithoutRevFromInlineDataID(String inlineDataID)
555
   {
556
     String docidWithoutRev = null;
557
     if ( inlineDataID == null)
558
     {
559
       return docidWithoutRev;
560
     }
561
     String seperator = MetaCatUtil.getOption("accNumSeparator");
562
     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

    
581
     MetaCatUtil.debugMessage("Docid without rev from inlinedata id: " +
582
                               docidWithoutRev, 35);
583
     return docidWithoutRev;
584

    
585
   }
586
   
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
  
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

    
618
    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
}
(41-41/57)