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-09-08 13:41:24 -0700 (Thu, 08 Sep 2005) $'
11
 * '$Revision: 2576 $'
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
    private static String[] allowedSubmitters;
60

    
61
    private static String[] deniedSubmitters;
62

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

    
72
        // read administrator and moderator lists from metacat.properties
73
        getUserAccessControlLists();
74
    }
75

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

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

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

    
127
    /** Utility method to convert a file handle into a URL */
128
    public static URL fileToURL(File file)
129
    {
130
        String path = file.getAbsolutePath();
131
        String fSep = System.getProperty("file.separator");
132
        if (fSep != null && fSep.length() == 1)
133
                path = path.replace(fSep.charAt(0), '/');
134
        if (path.length() > 0 && path.charAt(0) != '/') path = '/' + path;
135
        try {
136
            return new URL("file", null, path);
137
        } catch (java.net.MalformedURLException e) {
138
            /*
139
             * According to the spec this could only happen if the file
140
             */
141
            throw new Error("unexpected MalformedURLException");
142
        }
143
    }
144

    
145
    /**
146
     * Utility method to parse the query part of a URL into parameters. This
147
     * method assumes the format of the query par tof the url is an ampersand
148
     * separated list of name/value pairs, with equal signs separating the name
149
     * from the value (e.g., name=tom&zip=99801 ). Returns a has of the name
150
     * value pairs, hashed on name.
151
     */
152
    public static Hashtable parseQuery(String query)
153
            throws MalformedURLException
154
    {
155
        String[][] params = new String[200][2];
156
        Hashtable parameters = new Hashtable();
157

    
158
        String temp = "";
159
        boolean ampflag = true;
160
        boolean poundflag = false;
161
        int arrcount = 0;
162

    
163
        if (query != null) {
164
            for (int i = 0; i < query.length(); i++) {
165

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

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

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

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

    
240
            if (debugLevel < limit) {
241
                System.err.println("@debugprefix@ " + msg);
242
            }
243
        }
244
    }
245

    
246

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

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

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

    
290

    
291
    public static Vector getOptionList(String optiontext)
292
    {
293
        Vector optionsVector = new Vector();
294
        if (optiontext.indexOf(",") == -1) {
295
            optionsVector.addElement(optiontext);
296
            return optionsVector;
297
        }
298

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

    
311
    /** Normalizes the given string. Taken from configXML.java */
312
    public static String normalize(String s)
313
    {
314
        StringBuffer str = new StringBuffer();
315

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

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

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

    
443

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

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

    
489
    /**
490
     * Utility method to get docid from a given string
491
     *
492
     * @param string, the given string should be these two format: 1) str1.str2
493
     *            in this case docid= str1.str2 2) str1.str2.str3, in this case
494
     *            docid =str1.str2
495
     * @param the sperator char
496
     */
497
    public static String getDocIdFromString(String str)
498
    {
499
        String docId = null;
500
        if (str == null) {
501
            MetaCatUtil.debugMessage(
502
                    "The given str is null and null will be returned"
503
                            + " in getDocIdfromString", 30);
504
            return docId;
505
        } //make sure docid is not null
506
        int dotNumber = 0;//count how many dots in given string
507
        int indexOfLastDot = 0;
508

    
509
        //assume that seperator is one charactor string
510
        char seperator = getOption("accNumSeparator").charAt(0);
511

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

    
519
        //The string formatt is wrong, because it has more than two or less
520
        // than
521
        //one seperator
522
        if (dotNumber > 2 || dotNumber < 1) {
523
            docId = null;
524
        } else if (dotNumber == 2) //the case for str1.str2.str3
525
        {
526
            docId = str.substring(0, indexOfLastDot);
527
        } else if (dotNumber == 1) //the case for str1.str2
528
        {
529
            docId = str;
530
        }
531

    
532
        return docId;
533
    }//getDocIdFromString
534

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

    
550
        //assume that seperator is one charactor string
551
        char seperator = getOption("accNumSeparator").charAt(0);
552

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

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

    
575
        return version;
576
    }//getVersionFromString
577

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

    
593
        //assume that seperator is one charactor string
594
        char seperator = getOption("accNumSeparator").charAt(0);
595

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

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

    
617
        return versionString;
618
    }//getVersionFromString
619

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

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

    
655
        return docid;
656
    }
657

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

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

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

    
715
    }
716

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

    
742
        MetaCatUtil.debugMessage("Docid without rev from inlinedata id: "
743
                + docidWithoutRev, 35);
744
        return docidWithoutRev;
745

    
746
    }
747

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

    
760
        while (!stack.isEmpty()) {
761
            Object obj = stack.pop();
762
            result.push(obj);
763
        }
764
        return result;
765
    }
766

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

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

    
783
        }//for
784
        MetaCatUtil.debugMessage("The new string without space is:"
785
                + newUrl.toString(), 35);
786
        return newUrl.toString();
787

    
788
    }// replaceWhiteSpaceForUR
789

    
790
    /** 
791
     * A method to read administrators and moderators list from the metacat.properties 
792
     **/
793
    public static void getUserAccessControlLists(){
794
    	administrators = getListFromOption("administrators");
795
    	moderators = getListFromOption("moderators");
796
    	allowedSubmitters = getListFromOption("allowedSubmitters");
797
    	deniedSubmitters = getListFromOption("deniedSubmitters");
798
    }
799

    
800
    /** 
801
     * A method to read value of a given option from the metacat.properties 
802
     * into specified String array
803
     **/
804
    private static String[] getListFromOption(String optionName){
805
    	String[] list = null;
806
    	String listString = MetaCatUtil.getOption(optionName);
807
      
808
        try {
809
            if ( listString != null && !listString.trim().equals("")) {
810
            	list = listString.split(":");
811
            } else {
812
            	list = null;
813
            }
814
            
815
        } catch (PatternSyntaxException pse) {
816
        	list = null;
817
            MetaCatUtil.debugMessage("Error in MetacatServlet.init: "
818
                + pse.getMessage(), 20);
819
        }
820
        return list;
821
    }
822
    
823
    /** 
824
     * A method to check if the specified user is part of the moderators list 
825
     **/
826
    private static boolean onList(String list[], String username, String[] groups){
827

    
828
    	if(list == null){
829
    		return false;
830
    	}
831

    
832
    	// Check that the user is authenticated as an administrator account
833
        for (int i = 0; i < list.length; i++) {
834
            // check the given admin dn is a group dn...
835
        	if(list[i].startsWith("cn=")){
836
            	// is a group dn
837
        		for (int j = 0; j < groups.length; j++) {
838
        			if (groups[j].equals(list[i])) {
839
                		return true;
840
                	}	
841
        		}   		
842
            } else { 
843
            	// is a user dn
844
            	if (username.equals(list[i])) {
845
    	    		return true;
846
            	}	
847
            }
848
        }
849
        return false;
850
    }
851

    
852
    /** 
853
     * A method to check if the specified user is part of the administrators list 
854
     **/
855
    public static boolean isAdministrator(String username, String[] groups){
856
    	return (onList(administrators, username, groups));
857
    }
858
    
859
    /** 
860
     * A method to check if the specified user is part of the moderators list 
861
     **/
862
    public static boolean isModerator(String username, String[] groups){
863
    	return (onList(moderators, username, groups));
864
    }
865

    
866
    /** 
867
     * A method to check if the specified user is part of the moderators list 
868
     **/
869
    public static boolean isAllowedSubmitter(String username, String[] groups){
870
    	if(allowedSubmitters != null){
871
    		return (onList(allowedSubmitters, username, groups));
872
    	} else {
873
    		// no allowedSubmitters list specified - 
874
    		// hence everyone should be allowed
875
    		return true;
876
    	}
877
   }
878

    
879
    /** 
880
     * A method to check if the specified user is part of the moderators list 
881
     **/
882
    public static boolean isDeniedSubmitter(String username, String[] groups){
883
		return (onList(deniedSubmitters, username, groups));
884
    }
885
    
886
    /** 
887
     * A method to check if the specified user can insert the document 
888
     **/
889
    public static boolean canInsertOrUpdate(String username, String[] groups){
890
    	return (isAllowedSubmitter(username, groups) 
891
    			&& !isDeniedSubmitter(username, groups));
892
    }
893
}
(43-43/63)