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: jones $'
9
 *     '$Date: 2006-11-10 10:51:31 -0800 (Fri, 10 Nov 2006) $'
10
 * '$Revision: 3078 $'
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
                    default: {
297
                         if ( (ch<128) && (ch>31) ) {
298
                             str.append(ch);
299
                         }
300
                         else if (ch<32) {
301
                             if (ch == 10) { // new line
302
                                 str.append(ch);
303
                             }
304
                             if (ch == 13) { // carriage return
305
                                 str.append(ch);
306
                             }
307
                             if (ch == 9) {  // tab
308
                                 str.append(ch);
309
                             }
310
                             // otherwise skip
311
                         }
312
                         else {
313
                             str.append("&#");
314
                             str.append(Integer.toString(ch));
315
                             str.append(';');
316
                         }
317
                     }
318
                 }
319
             }
320
             return str.toString();
321
    }
322

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

    
379

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

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

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

    
445
        //assume that seperator is one charactor string
446
        char seperator = getOption("accNumSeparator").charAt(0);
447

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

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

    
468
        return docId;
469
    }//getDocIdFromString
470

    
471
    /**
472
     * Utility method to get version number from a given string
473
     *
474
     * @param string, the given string should be these two format: 1)
475
     *            str1.str2(no version) version =-1; 2) str1.str2.str3, in this
476
     *            case version = str3; 3) other, vresion =-2
477
     */
478
    public static int getVersionFromString(String str)
479
            throws NumberFormatException
480
    {
481
        int version = -1;
482
        String versionString = 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
            version = -2;
501
        } else if (dotNumber == 2 && (indexOfLastDot != (str.length() - 1)))
502
        //the case for str1.str2.str3
503
        {
504
            versionString = str.substring((indexOfLastDot + 1), str.length());
505
            version = Integer.parseInt(versionString);
506
        } else if (dotNumber == 1) //the case for str1.str2
507
        {
508
            version = -1;
509
        }
510

    
511
        return version;
512
    }//getVersionFromString
513

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

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

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

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

    
553
        return versionString;
554
    }//getVersionFromString
555

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

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

    
591
        return docid;
592
    }
593

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

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

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

    
651
    }
652

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

    
678
        logMetacat.info("Docid without rev from inlinedata id: "
679
                + docidWithoutRev);
680
        return docidWithoutRev;
681

    
682
    }
683

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

    
696
        while (!stack.isEmpty()) {
697
            Object obj = stack.pop();
698
            result.push(obj);
699
        }
700
        return result;
701
    }
702

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

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

    
719
        }//for
720
        logMetacat.info("The new string without space is:"
721
                + newUrl.toString());
722
        return newUrl.toString();
723

    
724
    }// replaceWhiteSpaceForUR
725

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

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

    
764
    	if(list == null){
765
    		return false;
766
    	}
767

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

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

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

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