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: 2006-01-19 14:35:00 -0800 (Thu, 19 Jan 2006) $'
11
 * '$Revision: 2893 $'
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.HashMap;
34
import java.util.Hashtable;
35
import java.util.Stack;
36
import java.util.Vector;
37
import java.util.regex.PatternSyntaxException;
38

    
39
import org.apache.log4j.Logger;
40

    
41
import edu.ucsb.nceas.dbadapter.AbstractDatabase;
42
import edu.ucsb.nceas.utilities.Options;
43

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

    
50
    public static AbstractDatabase dbAdapter;
51

    
52
    public static Vector pathsForIndexing;
53
    
54
    public static HashMap skinconfigs = new HashMap();
55

    
56
    private static Options options = null;
57

    
58
    private static boolean debug = true;
59
    
60
    private static String[] administrators;
61
    
62
    private static String[] moderators;
63

    
64
    private static String[] allowedSubmitters;
65

    
66
    private static String[] deniedSubmitters;
67
    
68
    private static Logger logMetacat = Logger.getLogger(MetaCatUtil.class);
69

    
70
    static {
71
    	// Determine our db adapter class and create an instance of that class
72
        try {
73
            dbAdapter = (AbstractDatabase) createObject(getOption("dbAdapter"));
74
        } catch (Exception e) {
75
            System.err.println("Error in MetaCatUtil static block:"
76
                    + e.getMessage());
77
        }
78

    
79
        // read administrator and moderator lists from metacat.properties
80
        getUserAccessControlLists();
81
    }
82
    
83
    /**
84
     * Instantiate a class using the name of the class at runtime
85
     *
86
     * @param className the fully qualified name of the class to instantiate
87
     */
88
    public static Object createObject(String className) throws Exception
89
    {
90

    
91
        Object object = null;
92
        try {
93
            Class classDefinition = Class.forName(className);
94
            object = classDefinition.newInstance();
95
        } catch (InstantiationException e) {
96
            throw e;
97
        } catch (IllegalAccessException e) {
98
            throw e;
99
        } catch (ClassNotFoundException e) {
100
            throw e;
101
        }
102
        return object;
103
    }
104

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

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

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

    
165
        String temp = "";
166
        boolean ampflag = true;
167
        boolean poundflag = false;
168
        int arrcount = 0;
169

    
170
        if (query != null) {
171
            for (int i = 0; i < query.length(); i++) {
172

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

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

    
225
    /**
226
     * Utility method to print debugging messages. User can set debug level for
227
     * this message. The number is fewer, the message is more important
228
     *
229
     * @param msg, the content of the message
230
     * @param debugLevel, an integer indicating the message debug leve
231
     */
232
    /** 
233
     * Commenting out the function for now...
234
     * public static void debugMessage(String msg, int debugLevel)
235
     * {
236
     *   if (debug) {
237
     *       int limit = 1;
238
     *       try {
239
     *           limit = Integer.parseInt(getOption("debuglevel"));
240
     *
241
     *       } catch (Exception e) {
242
     *           System.out.println(e.getMessage());
243
     *       }
244
     *       //don't allow the user set debugLevel less than or equals 0
245
     *       if (debugLevel <= 0) {
246
     *           debugLevel = 1;
247
     *       }
248
     *
249
     *       if (debugLevel < limit) {
250
     *           System.err.println("@debugprefix@ " + msg);
251
     *       }
252
     *   }
253
     *}
254
     */
255

    
256

    
257
    /**
258
     * Utility method to print debugging messages. User can set debug level for
259
     * this message. The number is fewer, the message is more important
260
     *
261
     * @param msg, the content of the message
262
     * @param debugLevel, an integer indicating the message debug leve
263
     */
264
    public static void printMessage(String msg)
265
    {
266
    	System.err.println("@debugprefix@ " + msg);
267
    }
268
    
269
  
270
    public static Vector getOptionList(String optiontext)
271
    {
272
        Vector optionsVector = new Vector();
273
        if (optiontext.indexOf(",") == -1) {
274
            optionsVector.addElement(optiontext);
275
            return optionsVector;
276
        }
277

    
278
        while (optiontext.indexOf(",") != -1) {
279
            String s = optiontext.substring(0, optiontext.indexOf(","));
280
            optionsVector.addElement(s.trim());
281
            optiontext = optiontext.substring(optiontext.indexOf(",") + 1,
282
                    optiontext.length());
283
            if (optiontext.indexOf(",") == -1) { //catch the last list entry
284
                optionsVector.addElement(optiontext.trim());
285
            }
286
        }
287
        return optionsVector;
288
    }
289

    
290
    /** Normalizes the given string. Taken from configXML.java */
291
    public static String normalize(String s)
292
    {
293
        StringBuffer str = new StringBuffer();
294

    
295
             int len = (s != null) ? s.length() : 0;
296
             for (int i = 0; i < len; i++) {
297
                 char ch = s.charAt(i);
298
                 switch (ch) {
299
                     case '<': {
300
                         str.append("&lt;");
301
                         break;
302
                     }
303
                     case '>': {
304
                         str.append("&gt;");
305
                         break;
306
                     }
307
                     case '&': {
308
                         /*
309
                          * patch provided by Johnoel Ancheta from U of Hawaii
310
                          */
311
                         // check if & is for a character reference &#xnnnn;
312
                         if (i + 1 < len - 1 && s.charAt(i + 1) == '#') {
313
                             str.append("&#");
314
                             i += 2;
315

    
316
                             ch = s.charAt(i);
317
                             while (i < len && ch != ';') {
318
                                 str.append(ch);
319
                                 i++;
320
                                 ch = s.charAt(i);
321
                             }
322
                             str.append(';');
323
                         } else 
324
                         // check if & is in front of amp; 
325
                         // (we dont yet check for other HTML 4.0 Character entities) 
326
                         if (i + 4 < len -1 && s.charAt(i + 1) == 'a' 
327
                        	 && s.charAt(i + 2) == 'm' 
328
                        		 && s.charAt(i + 3) == 'p' 
329
                        			 && s.charAt(i + 4) == ';'){
330
                             str.append("&amp;");
331
                             i += 5;                        	 
332
                         } else
333
                             str.append("&amp;");
334
                         /////////
335
                         break;
336
                     }
337
                    default: {
338
                         if ( (ch<128) && (ch>31) ) {
339
                             str.append(ch);
340
                         }
341
                         else if (ch<32) {
342
                             if (ch == 10) { // new line
343
                                 str.append(ch);
344
                             }
345
                             if (ch == 13) { // carriage return
346
                                 str.append(ch);
347
                             }
348
                             if (ch == 9) {  // tab
349
                                 str.append(ch);
350
                             }
351
                             // otherwise skip
352
                         }
353
                         else {
354
                             str.append("&#");
355
                             str.append(Integer.toString(ch));
356
                             str.append(';');
357
                         }
358
                     }
359
                 }
360
             }
361
             return str.toString();
362
    }
363

    
364
    /**
365
     * Get docid from online/url string
366
     */
367
    public static String getDocIdWithRevFromOnlineURL(String url)
368
    {
369
        String docid = null;
370
        String DOCID = "docid";
371
        boolean find = false;
372
        char limited = '&';
373
        int count = 0; //keep track how many & was found
374
        Vector list = new Vector();// keep index number for &
375
        if (url == null) {
376
            logMetacat.info("url is null and null will be returned");
377
            return docid;
378
        }
379
        // the first element in list is 0
380
        list.add(new Integer(0));
381
        for (int i = 0; i < url.length(); i++) {
382
            if (url.charAt(i) == limited) {
383
                // count plus 1
384
                count++;
385
                list.add(new Integer(i));
386
                // get substring beween two &
387
                String str = url.substring(
388
                        ((Integer) list.elementAt(count - 1)).intValue(), i);
389
                logMetacat.info("substring between two & is: " + str);
390
                //if the subString contains docid, we got it
391
                if (str.indexOf(DOCID) != -1) {
392
                    //get index of '="
393
                    int start = getIndexForGivenChar(str, '=') + 1;
394
                    int end = str.length();
395
                    docid = str.substring(start, end);
396
                    find = true;
397
                }//if
398
            }//if
399
        }//for
400
        //if not find, we need check the subtring between the index of last &
401
        // and
402
        // the end of string
403
        if (!find) {
404
            logMetacat.info("Checking the last substring");
405
            String str = url.substring(((Integer) list.elementAt(count))
406
                    .intValue() + 1, url.length());
407
            logMetacat.info("Last substring is: " + str);
408
            if (str.indexOf(DOCID) != -1) {
409
                //get index of '="
410
                int start = getIndexForGivenChar(str, '=') + 1;
411
                int end = str.length();
412
                docid = str.substring(start, end);
413
                find = true;
414
            }//if
415
        }//if
416
        logMetacat.info("The docid from online url is:" + docid);
417
        return docid.trim();
418
    }
419

    
420

    
421
    /**
422
     * Eocgorid identifier will look like: ecogrid://knb/tao.1.1
423
     * The AccessionNumber tao.1.1 will be returned. If the given doesn't
424
     * contains ecogrid, null will be returned.
425
     * @param identifier String
426
     * @return String
427
     */
428
    public static String getAccessionNumberFromEcogridIdentifier(String identifier)
429
    {
430
      String accessionNumber = null;
431
      if (identifier != null && identifier.startsWith(DBSAXHandler.ECOGRID))
432
      {
433
        // find the last "/" in identifier
434
        int indexOfLastSlash = identifier.lastIndexOf("/");
435
        int start = indexOfLastSlash+1;
436
        int end   = identifier.length();
437
        accessionNumber = identifier.substring(start, end);
438
      }
439
      logMetacat.warn("The accession number from url is " +
440
                                 accessionNumber);
441
      return accessionNumber;
442
    }
443

    
444
    private static int getIndexForGivenChar(String str, char character)
445
    {
446
        int index = -1;
447
        // make sure str is not null
448
        if (str == null) {
449
            logMetacat.info(
450
                    "The given str is null and -1 will be returned");
451
            return index;
452
        }
453
        // got though the string
454
        for (int i = 0; i < str.length(); i++) {
455
            // find the first one then break the loop
456
            if (str.charAt(i) == character) {
457
                index = i;
458
                break;
459
            }//if
460
        }//for
461
        logMetacat.info("the index for char " + character + " is: "
462
                + index);
463
        return index;
464
    }
465

    
466
    /**
467
     * Utility method to get docid from a given string
468
     *
469
     * @param string, the given string should be these two format: 1) str1.str2
470
     *            in this case docid= str1.str2 2) str1.str2.str3, in this case
471
     *            docid =str1.str2
472
     * @param the sperator char
473
     */
474
    public static String getDocIdFromString(String str)
475
    {
476
        String docId = null;
477
        if (str == null) {
478
            logMetacat.info(
479
                    "The given str is null and null will be returned"
480
                            + " in getDocIdfromString");
481
            return docId;
482
        } //make sure docid is not null
483
        int dotNumber = 0;//count how many dots in given string
484
        int indexOfLastDot = 0;
485

    
486
        //assume that seperator is one charactor string
487
        char seperator = getOption("accNumSeparator").charAt(0);
488

    
489
        for (int i = 0; i < str.length(); i++) {
490
            if (str.charAt(i) == seperator) {
491
                dotNumber++;//count how many dots
492
                indexOfLastDot = i;//keep the last dot postion
493
            }
494
        }//for
495

    
496
        //The string formatt is wrong, because it has more than two or less
497
        // than
498
        //one seperator
499
        if (dotNumber > 2 || dotNumber < 1) {
500
            docId = null;
501
        } else if (dotNumber == 2) //the case for str1.str2.str3
502
        {
503
            docId = str.substring(0, indexOfLastDot);
504
        } else if (dotNumber == 1) //the case for str1.str2
505
        {
506
            docId = str;
507
        }
508

    
509
        return docId;
510
    }//getDocIdFromString
511

    
512
    /**
513
     * Utility method to get version number from a given string
514
     *
515
     * @param string, the given string should be these two format: 1)
516
     *            str1.str2(no version) version =-1; 2) str1.str2.str3, in this
517
     *            case version = str3; 3) other, vresion =-2
518
     */
519
    public static int getVersionFromString(String str)
520
            throws NumberFormatException
521
    {
522
        int version = -1;
523
        String versionString = null;
524
        int dotNumber = 0;//count how many dots in given string
525
        int indexOfLastDot = 0;
526

    
527
        //assume that seperator is one charactor string
528
        char seperator = getOption("accNumSeparator").charAt(0);
529

    
530
        for (int i = 0; i < str.length(); i++) {
531
            if (str.charAt(i) == seperator) {
532
                dotNumber++;//count how many dots
533
                indexOfLastDot = i;//keep the last dot postion
534
            }
535
        }//for
536

    
537
        //The string formatt is wrong, because it has more than two or less
538
        // than
539
        //one seperator
540
        if (dotNumber > 2 || dotNumber < 1) {
541
            version = -2;
542
        } else if (dotNumber == 2 && (indexOfLastDot != (str.length() - 1)))
543
        //the case for str1.str2.str3
544
        {
545
            versionString = str.substring((indexOfLastDot + 1), str.length());
546
            version = Integer.parseInt(versionString);
547
        } else if (dotNumber == 1) //the case for str1.str2
548
        {
549
            version = -1;
550
        }
551

    
552
        return version;
553
    }//getVersionFromString
554

    
555
    /**
556
     * Utility method to get version string from a given string
557
     *
558
     * @param string, the given string should be these two format: 1)
559
     *            str1.str2(no version) version=null; 2) str1.str2.str3, in
560
     *            this case version = str3; 3) other, vresion =null;
561
     */
562
    public static String getRevisionStringFromString(String str)
563
            throws NumberFormatException
564
    {
565
        // String to store the version
566
        String versionString = null;
567
        int dotNumber = 0;//count how many dots in given string
568
        int indexOfLastDot = 0;
569

    
570
        //assume that seperator is one charactor string
571
        char seperator = getOption("accNumSeparator").charAt(0);
572

    
573
        for (int i = 0; i < str.length(); i++) {
574
            if (str.charAt(i) == seperator) {
575
                dotNumber++;//count how many dots
576
                indexOfLastDot = i;//keep the last dot postion
577
            }
578
        }//for
579

    
580
        //The string formatt is wrong, because it has more than two or less
581
        // than
582
        //one seperator
583
        if (dotNumber > 2 || dotNumber < 1) {
584
            versionString = null;
585
        } else if (dotNumber == 2 && (indexOfLastDot != (str.length() - 1))) {
586
            //the case for str1.str2.str3
587
            // indexOfLastDot != (str.length() -1) means get rid of str1.str2.
588
            versionString = str.substring((indexOfLastDot + 1), str.length());
589
        } else if (dotNumber == 1) //the case for str1.str2 or str1.str2.
590
        {
591
            versionString = null;
592
        }
593

    
594
        return versionString;
595
    }//getVersionFromString
596

    
597
    /**
598
     * This method will get docid from an AccessionNumber. There is no
599
     * assumption the accessnumber will be str1.str2.str3. It can be more. So
600
     * we think the docid will be get rid of last part
601
     */
602
    public static String getDocIdFromAccessionNumber(String accessionNumber)
603
    {
604
        String docid = null;
605
        if (accessionNumber == null) { return docid; }
606
        String seperator = getOption("accNumSeparator");
607
        int indexOfLastSeperator = accessionNumber.lastIndexOf(seperator);
608
        docid = accessionNumber.substring(0, indexOfLastSeperator);
609
        logMetacat.info("after parsing accessionnumber, docid is "
610
                + docid);
611
        return docid;
612
    }
613

    
614
    /**
615
     * This method will get inline data id without the revision number.
616
     * So if inlineData.1.2 is passed as input, inlineData.2 is returned.
617
     */
618
    public static String getInlineDataIdWithoutRev(String accessionNumber)
619
    {
620
        String docid = null;
621
        if (accessionNumber == null) { return docid; }
622
        String seperator = getOption("accNumSeparator");
623
        int indexOfLastSeperator = accessionNumber.lastIndexOf(seperator);
624
        String version = accessionNumber.substring(indexOfLastSeperator,
625
                                                   accessionNumber.length());
626
        accessionNumber = accessionNumber.substring(0, indexOfLastSeperator);
627
        indexOfLastSeperator = accessionNumber.lastIndexOf(seperator);
628
        docid = accessionNumber.substring(0, indexOfLastSeperator) + version;
629
        logMetacat.info("after parsing accessionnumber, docid is "
630
                                 + docid);
631

    
632
        return docid;
633
    }
634

    
635
    /**
636
     * This method will call both getDocIdFromString and
637
     * getDocIdFromAccessionNumber. So first, if the string looks str1.str2,
638
     * the docid will be str1.str2. If the string is str1.str2.str3, the docid
639
     * will be str1.str2. If the string is str1.str2.str3.str4 or more, the
640
     * docid will be str1.str2.str3. If the string look like str1, null will be
641
     * returned
642
     *
643
     */
644
    public static String getSmartDocId(String str)
645
    {
646
        String docid = null;
647
        //call geDocIdFromString first.
648
        docid = getDocIdFromString(str);
649
        // If docid is null, try to call getDocIdFromAccessionNumber
650
        // it will handle the seperator more than2
651
        if (docid == null) {
652
            docid = getDocIdFromAccessionNumber(str);
653
        }
654
        logMetacat.info("The docid get from smart docid getor is "
655
                + docid);
656
        return docid;
657
    }
658

    
659
    /**
660
     * This method will get revision from an AccessionNumber. There is no
661
     * assumption the accessnumber will be str1.str2.str3. It can be more. So
662
     * we think the docid will be get rid of last part
663
     */
664
    public static int getRevisionFromAccessionNumber(String accessionNumber)
665
            throws NumberFormatException
666
    {
667
        String rev = null;
668
        int revNumber = -1;
669
        if (accessionNumber == null) { return revNumber; }
670
        String seperator = getOption("accNumSeparator");
671
        int indexOfLastSeperator = accessionNumber.lastIndexOf(seperator);
672
        rev = accessionNumber.substring(indexOfLastSeperator + 1,
673
                accessionNumber.length());
674
        revNumber = Integer.parseInt(rev);
675
        logMetacat.info("after parsing accessionnumber, rev is "
676
                + revNumber);
677
        return revNumber;
678
    }
679

    
680
    /**
681
     * Method to get the name of local replication server
682
     */
683
    public static String getLocalReplicationServerName()
684
    {
685
        String replicationServerName = null;
686
        String serverHost = null;
687
        serverHost = getOption("server");
688
        // append "context/servelet/replication" to the host name
689
        replicationServerName = serverHost.trim() + getOption("replicationpath").trim();
690
        return replicationServerName;
691

    
692
    }
693

    
694
    /**
695
     * Method to get docidwithrev from eml2 inline data id The eml inline data
696
     * id would look like eml.200.2.3
697
     */
698
    public static String getDocIdWithoutRevFromInlineDataID(String inlineDataID)
699
    {
700
        String docidWithoutRev = null;
701
        if (inlineDataID == null) { return docidWithoutRev; }
702
        String seperator = MetaCatUtil.getOption("accNumSeparator");
703
        char charSeperator = seperator.charAt(0);
704
        int targetNumberOfSeperator = 2;// we want to know his index
705
        int numberOfSeperator = 0;
706
        for (int i = 0; i < inlineDataID.length(); i++) {
707
            // meet seperator, increase number of seperator
708
            if (inlineDataID.charAt(i) == charSeperator) {
709
                numberOfSeperator++;
710
            }
711
            // if number of seperator reach the target one, record the index(i)
712
            // and get substring and terminate the loop
713
            if (numberOfSeperator == targetNumberOfSeperator) {
714
                docidWithoutRev = inlineDataID.substring(0, i);
715
                break;
716
            }
717
        }
718

    
719
        logMetacat.info("Docid without rev from inlinedata id: "
720
                + docidWithoutRev);
721
        return docidWithoutRev;
722

    
723
    }
724

    
725
    /**
726
     * Revise stack change a stack to opposite order
727
     */
728
    public static Stack reviseStack(Stack stack)
729
    {
730
        Stack result = new Stack();
731
        // make sure the parameter is correct
732
        if (stack == null || stack.isEmpty()) {
733
            result = stack;
734
            return result;
735
        }
736

    
737
        while (!stack.isEmpty()) {
738
            Object obj = stack.pop();
739
            result.push(obj);
740
        }
741
        return result;
742
    }
743

    
744
    /** A method to replace whitespace in url */
745
    public static String replaceWhiteSpaceForURL(String urlHasWhiteSpace)
746
    {
747
        StringBuffer newUrl = new StringBuffer();
748
        String whiteSpaceReplace = "%20";
749
        if (urlHasWhiteSpace == null || urlHasWhiteSpace.trim().equals("")) { return null; }
750

    
751
        for (int i = 0; i < urlHasWhiteSpace.length(); i++) {
752
            char ch = urlHasWhiteSpace.charAt(i);
753
            if (!Character.isWhitespace(ch)) {
754
                newUrl.append(ch);
755
            } else {
756
                //it is white sapce, replace it by %20
757
                newUrl = newUrl.append(whiteSpaceReplace);
758
            }
759

    
760
        }//for
761
        logMetacat.info("The new string without space is:"
762
                + newUrl.toString());
763
        return newUrl.toString();
764

    
765
    }// replaceWhiteSpaceForUR
766

    
767
    /** 
768
     * A method to read administrators and moderators list from the metacat.properties 
769
     **/
770
    public static void getUserAccessControlLists(){
771
    	administrators = getListFromOption("administrators");
772
    	moderators = getListFromOption("moderators");
773
    	allowedSubmitters = getListFromOption("allowedSubmitters");
774
    	deniedSubmitters = getListFromOption("deniedSubmitters");
775
    }
776

    
777
    /** 
778
     * A method to read value of a given option from the metacat.properties 
779
     * into specified String array
780
     **/
781
    private static String[] getListFromOption(String optionName){
782
    	String[] list = null;
783
    	String listString = MetaCatUtil.getOption(optionName);
784
      
785
        try {
786
            if ( listString != null && !listString.trim().equals("")) {
787
            	list = listString.split(":");
788
            } else {
789
            	list = null;
790
            }
791
            
792
        } catch (PatternSyntaxException pse) {
793
        	list = null;
794
            logMetacat.error("Error in MetacatServlet.init: "
795
                + pse.getMessage());
796
        }
797
        return list;
798
    }
799
    
800
    /** 
801
     * A method to check if the specified user is part of the moderators list 
802
     **/
803
    private static boolean onList(String list[], String username, String[] groups){
804

    
805
    	if(list == null){
806
    		return false;
807
    	}
808

    
809
    	// Check that the user is authenticated as an administrator account
810
        for (int i = 0; i < list.length; i++) {
811
            // check the given admin dn is a group dn...
812
        	if(groups != null && list[i].startsWith("cn=")){
813
            	// is a group dn
814
        		for (int j = 0; j < groups.length; j++) {
815
        			if (groups[j].equals(list[i])) {
816
                		return true;
817
                	}	
818
        		}   		
819
            } else { 
820
            	// is a user dn
821
            	if (username != null && username.equals(list[i])) {
822
    	    		return true;
823
            	}	
824
            }
825
        }
826
        return false;
827
    }
828

    
829
    /** 
830
     * A method to check if the specified user is part of the administrators list 
831
     **/
832
    public static boolean isAdministrator(String username, String[] groups){
833
    	return (onList(administrators, username, groups));
834
    }
835
    
836
    /** 
837
     * A method to check if the specified user is part of the moderators list 
838
     **/
839
    public static boolean isModerator(String username, String[] groups){
840
    	return (onList(moderators, username, groups));
841
    }
842

    
843
    /** 
844
     * A method to check if the specified user is part of the moderators list 
845
     **/
846
    public static boolean isAllowedSubmitter(String username, String[] groups){
847
    	if(allowedSubmitters != null){
848
    		return (onList(allowedSubmitters, username, groups));
849
    	} else {
850
    		// no allowedSubmitters list specified - 
851
    		// hence everyone should be allowed
852
    		return true;
853
    	}
854
   }
855

    
856
    /** 
857
     * A method to check if the specified user is part of the moderators list 
858
     **/
859
    public static boolean isDeniedSubmitter(String username, String[] groups){
860
		return (onList(deniedSubmitters, username, groups));
861
    }
862
    
863
    /** 
864
     * A method to check if the specified user can insert the document 
865
     **/
866
    public static boolean canInsertOrUpdate(String username, String[] groups){
867
    	return (isAllowedSubmitter(username, groups) 
868
    			&& !isDeniedSubmitter(username, groups));
869
    }
870
}
(45-45/65)