Project

General

Profile

1
/**
2
 *  '$RCSfile$'
3
 *    Purpose: A Class that implements utility methods for a metadata catalog
4
 *  Copyright: 2000 Regents of the University of California and the
5
 *             National Center for Ecological Analysis and Synthesis
6
 *    Authors: Matt Jones, Jivka Bojilova
7
 *    Release: @release@
8
 *
9
 *   '$Author: sgarg $'
10
 *     '$Date: 2005-09-14 10:50:27 -0700 (Wed, 14 Sep 2005) $'
11
 * '$Revision: 2591 $'
12
 *
13
 * This program is free software; you can redistribute it and/or modify
14
 * it under the terms of the GNU General Public License as published by
15
 * the Free Software Foundation; either version 2 of the License, or
16
 * (at your option) any later version.
17
 *
18
 * This program is distributed in the hope that it will be useful,
19
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21
 * GNU General Public License for more details.
22
 *
23
 * You should have received a copy of the GNU General Public License
24
 * along with this program; if not, write to the Free Software
25
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
26
 */
27

    
28
package edu.ucsb.nceas.metacat;
29

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

    
38
import org.apache.log4j.Logger;
39
import org.apache.log4j.PropertyConfigurator;
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
    private static Options options = null;
55

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

    
62
    private static String[] allowedSubmitters;
63

    
64
    private static String[] deniedSubmitters;
65

    
66
    public static Logger logMetacat = null;
67
        
68
    static {
69

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

    
81
        // read administrator and moderator lists from metacat.properties
82
        getUserAccessControlLists();
83
    }
84

    
85
    /**
86
     * Instantiate a class using the name of the class at runtime
87
     *
88
     * @param className the fully qualified name of the class to instantiate
89
     */
90
    public static Object createObject(String className) throws Exception
91
    {
92

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

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

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

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

    
172
        String temp = "";
173
        boolean ampflag = true;
174
        boolean poundflag = false;
175
        int arrcount = 0;
176

    
177
        if (query != null) {
178
            for (int i = 0; i < query.length(); i++) {
179

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

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

    
232
    /**
233
     * Utility method to print debugging messages. User can set debug level for
234
     * this message. The number is fewer, the message is more important
235
     *
236
     * @param msg, the content of the message
237
     * @param debugLevel, an integer indicating the message debug leve
238
     */
239
    public static void debugMessage(String msg, int debugLevel)
240
    {
241
        if (debug) {
242
            int limit = 1;
243
            try {
244
                limit = Integer.parseInt(getOption("debuglevel"));
245

    
246
            } catch (Exception e) {
247
                System.out.println(e.getMessage());
248
            }
249
            //don't allow the user set debugLevel less than or equals 0
250
            if (debugLevel <= 0) {
251
                debugLevel = 1;
252
            }
253

    
254
            if (debugLevel < limit) {
255
                System.err.println("@debugprefix@ " + msg);
256
            }
257
        }
258
    }
259

    
260

    
261
    /**
262
     * Utility method to print debugging messages. User can set debug level for
263
     * this message. The number is fewer, the message is more important. Can be
264
     * used to control if the carriage return and debugPrefix are printed
265
     *
266
     * @param msg, the content of the message
267
     * @param debugLevel, an integer indicating the message debug level
268
     * @param debugPrefix, a boolean indicating whether debugprefix
269
     *                    should be printed or not
270
     */
271
    public static void formattedDebugMessage(String msg, int debugLevel,
272
                                      boolean carriageReturn,
273
                                      boolean debugPrefix)
274
    {
275
        if (debug) {
276
            int limit = 1;
277
            try {
278
                limit = Integer.parseInt(getOption("debuglevel"));
279

    
280
            } catch (Exception e) {
281
                System.out.println(e.getMessage());
282
            }
283
            //don't allow the user set debugLevel less than or equals 0
284
            if (debugLevel <= 0) {
285
                debugLevel = 1;
286
            }
287

    
288
            if (debugLevel < limit) {
289
                if(debugPrefix) {
290
                    if(carriageReturn)
291
                        System.err.println("@debugprefix@ " + msg);
292
                    else
293
                        System.err.print("@debugprefix@ " + msg);
294
                } else {
295
                    if(carriageReturn)
296
                        System.err.println(msg);
297
                    else
298
                        System.err.print(msg);
299
                }
300
            }
301
        }
302
    }
303

    
304

    
305
    public static Vector getOptionList(String optiontext)
306
    {
307
        Vector optionsVector = new Vector();
308
        if (optiontext.indexOf(",") == -1) {
309
            optionsVector.addElement(optiontext);
310
            return optionsVector;
311
        }
312

    
313
        while (optiontext.indexOf(",") != -1) {
314
            String s = optiontext.substring(0, optiontext.indexOf(","));
315
            optionsVector.addElement(s.trim());
316
            optiontext = optiontext.substring(optiontext.indexOf(",") + 1,
317
                    optiontext.length());
318
            if (optiontext.indexOf(",") == -1) { //catch the last list entry
319
                optionsVector.addElement(optiontext.trim());
320
            }
321
        }
322
        return optionsVector;
323
    }
324

    
325
    /** Normalizes the given string. Taken from configXML.java */
326
    public static String normalize(String s)
327
    {
328
        StringBuffer str = new StringBuffer();
329

    
330
             int len = (s != null) ? s.length() : 0;
331
             for (int i = 0; i < len; i++) {
332
                 char ch = s.charAt(i);
333
                 switch (ch) {
334
                     case '<': {
335
                         str.append("&lt;");
336
                         break;
337
                     }
338
                     case '>': {
339
                         str.append("&gt;");
340
                         break;
341
                     }
342
                     case '&': {
343
                         /*
344
                          * patch provided by Johnoel Ancheta from U of Hawaii
345
                          */
346
                         // check if & is for a character reference &#xnnnn;
347
                         if (i + 1 < len - 1 && s.charAt(i + 1) == '#') {
348
                             str.append("&#");
349
                             i += 2;
350

    
351
                             ch = s.charAt(i);
352
                             while (i < len && ch != ';') {
353
                                 str.append(ch);
354
                                 i++;
355
                                 ch = s.charAt(i);
356
                             }
357
                             str.append(';');
358
                         } else 
359
                         // check if & is in front of amp; 
360
                         // (we dont yet check for other HTML 4.0 Character entities) 
361
                         if (i + 4 < len -1 && s.charAt(i + 1) == 'a' 
362
                        	 && s.charAt(i + 2) == 'm' 
363
                        		 && s.charAt(i + 3) == 'p' 
364
                        			 && s.charAt(i + 4) == ';'){
365
                             str.append("&amp;");
366
                             i += 5;                        	 
367
                         } else
368
                             str.append("&amp;");
369
                         /////////
370
                         break;
371
                     }
372
                    default: {
373
                         if ( (ch<128) && (ch>31) ) {
374
                             str.append(ch);
375
                         }
376
                         else if (ch<32) {
377
                             if (ch == 10) { // new line
378
                                 str.append(ch);
379
                             }
380
                             if (ch == 13) { // carriage return
381
                                 str.append(ch);
382
                             }
383
                             if (ch == 9) {  // tab
384
                                 str.append(ch);
385
                             }
386
                             // otherwise skip
387
                         }
388
                         else {
389
                             str.append("&#");
390
                             str.append(Integer.toString(ch));
391
                             str.append(';');
392
                         }
393
                     }
394
                 }
395
             }
396
             return str.toString();
397
    }
398

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

    
457

    
458
    /**
459
     * Eocgorid identifier will look like: ecogrid://knb/tao.1.1
460
     * The AccessionNumber tao.1.1 will be returned. If the given doesn't
461
     * contains ecogrid, null will be returned.
462
     * @param identifier String
463
     * @return String
464
     */
465
    public static String getAccessionNumberFromEcogridIdentifier(String identifier)
466
    {
467
      String accessionNumber = null;
468
      if (identifier != null && identifier.startsWith(DBSAXHandler.ECOGRID))
469
      {
470
        // find the last "/" in identifier
471
        int indexOfLastSlash = identifier.lastIndexOf("/");
472
        int start = indexOfLastSlash+1;
473
        int end   = identifier.length();
474
        accessionNumber = identifier.substring(start, end);
475
      }
476
      MetaCatUtil.debugMessage("The accession number from url is " +
477
                                 accessionNumber, 10);
478
      return accessionNumber;
479
    }
480

    
481
    private static int getIndexForGivenChar(String str, char character)
482
    {
483
        int index = -1;
484
        // make sure str is not null
485
        if (str == null) {
486
            MetaCatUtil.debugMessage(
487
                    "The given str is null and -1 will be returned", 30);
488
            return index;
489
        }
490
        // got though the string
491
        for (int i = 0; i < str.length(); i++) {
492
            // find the first one then break the loop
493
            if (str.charAt(i) == character) {
494
                index = i;
495
                break;
496
            }//if
497
        }//for
498
        MetaCatUtil.debugMessage("the index for char " + character + " is: "
499
                + index, 30);
500
        return index;
501
    }
502

    
503
    /**
504
     * Utility method to get docid from a given string
505
     *
506
     * @param string, the given string should be these two format: 1) str1.str2
507
     *            in this case docid= str1.str2 2) str1.str2.str3, in this case
508
     *            docid =str1.str2
509
     * @param the sperator char
510
     */
511
    public static String getDocIdFromString(String str)
512
    {
513
        String docId = null;
514
        if (str == null) {
515
            MetaCatUtil.debugMessage(
516
                    "The given str is null and null will be returned"
517
                            + " in getDocIdfromString", 30);
518
            return docId;
519
        } //make sure docid is not null
520
        int dotNumber = 0;//count how many dots in given string
521
        int indexOfLastDot = 0;
522

    
523
        //assume that seperator is one charactor string
524
        char seperator = getOption("accNumSeparator").charAt(0);
525

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

    
533
        //The string formatt is wrong, because it has more than two or less
534
        // than
535
        //one seperator
536
        if (dotNumber > 2 || dotNumber < 1) {
537
            docId = null;
538
        } else if (dotNumber == 2) //the case for str1.str2.str3
539
        {
540
            docId = str.substring(0, indexOfLastDot);
541
        } else if (dotNumber == 1) //the case for str1.str2
542
        {
543
            docId = str;
544
        }
545

    
546
        return docId;
547
    }//getDocIdFromString
548

    
549
    /**
550
     * Utility method to get version number from a given string
551
     *
552
     * @param string, the given string should be these two format: 1)
553
     *            str1.str2(no version) version =-1; 2) str1.str2.str3, in this
554
     *            case version = str3; 3) other, vresion =-2
555
     */
556
    public static int getVersionFromString(String str)
557
            throws NumberFormatException
558
    {
559
        int version = -1;
560
        String versionString = null;
561
        int dotNumber = 0;//count how many dots in given string
562
        int indexOfLastDot = 0;
563

    
564
        //assume that seperator is one charactor string
565
        char seperator = getOption("accNumSeparator").charAt(0);
566

    
567
        for (int i = 0; i < str.length(); i++) {
568
            if (str.charAt(i) == seperator) {
569
                dotNumber++;//count how many dots
570
                indexOfLastDot = i;//keep the last dot postion
571
            }
572
        }//for
573

    
574
        //The string formatt is wrong, because it has more than two or less
575
        // than
576
        //one seperator
577
        if (dotNumber > 2 || dotNumber < 1) {
578
            version = -2;
579
        } else if (dotNumber == 2 && (indexOfLastDot != (str.length() - 1)))
580
        //the case for str1.str2.str3
581
        {
582
            versionString = str.substring((indexOfLastDot + 1), str.length());
583
            version = Integer.parseInt(versionString);
584
        } else if (dotNumber == 1) //the case for str1.str2
585
        {
586
            version = -1;
587
        }
588

    
589
        return version;
590
    }//getVersionFromString
591

    
592
    /**
593
     * Utility method to get version string from a given string
594
     *
595
     * @param string, the given string should be these two format: 1)
596
     *            str1.str2(no version) version=null; 2) str1.str2.str3, in
597
     *            this case version = str3; 3) other, vresion =null;
598
     */
599
    public static String getRevisionStringFromString(String str)
600
            throws NumberFormatException
601
    {
602
        // String to store the version
603
        String versionString = null;
604
        int dotNumber = 0;//count how many dots in given string
605
        int indexOfLastDot = 0;
606

    
607
        //assume that seperator is one charactor string
608
        char seperator = getOption("accNumSeparator").charAt(0);
609

    
610
        for (int i = 0; i < str.length(); i++) {
611
            if (str.charAt(i) == seperator) {
612
                dotNumber++;//count how many dots
613
                indexOfLastDot = i;//keep the last dot postion
614
            }
615
        }//for
616

    
617
        //The string formatt is wrong, because it has more than two or less
618
        // than
619
        //one seperator
620
        if (dotNumber > 2 || dotNumber < 1) {
621
            versionString = null;
622
        } else if (dotNumber == 2 && (indexOfLastDot != (str.length() - 1))) {
623
            //the case for str1.str2.str3
624
            // indexOfLastDot != (str.length() -1) means get rid of str1.str2.
625
            versionString = str.substring((indexOfLastDot + 1), str.length());
626
        } else if (dotNumber == 1) //the case for str1.str2 or str1.str2.
627
        {
628
            versionString = null;
629
        }
630

    
631
        return versionString;
632
    }//getVersionFromString
633

    
634
    /**
635
     * This method will get docid from an AccessionNumber. There is no
636
     * assumption the accessnumber will be str1.str2.str3. It can be more. So
637
     * we think the docid will be get rid of last part
638
     */
639
    public static String getDocIdFromAccessionNumber(String accessionNumber)
640
    {
641
        String docid = null;
642
        if (accessionNumber == null) { return docid; }
643
        String seperator = getOption("accNumSeparator");
644
        int indexOfLastSeperator = accessionNumber.lastIndexOf(seperator);
645
        docid = accessionNumber.substring(0, indexOfLastSeperator);
646
        MetaCatUtil.debugMessage("after parsing accessionnumber, docid is "
647
                + docid, 30);
648
        return docid;
649
    }
650

    
651
    /**
652
     * This method will get inline data id without the revision number.
653
     * So if inlineData.1.2 is passed as input, inlineData.2 is returned.
654
     */
655
    public static String getInlineDataIdWithoutRev(String accessionNumber)
656
    {
657
        String docid = null;
658
        if (accessionNumber == null) { return docid; }
659
        String seperator = getOption("accNumSeparator");
660
        int indexOfLastSeperator = accessionNumber.lastIndexOf(seperator);
661
        String version = accessionNumber.substring(indexOfLastSeperator,
662
                                                   accessionNumber.length());
663
        accessionNumber = accessionNumber.substring(0, indexOfLastSeperator);
664
        indexOfLastSeperator = accessionNumber.lastIndexOf(seperator);
665
        docid = accessionNumber.substring(0, indexOfLastSeperator) + version;
666
        MetaCatUtil.debugMessage("after parsing accessionnumber, docid is "
667
                                 + docid, 30);
668

    
669
        return docid;
670
    }
671

    
672
    /**
673
     * This method will call both getDocIdFromString and
674
     * getDocIdFromAccessionNumber. So first, if the string looks str1.str2,
675
     * the docid will be str1.str2. If the string is str1.str2.str3, the docid
676
     * will be str1.str2. If the string is str1.str2.str3.str4 or more, the
677
     * docid will be str1.str2.str3. If the string look like str1, null will be
678
     * returned
679
     *
680
     */
681
    public static String getSmartDocId(String str)
682
    {
683
        String docid = null;
684
        //call geDocIdFromString first.
685
        docid = getDocIdFromString(str);
686
        // If docid is null, try to call getDocIdFromAccessionNumber
687
        // it will handle the seperator more than2
688
        if (docid == null) {
689
            docid = getDocIdFromAccessionNumber(str);
690
        }
691
        MetaCatUtil.debugMessage("The docid get from smart docid getor is "
692
                + docid, 30);
693
        return docid;
694
    }
695

    
696
    /**
697
     * This method will get revision from an AccessionNumber. There is no
698
     * assumption the accessnumber will be str1.str2.str3. It can be more. So
699
     * we think the docid will be get rid of last part
700
     */
701
    public static int getRevisionFromAccessionNumber(String accessionNumber)
702
            throws NumberFormatException
703
    {
704
        String rev = null;
705
        int revNumber = -1;
706
        if (accessionNumber == null) { return revNumber; }
707
        String seperator = getOption("accNumSeparator");
708
        int indexOfLastSeperator = accessionNumber.lastIndexOf(seperator);
709
        rev = accessionNumber.substring(indexOfLastSeperator + 1,
710
                accessionNumber.length());
711
        revNumber = Integer.parseInt(rev);
712
        MetaCatUtil.debugMessage("after parsing accessionnumber, rev is "
713
                + revNumber, 30);
714
        return revNumber;
715
    }
716

    
717
    /**
718
     * Method to get the name of local replication server
719
     */
720
    public static String getLocalReplicationServerName()
721
    {
722
        String replicationServerName = null;
723
        String serverHost = null;
724
        serverHost = getOption("server");
725
        // append "context/servelet/replication" to the host name
726
        replicationServerName = serverHost.trim() + getOption("replicationpath").trim();
727
        return replicationServerName;
728

    
729
    }
730

    
731
    /**
732
     * Method to get docidwithrev from eml2 inline data id The eml inline data
733
     * id would look like eml.200.2.3
734
     */
735
    public static String getDocIdWithoutRevFromInlineDataID(String inlineDataID)
736
    {
737
        String docidWithoutRev = null;
738
        if (inlineDataID == null) { return docidWithoutRev; }
739
        String seperator = MetaCatUtil.getOption("accNumSeparator");
740
        char charSeperator = seperator.charAt(0);
741
        int targetNumberOfSeperator = 2;// we want to know his index
742
        int numberOfSeperator = 0;
743
        for (int i = 0; i < inlineDataID.length(); i++) {
744
            // meet seperator, increase number of seperator
745
            if (inlineDataID.charAt(i) == charSeperator) {
746
                numberOfSeperator++;
747
            }
748
            // if number of seperator reach the target one, record the index(i)
749
            // and get substring and terminate the loop
750
            if (numberOfSeperator == targetNumberOfSeperator) {
751
                docidWithoutRev = inlineDataID.substring(0, i);
752
                break;
753
            }
754
        }
755

    
756
        MetaCatUtil.debugMessage("Docid without rev from inlinedata id: "
757
                + docidWithoutRev, 35);
758
        return docidWithoutRev;
759

    
760
    }
761

    
762
    /**
763
     * Revise stack change a stack to opposite order
764
     */
765
    public static Stack reviseStack(Stack stack)
766
    {
767
        Stack result = new Stack();
768
        // make sure the parameter is correct
769
        if (stack == null || stack.isEmpty()) {
770
            result = stack;
771
            return result;
772
        }
773

    
774
        while (!stack.isEmpty()) {
775
            Object obj = stack.pop();
776
            result.push(obj);
777
        }
778
        return result;
779
    }
780

    
781
    /** A method to replace whitespace in url */
782
    public static String replaceWhiteSpaceForURL(String urlHasWhiteSpace)
783
    {
784
        StringBuffer newUrl = new StringBuffer();
785
        String whiteSpaceReplace = "%20";
786
        if (urlHasWhiteSpace == null || urlHasWhiteSpace.trim().equals("")) { return null; }
787

    
788
        for (int i = 0; i < urlHasWhiteSpace.length(); i++) {
789
            char ch = urlHasWhiteSpace.charAt(i);
790
            if (!Character.isWhitespace(ch)) {
791
                newUrl.append(ch);
792
            } else {
793
                //it is white sapce, replace it by %20
794
                newUrl = newUrl.append(whiteSpaceReplace);
795
            }
796

    
797
        }//for
798
        MetaCatUtil.debugMessage("The new string without space is:"
799
                + newUrl.toString(), 35);
800
        return newUrl.toString();
801

    
802
    }// replaceWhiteSpaceForUR
803

    
804
    /** 
805
     * A method to read administrators and moderators list from the metacat.properties 
806
     **/
807
    public static void getUserAccessControlLists(){
808
    	administrators = getListFromOption("administrators");
809
    	moderators = getListFromOption("moderators");
810
    	allowedSubmitters = getListFromOption("allowedSubmitters");
811
    	deniedSubmitters = getListFromOption("deniedSubmitters");
812
    }
813

    
814
    /** 
815
     * A method to read value of a given option from the metacat.properties 
816
     * into specified String array
817
     **/
818
    private static String[] getListFromOption(String optionName){
819
    	String[] list = null;
820
    	String listString = MetaCatUtil.getOption(optionName);
821
      
822
        try {
823
            if ( listString != null && !listString.trim().equals("")) {
824
            	list = listString.split(":");
825
            } else {
826
            	list = null;
827
            }
828
            
829
        } catch (PatternSyntaxException pse) {
830
        	list = null;
831
            MetaCatUtil.debugMessage("Error in MetacatServlet.init: "
832
                + pse.getMessage(), 20);
833
        }
834
        return list;
835
    }
836
    
837
    /** 
838
     * A method to check if the specified user is part of the moderators list 
839
     **/
840
    private static boolean onList(String list[], String username, String[] groups){
841

    
842
    	if(list == null){
843
    		return false;
844
    	}
845

    
846
    	// Check that the user is authenticated as an administrator account
847
        for (int i = 0; i < list.length; i++) {
848
            // check the given admin dn is a group dn...
849
        	if(groups != null && list[i].startsWith("cn=")){
850
            	// is a group dn
851
        		for (int j = 0; j < groups.length; j++) {
852
        			if (groups[j].equals(list[i])) {
853
                		return true;
854
                	}	
855
        		}   		
856
            } else { 
857
            	// is a user dn
858
            	if (username != null && username.equals(list[i])) {
859
    	    		return true;
860
            	}	
861
            }
862
        }
863
        return false;
864
    }
865

    
866
    /** 
867
     * A method to check if the specified user is part of the administrators list 
868
     **/
869
    public static boolean isAdministrator(String username, String[] groups){
870
    	return (onList(administrators, username, groups));
871
    }
872
    
873
    /** 
874
     * A method to check if the specified user is part of the moderators list 
875
     **/
876
    public static boolean isModerator(String username, String[] groups){
877
    	return (onList(moderators, username, groups));
878
    }
879

    
880
    /** 
881
     * A method to check if the specified user is part of the moderators list 
882
     **/
883
    public static boolean isAllowedSubmitter(String username, String[] groups){
884
    	if(allowedSubmitters != null){
885
    		return (onList(allowedSubmitters, username, groups));
886
    	} else {
887
    		// no allowedSubmitters list specified - 
888
    		// hence everyone should be allowed
889
    		return true;
890
    	}
891
   }
892

    
893
    /** 
894
     * A method to check if the specified user is part of the moderators list 
895
     **/
896
    public static boolean isDeniedSubmitter(String username, String[] groups){
897
		return (onList(deniedSubmitters, username, groups));
898
    }
899
    
900
    /** 
901
     * A method to check if the specified user can insert the document 
902
     **/
903
    public static boolean canInsertOrUpdate(String username, String[] groups){
904
    	return (isAllowedSubmitter(username, groups) 
905
    			&& !isDeniedSubmitter(username, groups));
906
    }
907
}
(44-44/64)