Project

General

Profile

1 51 jones
/**
2 203 jones
 *  '$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 309 bojilova
 *    Authors: Matt Jones, Jivka Bojilova
7 1538 berkley
 *
8 203 jones
 *   '$Author$'
9
 *     '$Date$'
10
 * '$Revision$'
11 669 jones
 *
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 51 jones
 */
26
27
package edu.ucsb.nceas.metacat;
28
29 185 jones
import java.io.File;
30 2068 jones
import java.net.MalformedURLException;
31 185 jones
import java.net.URL;
32 2893 sgarg
import java.util.HashMap;
33 309 bojilova
import java.util.Hashtable;
34 1545 tao
import java.util.Stack;
35 887 berkley
import java.util.Vector;
36 2558 sgarg
import java.util.regex.PatternSyntaxException;
37 50 jones
38 2591 sgarg
import org.apache.log4j.Logger;
39
40 777 bojilova
import edu.ucsb.nceas.dbadapter.AbstractDatabase;
41 1951 jones
import edu.ucsb.nceas.utilities.Options;
42 747 bojilova
43 50 jones
/**
44
 * A suite of utility classes for the metadata catalog server
45
 */
46 2068 jones
public class MetaCatUtil
47
{
48 50 jones
49 2068 jones
    public static AbstractDatabase dbAdapter;
50 109 bojilova
51 2521 sgarg
    public static Vector pathsForIndexing;
52 2893 sgarg
53
    public static HashMap skinconfigs = new HashMap();
54 2521 sgarg
55 3034 perry
    private static edu.ucsb.nceas.utilities.Options options = null;
56 747 bojilova
57 2068 jones
    private static boolean debug = true;
58 2558 sgarg
59
    private static String[] administrators;
60
61
    private static String[] moderators;
62 2068 jones
63 2576 sgarg
    private static String[] allowedSubmitters;
64
65
    private static String[] deniedSubmitters;
66 2665 sgarg
67
    private static Logger logMetacat = Logger.getLogger(MetaCatUtil.class);
68 2576 sgarg
69 2068 jones
    static {
70 2591 sgarg
    	// Determine our db adapter class and create an instance of that class
71 2068 jones
        try {
72
            dbAdapter = (AbstractDatabase) createObject(getOption("dbAdapter"));
73
        } catch (Exception e) {
74
            System.err.println("Error in MetaCatUtil static block:"
75
                    + e.getMessage());
76 3034 perry
            e.printStackTrace();
77 2068 jones
        }
78 2558 sgarg
79
        // read administrator and moderator lists from metacat.properties
80 2576 sgarg
        getUserAccessControlLists();
81 747 bojilova
    }
82 2665 sgarg
83 2068 jones
    /**
84
     * Instantiate a class using the name of the class at runtime
85 2165 tao
     *
86 2068 jones
     * @param className the fully qualified name of the class to instantiate
87
     */
88
    public static Object createObject(String className) throws Exception
89
    {
90 747 bojilova
91 2068 jones
        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 1217 tao
105 2068 jones
    /**
106
     * Utility method to get an option value from the properties file
107 2165 tao
     *
108 2068 jones
     * @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 3034 perry
            options = edu.ucsb.nceas.utilities.Options.getInstance();
115 2068 jones
        }
116 3034 perry
        if (options == null) {
117 3078 jones
            Logger logMetacat = Logger.getLogger(MetaCatUtil.class);
118
        	logMetacat.info("options is null");
119 3034 perry
        }
120 2068 jones
        String value = options.getOption(optionName);
121
        return value;
122
    }
123 2554 tao
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 3034 perry
            options = edu.ucsb.nceas.utilities.Options.getInstance();
133 2554 tao
        }
134
        options.setOption(optionName, newValue);
135
136
    }
137 1538 berkley
138 2068 jones
    /** 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 747 bojilova
    }
155
156 2068 jones
    /**
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 747 bojilova
169 2068 jones
        String temp = "";
170
        boolean ampflag = true;
171
        boolean poundflag = false;
172
        int arrcount = 0;
173 185 jones
174 2068 jones
        if (query != null) {
175
            for (int i = 0; i < query.length(); i++) {
176 566 jones
177 2068 jones
                // 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 566 jones
205 2068 jones
                    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 731 bojilova
            }
225 566 jones
        }
226 2068 jones
        return parameters;
227 566 jones
    }
228 2665 sgarg
229 2068 jones
    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 1538 berkley
237 2068 jones
        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 887 berkley
    }
248 1538 berkley
249 2068 jones
    /** Normalizes the given string. Taken from configXML.java */
250
    public static String normalize(String s)
251 887 berkley
    {
252 2068 jones
        StringBuffer str = new StringBuffer();
253
254 2339 sgarg
             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 2449 sgarg
                         /*
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 2557 sgarg
                         } 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 2449 sgarg
                             str.append("&amp;");
290 2997 sgarg
                             i += 4;
291 2557 sgarg
                         } else
292
                             str.append("&amp;");
293 2449 sgarg
                         /////////
294 2339 sgarg
                         break;
295
                     }
296 2449 sgarg
                    default: {
297
                         if ( (ch<128) && (ch>31) ) {
298 2339 sgarg
                             str.append(ch);
299
                         }
300
                         else if (ch<32) {
301 2449 sgarg
                             if (ch == 10) { // new line
302 2339 sgarg
                                 str.append(ch);
303
                             }
304 2449 sgarg
                             if (ch == 13) { // carriage return
305 2339 sgarg
                                 str.append(ch);
306
                             }
307 2449 sgarg
                             if (ch == 9) {  // tab
308 2339 sgarg
                                 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 2437 sgarg
             return str.toString();
321 887 berkley
    }
322 1538 berkley
323 2068 jones
    /**
324
     * Get docid from online/url string
325
     */
326
    public static String getDocIdWithRevFromOnlineURL(String url)
327 894 berkley
    {
328 2068 jones
        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 2665 sgarg
            logMetacat.info("url is null and null will be returned");
336 2068 jones
            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 2665 sgarg
                logMetacat.info("substring between two & is: " + str);
349 2068 jones
                //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 2665 sgarg
            logMetacat.info("Checking the last substring");
364 2068 jones
            String str = url.substring(((Integer) list.elementAt(count))
365
                    .intValue() + 1, url.length());
366 2665 sgarg
            logMetacat.info("Last substring is: " + str);
367 2068 jones
            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 2665 sgarg
        logMetacat.info("The docid from online url is:" + docid);
376 2068 jones
        return docid.trim();
377 894 berkley
    }
378 2068 jones
379 2165 tao
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 2665 sgarg
      logMetacat.warn("The accession number from url is " +
399
                                 accessionNumber);
400 2165 tao
      return accessionNumber;
401
    }
402
403 2068 jones
    private static int getIndexForGivenChar(String str, char character)
404 1557 tao
    {
405 2068 jones
        int index = -1;
406
        // make sure str is not null
407
        if (str == null) {
408 2665 sgarg
            logMetacat.info(
409
                    "The given str is null and -1 will be returned");
410 2068 jones
            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 2665 sgarg
        logMetacat.info("the index for char " + character + " is: "
421
                + index);
422 2068 jones
        return index;
423 1557 tao
    }
424 2068 jones
425
    /**
426
     * Utility method to get docid from a given string
427 2165 tao
     *
428 2068 jones
     * @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 1557 tao
    {
435 2068 jones
        String docId = null;
436
        if (str == null) {
437 2665 sgarg
            logMetacat.info(
438 2068 jones
                    "The given str is null and null will be returned"
439 2665 sgarg
                            + " in getDocIdfromString");
440 2068 jones
            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 1538 berkley
445 2068 jones
        //assume that seperator is one charactor string
446
        char seperator = getOption("accNumSeparator").charAt(0);
447 1538 berkley
448 2068 jones
        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 1538 berkley
455 2068 jones
        //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 2165 tao
     *
474 2068 jones
     * @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 942 tao
    {
481 2068 jones
        int version = -1;
482
        String versionString = null;
483
        int dotNumber = 0;//count how many dots in given string
484
        int indexOfLastDot = 0;
485 1538 berkley
486 2068 jones
        //assume that seperator is one charactor string
487
        char seperator = getOption("accNumSeparator").charAt(0);
488 942 tao
489 2068 jones
        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 2045 tao
496 2068 jones
        //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 1538 berkley
511 2068 jones
        return version;
512
    }//getVersionFromString
513 1538 berkley
514 2068 jones
    /**
515
     * Utility method to get version string from a given string
516 2165 tao
     *
517 2068 jones
     * @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 942 tao
    {
524 2068 jones
        // 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 1538 berkley
529 2068 jones
        //assume that seperator is one charactor string
530
        char seperator = getOption("accNumSeparator").charAt(0);
531 1538 berkley
532 2068 jones
        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 1538 berkley
539 2068 jones
        //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 1538 berkley
553 2068 jones
        return versionString;
554
    }//getVersionFromString
555 1538 berkley
556 2068 jones
    /**
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 1292 tao
    {
563 2068 jones
        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 2665 sgarg
        logMetacat.info("after parsing accessionnumber, docid is "
569
                + docid);
570 2068 jones
        return docid;
571
    }
572 1538 berkley
573 2068 jones
    /**
574 2290 sgarg
     * 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 2665 sgarg
        logMetacat.info("after parsing accessionnumber, docid is "
589
                                 + docid);
590 2290 sgarg
591
        return docid;
592
    }
593
594
    /**
595 2068 jones
     * 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 2165 tao
     *
602 2068 jones
     */
603
    public static String getSmartDocId(String str)
604 1292 tao
    {
605 2068 jones
        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 2665 sgarg
        logMetacat.info("The docid get from smart docid getor is "
614
                + docid);
615 2068 jones
        return docid;
616 1292 tao
    }
617 2068 jones
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 1292 tao
    {
626 2068 jones
        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 2665 sgarg
        logMetacat.info("after parsing accessionnumber, rev is "
635
                + revNumber);
636 2068 jones
        return revNumber;
637 1292 tao
    }
638 2068 jones
639
    /**
640
     * Method to get the name of local replication server
641
     */
642
    public static String getLocalReplicationServerName()
643 1292 tao
    {
644 2068 jones
        String replicationServerName = null;
645
        String serverHost = null;
646
        serverHost = getOption("server");
647
        // append "context/servelet/replication" to the host name
648 2574 tao
        replicationServerName = serverHost.trim() + getOption("replicationpath").trim();
649 2068 jones
        return replicationServerName;
650
651 1292 tao
    }
652 1538 berkley
653 2068 jones
    /**
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 2045 tao
    {
659 2068 jones
        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 1538 berkley
678 2665 sgarg
        logMetacat.info("Docid without rev from inlinedata id: "
679
                + docidWithoutRev);
680 2068 jones
        return docidWithoutRev;
681 1538 berkley
682 2068 jones
    }
683 1538 berkley
684 2068 jones
    /**
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 1538 berkley
696 2068 jones
        while (!stack.isEmpty()) {
697
            Object obj = stack.pop();
698
            result.push(obj);
699
        }
700
        return result;
701 1598 tao
    }
702 1538 berkley
703 2068 jones
    /** A method to replace whitespace in url */
704
    public static String replaceWhiteSpaceForURL(String urlHasWhiteSpace)
705 1598 tao
    {
706 2068 jones
        StringBuffer newUrl = new StringBuffer();
707
        String whiteSpaceReplace = "%20";
708
        if (urlHasWhiteSpace == null || urlHasWhiteSpace.trim().equals("")) { return null; }
709 1598 tao
710 2068 jones
        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 1598 tao
719 2068 jones
        }//for
720 2665 sgarg
        logMetacat.info("The new string without space is:"
721
                + newUrl.toString());
722 2068 jones
        return newUrl.toString();
723 1598 tao
724 2068 jones
    }// replaceWhiteSpaceForUR
725
726 2558 sgarg
    /**
727
     * A method to read administrators and moderators list from the metacat.properties
728
     **/
729 2576 sgarg
    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 2558 sgarg
        try {
745 2576 sgarg
            if ( listString != null && !listString.trim().equals("")) {
746
            	list = listString.split(":");
747
            } else {
748
            	list = null;
749 2566 tao
            }
750
751 2558 sgarg
        } catch (PatternSyntaxException pse) {
752 2576 sgarg
        	list = null;
753 2665 sgarg
            logMetacat.error("Error in MetacatServlet.init: "
754
                + pse.getMessage());
755 2558 sgarg
        }
756 2576 sgarg
        return list;
757 2558 sgarg
    }
758 2576 sgarg
759 2558 sgarg
    /**
760 2576 sgarg
     * A method to check if the specified user is part of the moderators list
761 2558 sgarg
     **/
762 2576 sgarg
    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 2558 sgarg
            // check the given admin dn is a group dn...
771 2585 tao
        	if(groups != null && list[i].startsWith("cn=")){
772 2576 sgarg
            	// is a group dn
773 2558 sgarg
        		for (int j = 0; j < groups.length; j++) {
774 2576 sgarg
        			if (groups[j].equals(list[i])) {
775 2558 sgarg
                		return true;
776
                	}
777
        		}
778
            } else {
779
            	// is a user dn
780 2585 tao
            	if (username != null && username.equals(list[i])) {
781 2576 sgarg
    	    		return true;
782 2558 sgarg
            	}
783
            }
784
        }
785
        return false;
786
    }
787 2576 sgarg
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 2558 sgarg
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 2576 sgarg
    	return (onList(moderators, username, groups));
800 2558 sgarg
    }
801 2576 sgarg
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 50 jones
}