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: 2004-12-20 15:12:31 -0800 (Mon, 20 Dec 2004) $'
11
 * '$Revision: 2339 $'
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
                     default: {
267
                         if ((ch<128)&&(ch>31)) {
268
                             str.append(ch);
269
                         }
270
                         else if (ch<32) {
271
                             if (ch== 10) {
272
                                 str.append(ch);
273
                             }
274
                             if (ch==13) {
275
                                 str.append(ch);
276
                             }
277
                             if (ch==9) {
278
                                 str.append(ch);
279
                             }
280
                             // otherwise skip
281
                         }
282
                         else {
283
                             str.append("&#");
284
                             str.append(Integer.toString(ch));
285
                             str.append(';');
286
                         }
287
                     }
288
                 }
289
             }
290
             String temp = str.toString();
291
             temp = temp.trim();
292
             if (temp.length()<1) temp = " ";
293
             return temp;
294
    }
295

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

    
354

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

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

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

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

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

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

    
443
        return docId;
444
    }//getDocIdFromString
445

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

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

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

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

    
486
        return version;
487
    }//getVersionFromString
488

    
489
    /**
490
     * Utility method to get version string from a given string
491
     *
492
     * @param string, the given string should be these two format: 1)
493
     *            str1.str2(no version) version=null; 2) str1.str2.str3, in
494
     *            this case version = str3; 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
            if (str.charAt(i) == seperator) {
509
                dotNumber++;//count how many dots
510
                indexOfLastDot = i;//keep the last dot postion
511
            }
512
        }//for
513

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

    
528
        return versionString;
529
    }//getVersionFromString
530

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

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

    
566
        return docid;
567
    }
568

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

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

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

    
626
    }
627

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

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

    
657
    }
658

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

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

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

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

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

    
699
    }// replaceWhiteSpaceForUR
700

    
701
}
(43-43/63)