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
 *
8
 *   '$Author: tao $'
9
 *     '$Date: 2007-01-18 17:03:26 -0800 (Thu, 18 Jan 2007) $'
10
 * '$Revision: 3150 $'
11
 *
12
 * This program is free software; you can redistribute it and/or modify
13
 * it under the terms of the GNU General Public License as published by
14
 * the Free Software Foundation; either version 2 of the License, or
15
 * (at your option) any later version.
16
 *
17
 * This program is distributed in the hope that it will be useful,
18
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20
 * GNU General Public License for more details.
21
 *
22
 * You should have received a copy of the GNU General Public License
23
 * along with this program; if not, write to the Free Software
24
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
25
 */
26

    
27
package edu.ucsb.nceas.metacat;
28

    
29
import java.io.File;
30
import java.net.MalformedURLException;
31
import java.net.URL;
32
import java.util.HashMap;
33
import java.util.Hashtable;
34
import java.util.Stack;
35
import java.util.Vector;
36
import java.util.regex.PatternSyntaxException;
37

    
38
import org.apache.log4j.Logger;
39

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

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

    
49
    public static AbstractDatabase dbAdapter;
50

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

    
55
    private static edu.ucsb.nceas.utilities.Options options = null;
56

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

    
63
    private static String[] allowedSubmitters;
64

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

    
69
    static {
70
    	// Determine our db adapter class and create an instance of that class
71
        try {
72
            dbAdapter = (AbstractDatabase) createObject(getOption("dbAdapter"));
73
        } catch (Exception e) {
74
            System.err.println("Error in MetaCatUtil static block:"
75
                    + e.getMessage());
76
            e.printStackTrace();
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 = edu.ucsb.nceas.utilities.Options.getInstance();
115
        }
116
        if (options == null) {
117
            Logger logMetacat = Logger.getLogger(MetaCatUtil.class);
118
        	logMetacat.info("options is null");
119
        }
120
        String value = options.getOption(optionName);
121
        return value;
122
    }
123
    
124
    /**
125
     * Utility method to set an option value from the properties file
126
     *
127
     * @param optionName the name of the option requested
128
     */
129
    public static void setOption(String optionName, String newValue)
130
    {
131
        if (options == null) {
132
            options = edu.ucsb.nceas.utilities.Options.getInstance();
133
        }
134
        options.setOption(optionName, newValue);
135
        
136
    }
137

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

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

    
169
        String temp = "";
170
        boolean ampflag = true;
171
        boolean poundflag = false;
172
        int arrcount = 0;
173

    
174
        if (query != null) {
175
            for (int i = 0; i < query.length(); i++) {
176

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

    
205
                    if (!ampflag && poundflag) {
206
                        params[arrcount][1] = temp.trim();
207
                        parameters
208
                                .put(params[arrcount][0], params[arrcount][1]);
209
                        temp = "";
210
                        arrcount++; //increment the array to the next row.
211
                    } else {
212
                        //if there are two =s or &s in a row through an
213
                        // exception
214
                        throw new MalformedURLException(
215
                                "metacatURL: Two parameter values "
216
                                        + "not allowed in sequence");
217
                    }
218
                    poundflag = false;
219
                    ampflag = true;
220
                } else {
221
                    //get the next character in the string
222
                    temp += query.charAt(i);
223
                }
224
            }
225
        }
226
        return parameters;
227
    }
228
  
229
    public static Vector getOptionList(String optiontext)
230
    {
231
        Vector optionsVector = new Vector();
232
        if (optiontext.indexOf(",") == -1) {
233
            optionsVector.addElement(optiontext);
234
            return optionsVector;
235
        }
236

    
237
        while (optiontext.indexOf(",") != -1) {
238
            String s = optiontext.substring(0, optiontext.indexOf(","));
239
            optionsVector.addElement(s.trim());
240
            optiontext = optiontext.substring(optiontext.indexOf(",") + 1,
241
                    optiontext.length());
242
            if (optiontext.indexOf(",") == -1) { //catch the last list entry
243
                optionsVector.addElement(optiontext.trim());
244
            }
245
        }
246
        return optionsVector;
247
    }
248

    
249
    /** Normalizes the given string. Taken from configXML.java */
250
    public static String normalize(String s)
251
    {
252
        StringBuffer str = new StringBuffer();
253

    
254
             int len = (s != null) ? s.length() : 0;
255
             for (int i = 0; i < len; i++) {
256
                 char ch = s.charAt(i);
257
                 switch (ch) {
258
                     case '<': {
259
                         str.append("&lt;");
260
                         break;
261
                     }
262
                     case '>': {
263
                         str.append("&gt;");
264
                         break;
265
                     }
266
                     case '&': {
267
                         /*
268
                          * patch provided by Johnoel Ancheta from U of Hawaii
269
                          */
270
                         // check if & is for a character reference &#xnnnn;
271
                         if (i + 1 < len - 1 && s.charAt(i + 1) == '#') {
272
                             str.append("&#");
273
                             i += 2;
274

    
275
                             ch = s.charAt(i);
276
                             while (i < len && ch != ';') {
277
                                 str.append(ch);
278
                                 i++;
279
                                 ch = s.charAt(i);
280
                             }
281
                             str.append(';');
282
                         } else 
283
                         // check if & is in front of amp; 
284
                         // (we dont yet check for other HTML 4.0 Character entities) 
285
                         if (i + 4 < len -1 && s.charAt(i + 1) == 'a' 
286
                        	 && s.charAt(i + 2) == 'm' 
287
                        		 && s.charAt(i + 3) == 'p' 
288
                        			 && s.charAt(i + 4) == ';'){
289
                             str.append("&amp;");
290
                             i += 4;                        	 
291
                         } else
292
                             str.append("&amp;");
293
                         /////////
294
                         break;
295
                     }
296
                     case '"':
297
                    	 str.append("&quot;");
298
                         break;
299
                    default: {
300
                         if ( (ch<128) && (ch>31) ) {
301
                             str.append(ch);
302
                         }
303
                         else if (ch<32) {
304
                             if (ch == 10) { // new line
305
                                 str.append(ch);
306
                             }
307
                             if (ch == 13) { // carriage return
308
                                 str.append(ch);
309
                             }
310
                             if (ch == 9) {  // tab
311
                                 str.append(ch);
312
                             }
313
                             // otherwise skip
314
                         }
315
                         else {
316
                             str.append("&#");
317
                             str.append(Integer.toString(ch));
318
                             str.append(';');
319
                         }
320
                     }
321
                 }
322
             }
323
             return str.toString();
324
    }
325

    
326
    /**
327
     * Get docid from online/url string
328
     */
329
    public static String getDocIdWithRevFromOnlineURL(String url)
330
    {
331
        String docid = null;
332
        String DOCID = "docid";
333
        boolean find = false;
334
        char limited = '&';
335
        int count = 0; //keep track how many & was found
336
        Vector list = new Vector();// keep index number for &
337
        if (url == null) {
338
            logMetacat.info("url is null and null will be returned");
339
            return docid;
340
        }
341
        // the first element in list is 0
342
        list.add(new Integer(0));
343
        for (int i = 0; i < url.length(); i++) {
344
            if (url.charAt(i) == limited) {
345
                // count plus 1
346
                count++;
347
                list.add(new Integer(i));
348
                // get substring beween two &
349
                String str = url.substring(
350
                        ((Integer) list.elementAt(count - 1)).intValue(), i);
351
                logMetacat.info("substring between two & is: " + str);
352
                //if the subString contains docid, we got it
353
                if (str.indexOf(DOCID) != -1) {
354
                    //get index of '="
355
                    int start = getIndexForGivenChar(str, '=') + 1;
356
                    int end = str.length();
357
                    docid = str.substring(start, end);
358
                    find = true;
359
                }//if
360
            }//if
361
        }//for
362
        //if not find, we need check the subtring between the index of last &
363
        // and
364
        // the end of string
365
        if (!find) {
366
            logMetacat.info("Checking the last substring");
367
            String str = url.substring(((Integer) list.elementAt(count))
368
                    .intValue() + 1, url.length());
369
            logMetacat.info("Last substring is: " + str);
370
            if (str.indexOf(DOCID) != -1) {
371
                //get index of '="
372
                int start = getIndexForGivenChar(str, '=') + 1;
373
                int end = str.length();
374
                docid = str.substring(start, end);
375
                find = true;
376
            }//if
377
        }//if
378
        logMetacat.info("The docid from online url is:" + docid);
379
        return docid.trim();
380
    }
381

    
382

    
383
    /**
384
     * Eocgorid identifier will look like: ecogrid://knb/tao.1.1
385
     * The AccessionNumber tao.1.1 will be returned. If the given doesn't
386
     * contains ecogrid, null will be returned.
387
     * @param identifier String
388
     * @return String
389
     */
390
    public static String getAccessionNumberFromEcogridIdentifier(String identifier)
391
    {
392
      String accessionNumber = null;
393
      if (identifier != null && identifier.startsWith(DBSAXHandler.ECOGRID))
394
      {
395
        // find the last "/" in identifier
396
        int indexOfLastSlash = identifier.lastIndexOf("/");
397
        int start = indexOfLastSlash+1;
398
        int end   = identifier.length();
399
        accessionNumber = identifier.substring(start, end);
400
      }
401
      logMetacat.warn("The accession number from url is " +
402
                                 accessionNumber);
403
      return accessionNumber;
404
    }
405

    
406
    private static int getIndexForGivenChar(String str, char character)
407
    {
408
        int index = -1;
409
        // make sure str is not null
410
        if (str == null) {
411
            logMetacat.info(
412
                    "The given str is null and -1 will be returned");
413
            return index;
414
        }
415
        // got though the string
416
        for (int i = 0; i < str.length(); i++) {
417
            // find the first one then break the loop
418
            if (str.charAt(i) == character) {
419
                index = i;
420
                break;
421
            }//if
422
        }//for
423
        logMetacat.info("the index for char " + character + " is: "
424
                + index);
425
        return index;
426
    }
427

    
428
    /**
429
     * Utility method to get docid from a given string
430
     *
431
     * @param string, the given string should be these two format: 1) str1.str2
432
     *            in this case docid= str1.str2 2) str1.str2.str3, in this case
433
     *            docid =str1.str2
434
     * @param the sperator char
435
     */
436
    public static String getDocIdFromString(String str)
437
    {
438
        String docId = null;
439
        if (str == null) {
440
            logMetacat.info(
441
                    "The given str is null and null will be returned"
442
                            + " in getDocIdfromString");
443
            return docId;
444
        } //make sure docid is not null
445
        int dotNumber = 0;//count how many dots in given string
446
        int indexOfLastDot = 0;
447

    
448
        //assume that seperator is one charactor string
449
        char seperator = getOption("accNumSeparator").charAt(0);
450

    
451
        for (int i = 0; i < str.length(); i++) {
452
            if (str.charAt(i) == seperator) {
453
                dotNumber++;//count how many dots
454
                indexOfLastDot = i;//keep the last dot postion
455
            }
456
        }//for
457

    
458
        //The string formatt is wrong, because it has more than two or less
459
        // than
460
        //one seperator
461
        if (dotNumber > 2 || dotNumber < 1) {
462
            docId = null;
463
        } else if (dotNumber == 2) //the case for str1.str2.str3
464
        {
465
            docId = str.substring(0, indexOfLastDot);
466
        } else if (dotNumber == 1) //the case for str1.str2
467
        {
468
            docId = str;
469
        }
470

    
471
        return docId;
472
    }//getDocIdFromString
473

    
474
    /**
475
     * Utility method to get version number from a given string
476
     *
477
     * @param string, the given string should be these two format: 1)
478
     *            str1.str2(no version) version =-1; 2) str1.str2.str3, in this
479
     *            case version = str3; 3) other, vresion =-2
480
     */
481
    public static int getVersionFromString(String str)
482
            throws NumberFormatException
483
    {
484
        int version = -1;
485
        String versionString = null;
486
        int dotNumber = 0;//count how many dots in given string
487
        int indexOfLastDot = 0;
488

    
489
        //assume that seperator is one charactor string
490
        char seperator = getOption("accNumSeparator").charAt(0);
491

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

    
499
        //The string formatt is wrong, because it has more than two or less
500
        // than
501
        //one seperator
502
        if (dotNumber > 2 || dotNumber < 1) {
503
            version = -2;
504
        } else if (dotNumber == 2 && (indexOfLastDot != (str.length() - 1)))
505
        //the case for str1.str2.str3
506
        {
507
            versionString = str.substring((indexOfLastDot + 1), str.length());
508
            version = Integer.parseInt(versionString);
509
        } else if (dotNumber == 1) //the case for str1.str2
510
        {
511
            version = -1;
512
        }
513

    
514
        return version;
515
    }//getVersionFromString
516

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

    
532
        //assume that seperator is one charactor string
533
        char seperator = getOption("accNumSeparator").charAt(0);
534

    
535
        for (int i = 0; i < str.length(); i++) {
536
            if (str.charAt(i) == seperator) {
537
                dotNumber++;//count how many dots
538
                indexOfLastDot = i;//keep the last dot postion
539
            }
540
        }//for
541

    
542
        //The string formatt is wrong, because it has more than two or less
543
        // than
544
        //one seperator
545
        if (dotNumber > 2 || dotNumber < 1) {
546
            versionString = null;
547
        } else if (dotNumber == 2 && (indexOfLastDot != (str.length() - 1))) {
548
            //the case for str1.str2.str3
549
            // indexOfLastDot != (str.length() -1) means get rid of str1.str2.
550
            versionString = str.substring((indexOfLastDot + 1), str.length());
551
        } else if (dotNumber == 1) //the case for str1.str2 or str1.str2.
552
        {
553
            versionString = null;
554
        }
555

    
556
        return versionString;
557
    }//getVersionFromString
558

    
559
    /**
560
     * This method will get docid from an AccessionNumber. There is no
561
     * assumption the accessnumber will be str1.str2.str3. It can be more. So
562
     * we think the docid will be get rid of last part
563
     */
564
    public static String getDocIdFromAccessionNumber(String accessionNumber)
565
    {
566
        String docid = null;
567
        if (accessionNumber == null) { return docid; }
568
        String seperator = getOption("accNumSeparator");
569
        int indexOfLastSeperator = accessionNumber.lastIndexOf(seperator);
570
        docid = accessionNumber.substring(0, indexOfLastSeperator);
571
        logMetacat.info("after parsing accessionnumber, docid is "
572
                + docid);
573
        return docid;
574
    }
575

    
576
    /**
577
     * This method will get inline data id without the revision number.
578
     * So if inlineData.1.2 is passed as input, inlineData.2 is returned.
579
     */
580
    public static String getInlineDataIdWithoutRev(String accessionNumber)
581
    {
582
        String docid = null;
583
        if (accessionNumber == null) { return docid; }
584
        String seperator = getOption("accNumSeparator");
585
        int indexOfLastSeperator = accessionNumber.lastIndexOf(seperator);
586
        String version = accessionNumber.substring(indexOfLastSeperator,
587
                                                   accessionNumber.length());
588
        accessionNumber = accessionNumber.substring(0, indexOfLastSeperator);
589
        indexOfLastSeperator = accessionNumber.lastIndexOf(seperator);
590
        docid = accessionNumber.substring(0, indexOfLastSeperator) + version;
591
        logMetacat.info("after parsing accessionnumber, docid is "
592
                                 + docid);
593

    
594
        return docid;
595
    }
596

    
597
    /**
598
     * This method will call both getDocIdFromString and
599
     * getDocIdFromAccessionNumber. So first, if the string looks str1.str2,
600
     * the docid will be str1.str2. If the string is str1.str2.str3, the docid
601
     * will be str1.str2. If the string is str1.str2.str3.str4 or more, the
602
     * docid will be str1.str2.str3. If the string look like str1, null will be
603
     * returned
604
     *
605
     */
606
    public static String getSmartDocId(String str)
607
    {
608
        String docid = null;
609
        //call geDocIdFromString first.
610
        docid = getDocIdFromString(str);
611
        // If docid is null, try to call getDocIdFromAccessionNumber
612
        // it will handle the seperator more than2
613
        if (docid == null) {
614
            docid = getDocIdFromAccessionNumber(str);
615
        }
616
        logMetacat.info("The docid get from smart docid getor is "
617
                + docid);
618
        return docid;
619
    }
620

    
621
    /**
622
     * This method will get revision from an AccessionNumber. There is no
623
     * assumption the accessnumber will be str1.str2.str3. It can be more. So
624
     * we think the docid will be get rid of last part
625
     */
626
    public static int getRevisionFromAccessionNumber(String accessionNumber)
627
            throws NumberFormatException
628
    {
629
        String rev = null;
630
        int revNumber = -1;
631
        if (accessionNumber == null) { return revNumber; }
632
        String seperator = getOption("accNumSeparator");
633
        int indexOfLastSeperator = accessionNumber.lastIndexOf(seperator);
634
        rev = accessionNumber.substring(indexOfLastSeperator + 1,
635
                accessionNumber.length());
636
        revNumber = Integer.parseInt(rev);
637
        logMetacat.info("after parsing accessionnumber, rev is "
638
                + revNumber);
639
        return revNumber;
640
    }
641

    
642
    /**
643
     * Method to get the name of local replication server
644
     */
645
    public static String getLocalReplicationServerName()
646
    {
647
        String replicationServerName = null;
648
        String serverHost = null;
649
        serverHost = getOption("server");
650
        // append "context/servelet/replication" to the host name
651
        replicationServerName = serverHost.trim() + getOption("replicationpath").trim();
652
        return replicationServerName;
653

    
654
    }
655

    
656
    /**
657
     * Method to get docidwithrev from eml2 inline data id The eml inline data
658
     * id would look like eml.200.2.3
659
     */
660
    public static String getDocIdWithoutRevFromInlineDataID(String inlineDataID)
661
    {
662
        String docidWithoutRev = null;
663
        if (inlineDataID == null) { return docidWithoutRev; }
664
        String seperator = MetaCatUtil.getOption("accNumSeparator");
665
        char charSeperator = seperator.charAt(0);
666
        int targetNumberOfSeperator = 2;// we want to know his index
667
        int numberOfSeperator = 0;
668
        for (int i = 0; i < inlineDataID.length(); i++) {
669
            // meet seperator, increase number of seperator
670
            if (inlineDataID.charAt(i) == charSeperator) {
671
                numberOfSeperator++;
672
            }
673
            // if number of seperator reach the target one, record the index(i)
674
            // and get substring and terminate the loop
675
            if (numberOfSeperator == targetNumberOfSeperator) {
676
                docidWithoutRev = inlineDataID.substring(0, i);
677
                break;
678
            }
679
        }
680

    
681
        logMetacat.info("Docid without rev from inlinedata id: "
682
                + docidWithoutRev);
683
        return docidWithoutRev;
684

    
685
    }
686

    
687
    /**
688
     * Revise stack change a stack to opposite order
689
     */
690
    public static Stack reviseStack(Stack stack)
691
    {
692
        Stack result = new Stack();
693
        // make sure the parameter is correct
694
        if (stack == null || stack.isEmpty()) {
695
            result = stack;
696
            return result;
697
        }
698

    
699
        while (!stack.isEmpty()) {
700
            Object obj = stack.pop();
701
            result.push(obj);
702
        }
703
        return result;
704
    }
705

    
706
    /** A method to replace whitespace in url */
707
    public static String replaceWhiteSpaceForURL(String urlHasWhiteSpace)
708
    {
709
        StringBuffer newUrl = new StringBuffer();
710
        String whiteSpaceReplace = "%20";
711
        if (urlHasWhiteSpace == null || urlHasWhiteSpace.trim().equals("")) { return null; }
712

    
713
        for (int i = 0; i < urlHasWhiteSpace.length(); i++) {
714
            char ch = urlHasWhiteSpace.charAt(i);
715
            if (!Character.isWhitespace(ch)) {
716
                newUrl.append(ch);
717
            } else {
718
                //it is white sapce, replace it by %20
719
                newUrl = newUrl.append(whiteSpaceReplace);
720
            }
721

    
722
        }//for
723
        logMetacat.info("The new string without space is:"
724
                + newUrl.toString());
725
        return newUrl.toString();
726

    
727
    }// replaceWhiteSpaceForUR
728

    
729
    /** 
730
     * A method to read administrators and moderators list from the metacat.properties 
731
     **/
732
    public static void getUserAccessControlLists(){
733
    	administrators = getListFromOption("administrators");
734
    	moderators = getListFromOption("moderators");
735
    	allowedSubmitters = getListFromOption("allowedSubmitters");
736
    	deniedSubmitters = getListFromOption("deniedSubmitters");
737
    }
738

    
739
    /** 
740
     * A method to read value of a given option from the metacat.properties 
741
     * into specified String array
742
     **/
743
    private static String[] getListFromOption(String optionName){
744
    	String[] list = null;
745
    	String listString = MetaCatUtil.getOption(optionName);
746
      
747
        try {
748
            if ( listString != null && !listString.trim().equals("")) {
749
            	list = listString.split(":");
750
            } else {
751
            	list = null;
752
            }
753
            
754
        } catch (PatternSyntaxException pse) {
755
        	list = null;
756
            logMetacat.error("Error in MetacatServlet.init: "
757
                + pse.getMessage());
758
        }
759
        return list;
760
    }
761
    
762
    /** 
763
     * A method to check if the specified user is part of the moderators list 
764
     **/
765
    private static boolean onList(String list[], String username, String[] groups){
766

    
767
    	if(list == null){
768
    		return false;
769
    	}
770

    
771
    	// Check that the user is authenticated as an administrator account
772
        for (int i = 0; i < list.length; i++) {
773
            // check the given admin dn is a group dn...
774
        	if(groups != null && list[i].startsWith("cn=")){
775
            	// is a group dn
776
        		for (int j = 0; j < groups.length; j++) {
777
        			if (groups[j].equals(list[i])) {
778
                		return true;
779
                	}	
780
        		}   		
781
            } else { 
782
            	// is a user dn
783
            	if (username != null && username.equals(list[i])) {
784
    	    		return true;
785
            	}	
786
            }
787
        }
788
        return false;
789
    }
790

    
791
    /** 
792
     * A method to check if the specified user is part of the administrators list 
793
     **/
794
    public static boolean isAdministrator(String username, String[] groups){
795
    	return (onList(administrators, username, groups));
796
    }
797
    
798
    /** 
799
     * A method to check if the specified user is part of the moderators list 
800
     **/
801
    public static boolean isModerator(String username, String[] groups){
802
    	return (onList(moderators, username, groups));
803
    }
804

    
805
    /** 
806
     * A method to check if the specified user is part of the moderators list 
807
     **/
808
    public static boolean isAllowedSubmitter(String username, String[] groups){
809
    	if(allowedSubmitters != null){
810
    		return (onList(allowedSubmitters, username, groups));
811
    	} else {
812
    		// no allowedSubmitters list specified - 
813
    		// hence everyone should be allowed
814
    		return true;
815
    	}
816
   }
817

    
818
    /** 
819
     * A method to check if the specified user is part of the moderators list 
820
     **/
821
    public static boolean isDeniedSubmitter(String username, String[] groups){
822
		return (onList(deniedSubmitters, username, groups));
823
    }
824
    
825
    /** 
826
     * A method to check if the specified user can insert the document 
827
     **/
828
    public static boolean canInsertOrUpdate(String username, String[] groups){
829
    	return (isAllowedSubmitter(username, groups) 
830
    			&& !isDeniedSubmitter(username, groups));
831
    }
832
}
(45-45/66)