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: 2005-09-07 16:47:18 -0700 (Wed, 07 Sep 2005) $'
11
 * '$Revision: 2566 $'
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
import java.util.regex.PatternSyntaxException;
37

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

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

    
47
    public static AbstractDatabase dbAdapter;
48

    
49
    public static Vector pathsForIndexing;
50

    
51
    private static Options options = null;
52

    
53
    private static boolean debug = true;
54
    
55
    private static String[] administrators;
56
    
57
    private static String[] moderators;
58

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

    
68
        // read administrator and moderator lists from metacat.properties
69
        getAdminInfo();
70
    }
71

    
72
    /**
73
     * Instantiate a class using the name of the class at runtime
74
     *
75
     * @param className the fully qualified name of the class to instantiate
76
     */
77
    public static Object createObject(String className) throws Exception
78
    {
79

    
80
        Object object = null;
81
        try {
82
            Class classDefinition = Class.forName(className);
83
            object = classDefinition.newInstance();
84
        } catch (InstantiationException e) {
85
            throw e;
86
        } catch (IllegalAccessException e) {
87
            throw e;
88
        } catch (ClassNotFoundException e) {
89
            throw e;
90
        }
91
        return object;
92
    }
93

    
94
    /**
95
     * Utility method to get an option value from the properties file
96
     *
97
     * @param optionName the name of the option requested
98
     * @return the String value for the option, or null if not set
99
     */
100
    public static String getOption(String optionName)
101
    {
102
        if (options == null) {
103
            options = Options.getInstance();
104
        }
105
        String value = options.getOption(optionName);
106
        return value;
107
    }
108
    
109
    /**
110
     * Utility method to set an option value from the properties file
111
     *
112
     * @param optionName the name of the option requested
113
     */
114
    public static void setOption(String optionName, String newValue)
115
    {
116
        if (options == null) {
117
            options = Options.getInstance();
118
        }
119
        options.setOption(optionName, newValue);
120
        
121
    }
122

    
123
    /** Utility method to convert a file handle into a URL */
124
    public static URL fileToURL(File file)
125
    {
126
        String path = file.getAbsolutePath();
127
        String fSep = System.getProperty("file.separator");
128
        if (fSep != null && fSep.length() == 1)
129
                path = path.replace(fSep.charAt(0), '/');
130
        if (path.length() > 0 && path.charAt(0) != '/') path = '/' + path;
131
        try {
132
            return new URL("file", null, path);
133
        } catch (java.net.MalformedURLException e) {
134
            /*
135
             * According to the spec this could only happen if the file
136
             */
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 ampersand
144
     * separated list of name/value pairs, with equal signs separating the name
145
     * from the value (e.g., name=tom&zip=99801 ). Returns a has of the name
146
     * value pairs, hashed on name.
147
     */
148
    public static Hashtable parseQuery(String query)
149
            throws MalformedURLException
150
    {
151
        String[][] params = new String[200][2];
152
        Hashtable parameters = new Hashtable();
153

    
154
        String temp = "";
155
        boolean ampflag = true;
156
        boolean poundflag = false;
157
        int arrcount = 0;
158

    
159
        if (query != null) {
160
            for (int i = 0; i < query.length(); i++) {
161

    
162
                // go throught the remainder of the query one character at a
163
                // time.
164
                if (query.charAt(i) == '=') {
165
                    // if the current char is a # then the preceding should be
166
                    // a name
167
                    if (!poundflag && ampflag) {
168
                        params[arrcount][0] = temp.trim();
169
                        temp = "";
170
                    } else {
171
                        //if there are two #s or &s in a row throw an
172
                        // exception.
173
                        throw new MalformedURLException(
174
                                "metacatURL: Two parameter names "
175
                                        + "not allowed in sequence");
176
                    }
177
                    poundflag = true;
178
                    ampflag = false;
179
                } else if (query.charAt(i) == '&' || i == query.length() - 1) {
180
                    //the text preceding the & should be the param value.
181
                    if (i == query.length() - 1) {
182
                        //if at the end of the string grab the last value and
183
                        // append it.
184
                        if (query.charAt(i) != '=') {
185
                            //ignore an extra & on the end of the string
186
                            temp += query.charAt(i);
187
                        }
188
                    }
189

    
190
                    if (!ampflag && poundflag) {
191
                        params[arrcount][1] = temp.trim();
192
                        parameters
193
                                .put(params[arrcount][0], params[arrcount][1]);
194
                        temp = "";
195
                        arrcount++; //increment the array to the next row.
196
                    } else {
197
                        //if there are two =s or &s in a row through an
198
                        // exception
199
                        throw new MalformedURLException(
200
                                "metacatURL: Two parameter values "
201
                                        + "not allowed in sequence");
202
                    }
203
                    poundflag = false;
204
                    ampflag = true;
205
                } else {
206
                    //get the next character in the string
207
                    temp += query.charAt(i);
208
                }
209
            }
210
        }
211
        return parameters;
212
    }
213

    
214
    /**
215
     * Utility method to print debugging messages. User can set debug level for
216
     * this message. The number is fewer, the message is more important
217
     *
218
     * @param msg, the content of the message
219
     * @param debugLevel, an integer indicating the message debug leve
220
     */
221
    public static void debugMessage(String msg, int debugLevel)
222
    {
223
        if (debug) {
224
            int limit = 1;
225
            try {
226
                limit = Integer.parseInt(getOption("debuglevel"));
227

    
228
            } catch (Exception e) {
229
                System.out.println(e.getMessage());
230
            }
231
            //don't allow the user set debugLevel less than or equals 0
232
            if (debugLevel <= 0) {
233
                debugLevel = 1;
234
            }
235

    
236
            if (debugLevel < limit) {
237
                System.err.println("@debugprefix@ " + msg);
238
            }
239
        }
240
    }
241

    
242

    
243
    /**
244
     * Utility method to print debugging messages. User can set debug level for
245
     * this message. The number is fewer, the message is more important. Can be
246
     * used to control if the carriage return and debugPrefix are printed
247
     *
248
     * @param msg, the content of the message
249
     * @param debugLevel, an integer indicating the message debug level
250
     * @param debugPrefix, a boolean indicating whether debugprefix
251
     *                    should be printed or not
252
     */
253
    public static void formattedDebugMessage(String msg, int debugLevel,
254
                                      boolean carriageReturn,
255
                                      boolean debugPrefix)
256
    {
257
        if (debug) {
258
            int limit = 1;
259
            try {
260
                limit = Integer.parseInt(getOption("debuglevel"));
261

    
262
            } catch (Exception e) {
263
                System.out.println(e.getMessage());
264
            }
265
            //don't allow the user set debugLevel less than or equals 0
266
            if (debugLevel <= 0) {
267
                debugLevel = 1;
268
            }
269

    
270
            if (debugLevel < limit) {
271
                if(debugPrefix) {
272
                    if(carriageReturn)
273
                        System.err.println("@debugprefix@ " + msg);
274
                    else
275
                        System.err.print("@debugprefix@ " + msg);
276
                } else {
277
                    if(carriageReturn)
278
                        System.err.println(msg);
279
                    else
280
                        System.err.print(msg);
281
                }
282
            }
283
        }
284
    }
285

    
286

    
287
    public static Vector getOptionList(String optiontext)
288
    {
289
        Vector optionsVector = new Vector();
290
        if (optiontext.indexOf(",") == -1) {
291
            optionsVector.addElement(optiontext);
292
            return optionsVector;
293
        }
294

    
295
        while (optiontext.indexOf(",") != -1) {
296
            String s = optiontext.substring(0, optiontext.indexOf(","));
297
            optionsVector.addElement(s.trim());
298
            optiontext = optiontext.substring(optiontext.indexOf(",") + 1,
299
                    optiontext.length());
300
            if (optiontext.indexOf(",") == -1) { //catch the last list entry
301
                optionsVector.addElement(optiontext.trim());
302
            }
303
        }
304
        return optionsVector;
305
    }
306

    
307
    /** Normalizes the given string. Taken from configXML.java */
308
    public static String normalize(String s)
309
    {
310
        StringBuffer str = new StringBuffer();
311

    
312
             int len = (s != null) ? s.length() : 0;
313
             for (int i = 0; i < len; i++) {
314
                 char ch = s.charAt(i);
315
                 switch (ch) {
316
                     case '<': {
317
                         str.append("&lt;");
318
                         break;
319
                     }
320
                     case '>': {
321
                         str.append("&gt;");
322
                         break;
323
                     }
324
                     case '&': {
325
                         /*
326
                          * patch provided by Johnoel Ancheta from U of Hawaii
327
                          */
328
                         // check if & is for a character reference &#xnnnn;
329
                         if (i + 1 < len - 1 && s.charAt(i + 1) == '#') {
330
                             str.append("&#");
331
                             i += 2;
332

    
333
                             ch = s.charAt(i);
334
                             while (i < len && ch != ';') {
335
                                 str.append(ch);
336
                                 i++;
337
                                 ch = s.charAt(i);
338
                             }
339
                             str.append(';');
340
                         } else 
341
                         // check if & is in front of amp; 
342
                         // (we dont yet check for other HTML 4.0 Character entities) 
343
                         if (i + 4 < len -1 && s.charAt(i + 1) == 'a' 
344
                        	 && s.charAt(i + 2) == 'm' 
345
                        		 && s.charAt(i + 3) == 'p' 
346
                        			 && s.charAt(i + 4) == ';'){
347
                             str.append("&amp;");
348
                             i += 5;                        	 
349
                         } else
350
                             str.append("&amp;");
351
                         /////////
352
                         break;
353
                     }
354
                    default: {
355
                         if ( (ch<128) && (ch>31) ) {
356
                             str.append(ch);
357
                         }
358
                         else if (ch<32) {
359
                             if (ch == 10) { // new line
360
                                 str.append(ch);
361
                             }
362
                             if (ch == 13) { // carriage return
363
                                 str.append(ch);
364
                             }
365
                             if (ch == 9) {  // tab
366
                                 str.append(ch);
367
                             }
368
                             // otherwise skip
369
                         }
370
                         else {
371
                             str.append("&#");
372
                             str.append(Integer.toString(ch));
373
                             str.append(';');
374
                         }
375
                     }
376
                 }
377
             }
378
             return str.toString();
379
    }
380

    
381
    /**
382
     * Get docid from online/url string
383
     */
384
    public static String getDocIdWithRevFromOnlineURL(String url)
385
    {
386
        String docid = null;
387
        String DOCID = "docid";
388
        boolean find = false;
389
        char limited = '&';
390
        int count = 0; //keep track how many & was found
391
        Vector list = new Vector();// keep index number for &
392
        if (url == null) {
393
            MetaCatUtil.debugMessage("url is null and null will be returned",
394
                    30);
395
            return docid;
396
        }
397
        // the first element in list is 0
398
        list.add(new Integer(0));
399
        for (int i = 0; i < url.length(); i++) {
400
            if (url.charAt(i) == limited) {
401
                // count plus 1
402
                count++;
403
                list.add(new Integer(i));
404
                // get substring beween two &
405
                String str = url.substring(
406
                        ((Integer) list.elementAt(count - 1)).intValue(), i);
407
                MetaCatUtil.debugMessage("substring between two & is: " + str,
408
                        30);
409
                //if the subString contains docid, we got it
410
                if (str.indexOf(DOCID) != -1) {
411
                    //get index of '="
412
                    int start = getIndexForGivenChar(str, '=') + 1;
413
                    int end = str.length();
414
                    docid = str.substring(start, end);
415
                    find = true;
416
                }//if
417
            }//if
418
        }//for
419
        //if not find, we need check the subtring between the index of last &
420
        // and
421
        // the end of string
422
        if (!find) {
423
            MetaCatUtil.debugMessage("Checking the last substring", 35);
424
            String str = url.substring(((Integer) list.elementAt(count))
425
                    .intValue() + 1, url.length());
426
            MetaCatUtil.debugMessage("Last substring is: " + str, 30);
427
            if (str.indexOf(DOCID) != -1) {
428
                //get index of '="
429
                int start = getIndexForGivenChar(str, '=') + 1;
430
                int end = str.length();
431
                docid = str.substring(start, end);
432
                find = true;
433
            }//if
434
        }//if
435
        MetaCatUtil.debugMessage("The docid from online url is:" + docid, 30);
436
        return docid.trim();
437
    }
438

    
439

    
440
    /**
441
     * Eocgorid identifier will look like: ecogrid://knb/tao.1.1
442
     * The AccessionNumber tao.1.1 will be returned. If the given doesn't
443
     * contains ecogrid, null will be returned.
444
     * @param identifier String
445
     * @return String
446
     */
447
    public static String getAccessionNumberFromEcogridIdentifier(String identifier)
448
    {
449
      String accessionNumber = null;
450
      if (identifier != null && identifier.startsWith(DBSAXHandler.ECOGRID))
451
      {
452
        // find the last "/" in identifier
453
        int indexOfLastSlash = identifier.lastIndexOf("/");
454
        int start = indexOfLastSlash+1;
455
        int end   = identifier.length();
456
        accessionNumber = identifier.substring(start, end);
457
      }
458
      MetaCatUtil.debugMessage("The accession number from url is " +
459
                                 accessionNumber, 10);
460
      return accessionNumber;
461
    }
462

    
463
    private static int getIndexForGivenChar(String str, char character)
464
    {
465
        int index = -1;
466
        // make sure str is not null
467
        if (str == null) {
468
            MetaCatUtil.debugMessage(
469
                    "The given str is null and -1 will be returned", 30);
470
            return index;
471
        }
472
        // got though the string
473
        for (int i = 0; i < str.length(); i++) {
474
            // find the first one then break the loop
475
            if (str.charAt(i) == character) {
476
                index = i;
477
                break;
478
            }//if
479
        }//for
480
        MetaCatUtil.debugMessage("the index for char " + character + " is: "
481
                + index, 30);
482
        return index;
483
    }
484

    
485
    /**
486
     * Utility method to get docid from a given string
487
     *
488
     * @param string, the given string should be these two format: 1) str1.str2
489
     *            in this case docid= str1.str2 2) str1.str2.str3, in this case
490
     *            docid =str1.str2
491
     * @param the sperator char
492
     */
493
    public static String getDocIdFromString(String str)
494
    {
495
        String docId = null;
496
        if (str == null) {
497
            MetaCatUtil.debugMessage(
498
                    "The given str is null and null will be returned"
499
                            + " in getDocIdfromString", 30);
500
            return docId;
501
        } //make sure docid is not 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
            docId = null;
520
        } else if (dotNumber == 2) //the case for str1.str2.str3
521
        {
522
            docId = str.substring(0, indexOfLastDot);
523
        } else if (dotNumber == 1) //the case for str1.str2
524
        {
525
            docId = str;
526
        }
527

    
528
        return docId;
529
    }//getDocIdFromString
530

    
531
    /**
532
     * Utility method to get version number from a given string
533
     *
534
     * @param string, the given string should be these two format: 1)
535
     *            str1.str2(no version) version =-1; 2) str1.str2.str3, in this
536
     *            case version = str3; 3) other, vresion =-2
537
     */
538
    public static int getVersionFromString(String str)
539
            throws NumberFormatException
540
    {
541
        int version = -1;
542
        String versionString = null;
543
        int dotNumber = 0;//count how many dots in given string
544
        int indexOfLastDot = 0;
545

    
546
        //assume that seperator is one charactor string
547
        char seperator = getOption("accNumSeparator").charAt(0);
548

    
549
        for (int i = 0; i < str.length(); i++) {
550
            if (str.charAt(i) == seperator) {
551
                dotNumber++;//count how many dots
552
                indexOfLastDot = i;//keep the last dot postion
553
            }
554
        }//for
555

    
556
        //The string formatt is wrong, because it has more than two or less
557
        // than
558
        //one seperator
559
        if (dotNumber > 2 || dotNumber < 1) {
560
            version = -2;
561
        } else if (dotNumber == 2 && (indexOfLastDot != (str.length() - 1)))
562
        //the case for str1.str2.str3
563
        {
564
            versionString = str.substring((indexOfLastDot + 1), str.length());
565
            version = Integer.parseInt(versionString);
566
        } else if (dotNumber == 1) //the case for str1.str2
567
        {
568
            version = -1;
569
        }
570

    
571
        return version;
572
    }//getVersionFromString
573

    
574
    /**
575
     * Utility method to get version string from a given string
576
     *
577
     * @param string, the given string should be these two format: 1)
578
     *            str1.str2(no version) version=null; 2) str1.str2.str3, in
579
     *            this case version = str3; 3) other, vresion =null;
580
     */
581
    public static String getRevisionStringFromString(String str)
582
            throws NumberFormatException
583
    {
584
        // String to store the version
585
        String versionString = null;
586
        int dotNumber = 0;//count how many dots in given string
587
        int indexOfLastDot = 0;
588

    
589
        //assume that seperator is one charactor string
590
        char seperator = getOption("accNumSeparator").charAt(0);
591

    
592
        for (int i = 0; i < str.length(); i++) {
593
            if (str.charAt(i) == seperator) {
594
                dotNumber++;//count how many dots
595
                indexOfLastDot = i;//keep the last dot postion
596
            }
597
        }//for
598

    
599
        //The string formatt is wrong, because it has more than two or less
600
        // than
601
        //one seperator
602
        if (dotNumber > 2 || dotNumber < 1) {
603
            versionString = null;
604
        } else if (dotNumber == 2 && (indexOfLastDot != (str.length() - 1))) {
605
            //the case for str1.str2.str3
606
            // indexOfLastDot != (str.length() -1) means get rid of str1.str2.
607
            versionString = str.substring((indexOfLastDot + 1), str.length());
608
        } else if (dotNumber == 1) //the case for str1.str2 or str1.str2.
609
        {
610
            versionString = null;
611
        }
612

    
613
        return versionString;
614
    }//getVersionFromString
615

    
616
    /**
617
     * This method will get docid from an AccessionNumber. There is no
618
     * assumption the accessnumber will be str1.str2.str3. It can be more. So
619
     * we think the docid will be get rid of last part
620
     */
621
    public static String getDocIdFromAccessionNumber(String accessionNumber)
622
    {
623
        String docid = null;
624
        if (accessionNumber == null) { return docid; }
625
        String seperator = getOption("accNumSeparator");
626
        int indexOfLastSeperator = accessionNumber.lastIndexOf(seperator);
627
        docid = accessionNumber.substring(0, indexOfLastSeperator);
628
        MetaCatUtil.debugMessage("after parsing accessionnumber, docid is "
629
                + docid, 30);
630
        return docid;
631
    }
632

    
633
    /**
634
     * This method will get inline data id without the revision number.
635
     * So if inlineData.1.2 is passed as input, inlineData.2 is returned.
636
     */
637
    public static String getInlineDataIdWithoutRev(String accessionNumber)
638
    {
639
        String docid = null;
640
        if (accessionNumber == null) { return docid; }
641
        String seperator = getOption("accNumSeparator");
642
        int indexOfLastSeperator = accessionNumber.lastIndexOf(seperator);
643
        String version = accessionNumber.substring(indexOfLastSeperator,
644
                                                   accessionNumber.length());
645
        accessionNumber = accessionNumber.substring(0, indexOfLastSeperator);
646
        indexOfLastSeperator = accessionNumber.lastIndexOf(seperator);
647
        docid = accessionNumber.substring(0, indexOfLastSeperator) + version;
648
        MetaCatUtil.debugMessage("after parsing accessionnumber, docid is "
649
                                 + docid, 30);
650

    
651
        return docid;
652
    }
653

    
654
    /**
655
     * This method will call both getDocIdFromString and
656
     * getDocIdFromAccessionNumber. So first, if the string looks str1.str2,
657
     * the docid will be str1.str2. If the string is str1.str2.str3, the docid
658
     * will be str1.str2. If the string is str1.str2.str3.str4 or more, the
659
     * docid will be str1.str2.str3. If the string look like str1, null will be
660
     * returned
661
     *
662
     */
663
    public static String getSmartDocId(String str)
664
    {
665
        String docid = null;
666
        //call geDocIdFromString first.
667
        docid = getDocIdFromString(str);
668
        // If docid is null, try to call getDocIdFromAccessionNumber
669
        // it will handle the seperator more than2
670
        if (docid == null) {
671
            docid = getDocIdFromAccessionNumber(str);
672
        }
673
        MetaCatUtil.debugMessage("The docid get from smart docid getor is "
674
                + docid, 30);
675
        return docid;
676
    }
677

    
678
    /**
679
     * This method will get revision from an AccessionNumber. There is no
680
     * assumption the accessnumber will be str1.str2.str3. It can be more. So
681
     * we think the docid will be get rid of last part
682
     */
683
    public static int getRevisionFromAccessionNumber(String accessionNumber)
684
            throws NumberFormatException
685
    {
686
        String rev = null;
687
        int revNumber = -1;
688
        if (accessionNumber == null) { return revNumber; }
689
        String seperator = getOption("accNumSeparator");
690
        int indexOfLastSeperator = accessionNumber.lastIndexOf(seperator);
691
        rev = accessionNumber.substring(indexOfLastSeperator + 1,
692
                accessionNumber.length());
693
        revNumber = Integer.parseInt(rev);
694
        MetaCatUtil.debugMessage("after parsing accessionnumber, rev is "
695
                + revNumber, 30);
696
        return revNumber;
697
    }
698

    
699
    /**
700
     * Method to get the name of local replication server
701
     */
702
    public static String getLocalReplicationServerName()
703
    {
704
        String replicationServerName = null;
705
        String serverHost = null;
706
        serverHost = getOption("server");
707
        // append "context/servelet/replication" to the host name
708
        replicationServerName = serverHost + getOption("replicationpath");
709
        return replicationServerName;
710

    
711
    }
712

    
713
    /**
714
     * Method to get docidwithrev from eml2 inline data id The eml inline data
715
     * id would look like eml.200.2.3
716
     */
717
    public static String getDocIdWithoutRevFromInlineDataID(String inlineDataID)
718
    {
719
        String docidWithoutRev = null;
720
        if (inlineDataID == null) { return docidWithoutRev; }
721
        String seperator = MetaCatUtil.getOption("accNumSeparator");
722
        char charSeperator = seperator.charAt(0);
723
        int targetNumberOfSeperator = 2;// we want to know his index
724
        int numberOfSeperator = 0;
725
        for (int i = 0; i < inlineDataID.length(); i++) {
726
            // meet seperator, increase number of seperator
727
            if (inlineDataID.charAt(i) == charSeperator) {
728
                numberOfSeperator++;
729
            }
730
            // if number of seperator reach the target one, record the index(i)
731
            // and get substring and terminate the loop
732
            if (numberOfSeperator == targetNumberOfSeperator) {
733
                docidWithoutRev = inlineDataID.substring(0, i);
734
                break;
735
            }
736
        }
737

    
738
        MetaCatUtil.debugMessage("Docid without rev from inlinedata id: "
739
                + docidWithoutRev, 35);
740
        return docidWithoutRev;
741

    
742
    }
743

    
744
    /**
745
     * Revise stack change a stack to opposite order
746
     */
747
    public static Stack reviseStack(Stack stack)
748
    {
749
        Stack result = new Stack();
750
        // make sure the parameter is correct
751
        if (stack == null || stack.isEmpty()) {
752
            result = stack;
753
            return result;
754
        }
755

    
756
        while (!stack.isEmpty()) {
757
            Object obj = stack.pop();
758
            result.push(obj);
759
        }
760
        return result;
761
    }
762

    
763
    /** A method to replace whitespace in url */
764
    public static String replaceWhiteSpaceForURL(String urlHasWhiteSpace)
765
    {
766
        StringBuffer newUrl = new StringBuffer();
767
        String whiteSpaceReplace = "%20";
768
        if (urlHasWhiteSpace == null || urlHasWhiteSpace.trim().equals("")) { return null; }
769

    
770
        for (int i = 0; i < urlHasWhiteSpace.length(); i++) {
771
            char ch = urlHasWhiteSpace.charAt(i);
772
            if (!Character.isWhitespace(ch)) {
773
                newUrl.append(ch);
774
            } else {
775
                //it is white sapce, replace it by %20
776
                newUrl = newUrl.append(whiteSpaceReplace);
777
            }
778

    
779
        }//for
780
        MetaCatUtil.debugMessage("The new string without space is:"
781
                + newUrl.toString(), 35);
782
        return newUrl.toString();
783

    
784
    }// replaceWhiteSpaceForUR
785

    
786
    /** 
787
     * A method to read administrators and moderators list from the metacat.properties 
788
     **/
789
    public static void getAdminInfo(){
790
    	String adminList = MetaCatUtil.getOption("administrators");
791
        try {
792
            if (adminList != null)
793
            {
794
              administrators = adminList.split(":");
795
            }
796
            else
797
            {
798
               administrators = null;
799
            }
800
        } catch (PatternSyntaxException pse) {
801
            administrators = null;
802
            MetaCatUtil.debugMessage("Error in MetacatServlet.init: "
803
                + pse.getMessage(), 20);
804
        }
805
        
806
    	String modList = MetaCatUtil.getOption("moderators");
807
        try {
808
            if ( modList != null)
809
            {
810
                moderators = modList.split(":");
811
            }
812
            else
813
            {
814
                moderators = null;
815
            }
816
            
817
        } catch (PatternSyntaxException pse) {
818
            moderators = null;
819
            MetaCatUtil.debugMessage("Error in MetacatServlet.init: "
820
                + pse.getMessage(), 20);
821
        }
822
    }
823

    
824
    /** 
825
     * A method to check if the specified user is part of the administrators list 
826
     **/
827
    public static boolean isAdministrator(String username, String[] groups){
828
        // Check that the user is authenticated as an administrator account
829
    	for (int i = 0; i < administrators.length; i++) {
830
            // check the given admin dn is a group dn...
831
        	if(administrators[i].startsWith("cn=")){
832
        		// is a group dn
833
        		for (int j = 0; j < groups.length; j++) {
834
        			if (groups[j].equals(administrators[i])) {
835
                		return true;
836
                	}	
837
        		}   		
838
            } else { 
839
            	// is a user dn
840
            	if (username.equals(administrators[i])) {
841
            		return true;
842
            	}	
843
            }
844
        }
845
                
846
        return false;
847
    }
848
    
849
    /** 
850
     * A method to check if the specified user is part of the moderators list 
851
     **/
852
    public static boolean isModerator(String username, String[] groups){
853
        // Check that the user is authenticated as an administrator account
854
        for (int i = 0; i < moderators.length; i++) {
855
            // check the given admin dn is a group dn...
856
        	if(moderators[i].startsWith("cn=")){
857
            	// is a group dn
858
        		for (int j = 0; j < groups.length; j++) {
859
        			if (groups[j].equals(moderators[i])) {
860
                		return true;
861
                	}	
862
        		}   		
863
            } else { 
864
            	// is a user dn
865
            	if (username.equals(moderators[i])) {
866
            		return true;
867
            	}	
868
            }
869
        }
870
        
871
        return false;
872
    }
873
}
(43-43/63)