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: sgarg $'
10
 *     '$Date: 2005-03-31 18:00:53 -0800 (Thu, 31 Mar 2005) $'
11
 * '$Revision: 2437 $'
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.MalformedURLException;
32
import java.net.URL;
33
import java.util.Hashtable;
34
import java.util.Stack;
35
import java.util.Vector;
36

    
37
import edu.ucsb.nceas.dbadapter.AbstractDatabase;
38
import edu.ucsb.nceas.utilities.Options;
39

    
40
/**
41
 * A suite of utility classes for the metadata catalog server
42
 */
43
public class MetaCatUtil
44
{
45

    
46
    public static AbstractDatabase dbAdapter;
47

    
48
    private static Options options = null;
49

    
50
    private static boolean debug = true;
51

    
52

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

    
65
    /**
66
     * Instantiate a class using the name of the class at runtime
67
     *
68
     * @param className the fully qualified name of the class to instantiate
69
     */
70
    public static Object createObject(String className) throws Exception
71
    {
72

    
73
        Object object = null;
74
        try {
75
            Class classDefinition = Class.forName(className);
76
            object = classDefinition.newInstance();
77
        } catch (InstantiationException e) {
78
            throw e;
79
        } catch (IllegalAccessException e) {
80
            throw e;
81
        } catch (ClassNotFoundException e) {
82
            throw e;
83
        }
84
        return object;
85
    }
86

    
87
    /**
88
     * Utility method to get an option value from the properties file
89
     *
90
     * @param optionName the name of the option requested
91
     * @return the String value for the option, or null if not set
92
     */
93
    public static String getOption(String optionName)
94
    {
95
        if (options == null) {
96
            options = Options.getInstance();
97
        }
98
        String value = options.getOption(optionName);
99
        return value;
100
    }
101

    
102
    /** Utility method to convert a file handle into a URL */
103
    public static URL fileToURL(File file)
104
    {
105
        String path = file.getAbsolutePath();
106
        String fSep = System.getProperty("file.separator");
107
        if (fSep != null && fSep.length() == 1)
108
                path = path.replace(fSep.charAt(0), '/');
109
        if (path.length() > 0 && path.charAt(0) != '/') path = '/' + path;
110
        try {
111
            return new URL("file", null, path);
112
        } catch (java.net.MalformedURLException e) {
113
            /*
114
             * According to the spec this could only happen if the file
115
             */
116
            throw new Error("unexpected MalformedURLException");
117
        }
118
    }
119

    
120
    /**
121
     * Utility method to parse the query part of a URL into parameters. This
122
     * method assumes the format of the query par tof the url is an ampersand
123
     * separated list of name/value pairs, with equal signs separating the name
124
     * from the value (e.g., name=tom&zip=99801 ). Returns a has of the name
125
     * value pairs, hashed on name.
126
     */
127
    public static Hashtable parseQuery(String query)
128
            throws MalformedURLException
129
    {
130
        String[][] params = new String[200][2];
131
        Hashtable parameters = new Hashtable();
132

    
133
        String temp = "";
134
        boolean ampflag = true;
135
        boolean poundflag = false;
136
        int arrcount = 0;
137

    
138
        if (query != null) {
139
            for (int i = 0; i < query.length(); i++) {
140

    
141
                // go throught the remainder of the query one character at a
142
                // time.
143
                if (query.charAt(i) == '=') {
144
                    // if the current char is a # then the preceding should be
145
                    // a name
146
                    if (!poundflag && ampflag) {
147
                        params[arrcount][0] = temp.trim();
148
                        temp = "";
149
                    } else {
150
                        //if there are two #s or &s in a row throw an
151
                        // exception.
152
                        throw new MalformedURLException(
153
                                "metacatURL: Two parameter names "
154
                                        + "not allowed in sequence");
155
                    }
156
                    poundflag = true;
157
                    ampflag = false;
158
                } else if (query.charAt(i) == '&' || i == query.length() - 1) {
159
                    //the text preceding the & should be the param value.
160
                    if (i == query.length() - 1) {
161
                        //if at the end of the string grab the last value and
162
                        // append it.
163
                        if (query.charAt(i) != '=') {
164
                            //ignore an extra & on the end of the string
165
                            temp += query.charAt(i);
166
                        }
167
                    }
168

    
169
                    if (!ampflag && poundflag) {
170
                        params[arrcount][1] = temp.trim();
171
                        parameters
172
                                .put(params[arrcount][0], params[arrcount][1]);
173
                        temp = "";
174
                        arrcount++; //increment the array to the next row.
175
                    } else {
176
                        //if there are two =s or &s in a row through an
177
                        // exception
178
                        throw new MalformedURLException(
179
                                "metacatURL: Two parameter values "
180
                                        + "not allowed in sequence");
181
                    }
182
                    poundflag = false;
183
                    ampflag = true;
184
                } else {
185
                    //get the next character in the string
186
                    temp += query.charAt(i);
187
                }
188
            }
189
        }
190
        return parameters;
191
    }
192

    
193
    /**
194
     * Utility method to print debugging messages. User can set debug level for
195
     * this message. The number is fewer, the message is more important
196
     *
197
     * @param msg, the content of the message
198
     * @param debugLevel, an integer indicating the message debug leve
199
     */
200
    public static void debugMessage(String msg, int debugLevel)
201
    {
202
        if (debug) {
203
            int limit = 1;
204
            try {
205
                limit = Integer.parseInt(getOption("debuglevel"));
206

    
207
            } catch (Exception e) {
208
                System.out.println(e.getMessage());
209
            }
210
            //don't allow the user set debugLevel less than or equals 0
211
            if (debugLevel <= 0) {
212
                debugLevel = 1;
213
            }
214

    
215
            if (debugLevel < limit) {
216
                System.err.println("@debugprefix@ " + msg);
217
            }
218
        }
219
    }
220

    
221
    public static Vector getOptionList(String optiontext)
222
    {
223
        Vector optionsVector = new Vector();
224
        if (optiontext.indexOf(",") == -1) {
225
            optionsVector.addElement(optiontext);
226
            return optionsVector;
227
        }
228

    
229
        while (optiontext.indexOf(",") != -1) {
230
            String s = optiontext.substring(0, optiontext.indexOf(","));
231
            optionsVector.addElement(s.trim());
232
            optiontext = optiontext.substring(optiontext.indexOf(",") + 1,
233
                    optiontext.length());
234
            if (optiontext.indexOf(",") == -1) { //catch the last list entry
235
                optionsVector.addElement(optiontext.trim());
236
            }
237
        }
238
        return optionsVector;
239
    }
240

    
241
    /** Normalizes the given string. Taken from configXML.java */
242
    public static String normalize(String s)
243
    {
244
        StringBuffer str = new StringBuffer();
245

    
246
             int len = (s != null) ? s.length() : 0;
247
             for (int i = 0; i < len; i++) {
248
                 char ch = s.charAt(i);
249
                 switch (ch) {
250
                     case '<': {
251
                         str.append("&lt;");
252
                         break;
253
                     }
254
                     case '>': {
255
                         str.append("&gt;");
256
                         break;
257
                     }
258
                     case '&': {
259
                         str.append("&amp;");
260
                         break;
261
                     }
262
                     case '"': {
263
                         str.append("&quot;");
264
                         break;
265
                     }
266
                     case '\r':
267
                     case '\n': {
268
                         // else, default append char
269
                     }
270
                     default: {
271
                         if ((ch<128)&&(ch>31)) {
272
                             str.append(ch);
273
                         }
274
                         else if (ch<32) {
275
                             if (ch== 10) {
276
                                 str.append(ch);
277
                             }
278
                             if (ch==13) {
279
                                 str.append(ch);
280
                             }
281
                             if (ch==9) {
282
                                 str.append(ch);
283
                             }
284
                             // otherwise skip
285
                         }
286
                         else {
287
                             str.append("&#");
288
                             str.append(Integer.toString(ch));
289
                             str.append(';');
290
                         }
291
                     }
292
                 }
293
             }
294
             return str.toString();
295
    }
296

    
297
    /**
298
     * Get docid from online/url string
299
     */
300
    public static String getDocIdWithRevFromOnlineURL(String url)
301
    {
302
        String docid = null;
303
        String DOCID = "docid";
304
        boolean find = false;
305
        char limited = '&';
306
        int count = 0; //keep track how many & was found
307
        Vector list = new Vector();// keep index number for &
308
        if (url == null) {
309
            MetaCatUtil.debugMessage("url is null and null will be returned",
310
                    30);
311
            return docid;
312
        }
313
        // the first element in list is 0
314
        list.add(new Integer(0));
315
        for (int i = 0; i < url.length(); i++) {
316
            if (url.charAt(i) == limited) {
317
                // count plus 1
318
                count++;
319
                list.add(new Integer(i));
320
                // get substring beween two &
321
                String str = url.substring(
322
                        ((Integer) list.elementAt(count - 1)).intValue(), i);
323
                MetaCatUtil.debugMessage("substring between two & is: " + str,
324
                        30);
325
                //if the subString contains docid, we got it
326
                if (str.indexOf(DOCID) != -1) {
327
                    //get index of '="
328
                    int start = getIndexForGivenChar(str, '=') + 1;
329
                    int end = str.length();
330
                    docid = str.substring(start, end);
331
                    find = true;
332
                }//if
333
            }//if
334
        }//for
335
        //if not find, we need check the subtring between the index of last &
336
        // and
337
        // the end of string
338
        if (!find) {
339
            MetaCatUtil.debugMessage("Checking the last substring", 35);
340
            String str = url.substring(((Integer) list.elementAt(count))
341
                    .intValue() + 1, url.length());
342
            MetaCatUtil.debugMessage("Last substring is: " + str, 30);
343
            if (str.indexOf(DOCID) != -1) {
344
                //get index of '="
345
                int start = getIndexForGivenChar(str, '=') + 1;
346
                int end = str.length();
347
                docid = str.substring(start, end);
348
                find = true;
349
            }//if
350
        }//if
351
        MetaCatUtil.debugMessage("The docid from online url is:" + docid, 30);
352
        return docid.trim();
353
    }
354

    
355

    
356
    /**
357
     * Eocgorid identifier will look like: ecogrid://knb/tao.1.1
358
     * The AccessionNumber tao.1.1 will be returned. If the given doesn't
359
     * contains ecogrid, null will be returned.
360
     * @param identifier String
361
     * @return String
362
     */
363
    public static String getAccessionNumberFromEcogridIdentifier(String identifier)
364
    {
365
      String accessionNumber = null;
366
      if (identifier != null && identifier.startsWith(DBSAXHandler.ECOGRID))
367
      {
368
        // find the last "/" in identifier
369
        int indexOfLastSlash = identifier.lastIndexOf("/");
370
        int start = indexOfLastSlash+1;
371
        int end   = identifier.length();
372
        accessionNumber = identifier.substring(start, end);
373
      }
374
      MetaCatUtil.debugMessage("The accession number from url is " +
375
                                 accessionNumber, 10);
376
      return accessionNumber;
377
    }
378

    
379
    private static int getIndexForGivenChar(String str, char character)
380
    {
381
        int index = -1;
382
        // make sure str is not null
383
        if (str == null) {
384
            MetaCatUtil.debugMessage(
385
                    "The given str is null and -1 will be returned", 30);
386
            return index;
387
        }
388
        // got though the string
389
        for (int i = 0; i < str.length(); i++) {
390
            // find the first one then break the loop
391
            if (str.charAt(i) == character) {
392
                index = i;
393
                break;
394
            }//if
395
        }//for
396
        MetaCatUtil.debugMessage("the index for char " + character + " is: "
397
                + index, 30);
398
        return index;
399
    }
400

    
401
    /**
402
     * Utility method to get docid from a given string
403
     *
404
     * @param string, the given string should be these two format: 1) str1.str2
405
     *            in this case docid= str1.str2 2) str1.str2.str3, in this case
406
     *            docid =str1.str2
407
     * @param the sperator char
408
     */
409
    public static String getDocIdFromString(String str)
410
    {
411
        String docId = null;
412
        if (str == null) {
413
            MetaCatUtil.debugMessage(
414
                    "The given str is null and null will be returned"
415
                            + " in getDocIdfromString", 30);
416
            return docId;
417
        } //make sure docid is not null
418
        int dotNumber = 0;//count how many dots in given string
419
        int indexOfLastDot = 0;
420

    
421
        //assume that seperator is one charactor string
422
        char seperator = getOption("accNumSeparator").charAt(0);
423

    
424
        for (int i = 0; i < str.length(); i++) {
425
            if (str.charAt(i) == seperator) {
426
                dotNumber++;//count how many dots
427
                indexOfLastDot = i;//keep the last dot postion
428
            }
429
        }//for
430

    
431
        //The string formatt is wrong, because it has more than two or less
432
        // than
433
        //one seperator
434
        if (dotNumber > 2 || dotNumber < 1) {
435
            docId = null;
436
        } else if (dotNumber == 2) //the case for str1.str2.str3
437
        {
438
            docId = str.substring(0, indexOfLastDot);
439
        } else if (dotNumber == 1) //the case for str1.str2
440
        {
441
            docId = str;
442
        }
443

    
444
        return docId;
445
    }//getDocIdFromString
446

    
447
    /**
448
     * Utility method to get version number from a given string
449
     *
450
     * @param string, the given string should be these two format: 1)
451
     *            str1.str2(no version) version =-1; 2) str1.str2.str3, in this
452
     *            case version = str3; 3) other, vresion =-2
453
     */
454
    public static int getVersionFromString(String str)
455
            throws NumberFormatException
456
    {
457
        int version = -1;
458
        String versionString = null;
459
        int dotNumber = 0;//count how many dots in given string
460
        int indexOfLastDot = 0;
461

    
462
        //assume that seperator is one charactor string
463
        char seperator = getOption("accNumSeparator").charAt(0);
464

    
465
        for (int i = 0; i < str.length(); i++) {
466
            if (str.charAt(i) == seperator) {
467
                dotNumber++;//count how many dots
468
                indexOfLastDot = i;//keep the last dot postion
469
            }
470
        }//for
471

    
472
        //The string formatt is wrong, because it has more than two or less
473
        // than
474
        //one seperator
475
        if (dotNumber > 2 || dotNumber < 1) {
476
            version = -2;
477
        } else if (dotNumber == 2 && (indexOfLastDot != (str.length() - 1)))
478
        //the case for str1.str2.str3
479
        {
480
            versionString = str.substring((indexOfLastDot + 1), str.length());
481
            version = Integer.parseInt(versionString);
482
        } else if (dotNumber == 1) //the case for str1.str2
483
        {
484
            version = -1;
485
        }
486

    
487
        return version;
488
    }//getVersionFromString
489

    
490
    /**
491
     * Utility method to get version string from a given string
492
     *
493
     * @param string, the given string should be these two format: 1)
494
     *            str1.str2(no version) version=null; 2) str1.str2.str3, in
495
     *            this case version = str3; 3) other, vresion =null;
496
     */
497
    public static String getRevisionStringFromString(String str)
498
            throws NumberFormatException
499
    {
500
        // String to store the version
501
        String versionString = null;
502
        int dotNumber = 0;//count how many dots in given string
503
        int indexOfLastDot = 0;
504

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

    
508
        for (int i = 0; i < str.length(); i++) {
509
            if (str.charAt(i) == seperator) {
510
                dotNumber++;//count how many dots
511
                indexOfLastDot = i;//keep the last dot postion
512
            }
513
        }//for
514

    
515
        //The string formatt is wrong, because it has more than two or less
516
        // than
517
        //one seperator
518
        if (dotNumber > 2 || dotNumber < 1) {
519
            versionString = null;
520
        } else if (dotNumber == 2 && (indexOfLastDot != (str.length() - 1))) {
521
            //the case for str1.str2.str3
522
            // indexOfLastDot != (str.length() -1) means get rid of str1.str2.
523
            versionString = str.substring((indexOfLastDot + 1), str.length());
524
        } else if (dotNumber == 1) //the case for str1.str2 or str1.str2.
525
        {
526
            versionString = null;
527
        }
528

    
529
        return versionString;
530
    }//getVersionFromString
531

    
532
    /**
533
     * This method will get docid from an AccessionNumber. There is no
534
     * assumption the accessnumber will be str1.str2.str3. It can be more. So
535
     * we think the docid will be get rid of last part
536
     */
537
    public static String getDocIdFromAccessionNumber(String accessionNumber)
538
    {
539
        String docid = null;
540
        if (accessionNumber == null) { return docid; }
541
        String seperator = getOption("accNumSeparator");
542
        int indexOfLastSeperator = accessionNumber.lastIndexOf(seperator);
543
        docid = accessionNumber.substring(0, indexOfLastSeperator);
544
        MetaCatUtil.debugMessage("after parsing accessionnumber, docid is "
545
                + docid, 30);
546
        return docid;
547
    }
548

    
549
    /**
550
     * This method will get inline data id without the revision number.
551
     * So if inlineData.1.2 is passed as input, inlineData.2 is returned.
552
     */
553
    public static String getInlineDataIdWithoutRev(String accessionNumber)
554
    {
555
        String docid = null;
556
        if (accessionNumber == null) { return docid; }
557
        String seperator = getOption("accNumSeparator");
558
        int indexOfLastSeperator = accessionNumber.lastIndexOf(seperator);
559
        String version = accessionNumber.substring(indexOfLastSeperator,
560
                                                   accessionNumber.length());
561
        accessionNumber = accessionNumber.substring(0, indexOfLastSeperator);
562
        indexOfLastSeperator = accessionNumber.lastIndexOf(seperator);
563
        docid = accessionNumber.substring(0, indexOfLastSeperator) + version;
564
        MetaCatUtil.debugMessage("after parsing accessionnumber, docid is "
565
                                 + docid, 30);
566

    
567
        return docid;
568
    }
569

    
570
    /**
571
     * This method will call both getDocIdFromString and
572
     * getDocIdFromAccessionNumber. So first, if the string looks str1.str2,
573
     * the docid will be str1.str2. If the string is str1.str2.str3, the docid
574
     * will be str1.str2. If the string is str1.str2.str3.str4 or more, the
575
     * docid will be str1.str2.str3. If the string look like str1, null will be
576
     * returned
577
     *
578
     */
579
    public static String getSmartDocId(String str)
580
    {
581
        String docid = null;
582
        //call geDocIdFromString first.
583
        docid = getDocIdFromString(str);
584
        // If docid is null, try to call getDocIdFromAccessionNumber
585
        // it will handle the seperator more than2
586
        if (docid == null) {
587
            docid = getDocIdFromAccessionNumber(str);
588
        }
589
        MetaCatUtil.debugMessage("The docid get from smart docid getor is "
590
                + docid, 30);
591
        return docid;
592
    }
593

    
594
    /**
595
     * This method will get revision from an AccessionNumber. There is no
596
     * assumption the accessnumber will be str1.str2.str3. It can be more. So
597
     * we think the docid will be get rid of last part
598
     */
599
    public static int getRevisionFromAccessionNumber(String accessionNumber)
600
            throws NumberFormatException
601
    {
602
        String rev = null;
603
        int revNumber = -1;
604
        if (accessionNumber == null) { return revNumber; }
605
        String seperator = getOption("accNumSeparator");
606
        int indexOfLastSeperator = accessionNumber.lastIndexOf(seperator);
607
        rev = accessionNumber.substring(indexOfLastSeperator + 1,
608
                accessionNumber.length());
609
        revNumber = Integer.parseInt(rev);
610
        MetaCatUtil.debugMessage("after parsing accessionnumber, rev is "
611
                + revNumber, 30);
612
        return revNumber;
613
    }
614

    
615
    /**
616
     * Method to get the name of local replication server
617
     */
618
    public static String getLocalReplicationServerName()
619
    {
620
        String replicationServerName = null;
621
        String serverHost = null;
622
        serverHost = getOption("server");
623
        // append "context/servelet/replication" to the host name
624
        replicationServerName = serverHost + getOption("replicationpath");
625
        return replicationServerName;
626

    
627
    }
628

    
629
    /**
630
     * Method to get docidwithrev from eml2 inline data id The eml inline data
631
     * id would look like eml.200.2.3
632
     */
633
    public static String getDocIdWithoutRevFromInlineDataID(String inlineDataID)
634
    {
635
        String docidWithoutRev = null;
636
        if (inlineDataID == null) { return docidWithoutRev; }
637
        String seperator = MetaCatUtil.getOption("accNumSeparator");
638
        char charSeperator = seperator.charAt(0);
639
        int targetNumberOfSeperator = 2;// we want to know his index
640
        int numberOfSeperator = 0;
641
        for (int i = 0; i < inlineDataID.length(); i++) {
642
            // meet seperator, increase number of seperator
643
            if (inlineDataID.charAt(i) == charSeperator) {
644
                numberOfSeperator++;
645
            }
646
            // if number of seperator reach the target one, record the index(i)
647
            // and get substring and terminate the loop
648
            if (numberOfSeperator == targetNumberOfSeperator) {
649
                docidWithoutRev = inlineDataID.substring(0, i);
650
                break;
651
            }
652
        }
653

    
654
        MetaCatUtil.debugMessage("Docid without rev from inlinedata id: "
655
                + docidWithoutRev, 35);
656
        return docidWithoutRev;
657

    
658
    }
659

    
660
    /**
661
     * Revise stack change a stack to opposite order
662
     */
663
    public static Stack reviseStack(Stack stack)
664
    {
665
        Stack result = new Stack();
666
        // make sure the parameter is correct
667
        if (stack == null || stack.isEmpty()) {
668
            result = stack;
669
            return result;
670
        }
671

    
672
        while (!stack.isEmpty()) {
673
            Object obj = stack.pop();
674
            result.push(obj);
675
        }
676
        return result;
677
    }
678

    
679
    /** A method to replace whitespace in url */
680
    public static String replaceWhiteSpaceForURL(String urlHasWhiteSpace)
681
    {
682
        StringBuffer newUrl = new StringBuffer();
683
        String whiteSpaceReplace = "%20";
684
        if (urlHasWhiteSpace == null || urlHasWhiteSpace.trim().equals("")) { return null; }
685

    
686
        for (int i = 0; i < urlHasWhiteSpace.length(); i++) {
687
            char ch = urlHasWhiteSpace.charAt(i);
688
            if (!Character.isWhitespace(ch)) {
689
                newUrl.append(ch);
690
            } else {
691
                //it is white sapce, replace it by %20
692
                newUrl = newUrl.append(whiteSpaceReplace);
693
            }
694

    
695
        }//for
696
        MetaCatUtil.debugMessage("The new string without space is:"
697
                + newUrl.toString(), 35);
698
        return newUrl.toString();
699

    
700
    }// replaceWhiteSpaceForUR
701

    
702
}
(43-43/63)