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 349 jones
 *    Release: @release@
8 1538 berkley
 *
9 203 jones
 *   '$Author$'
10
 *     '$Date$'
11
 * '$Revision$'
12 669 jones
 *
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 51 jones
 */
27
28
package edu.ucsb.nceas.metacat;
29
30 185 jones
import java.io.File;
31 2068 jones
import java.net.MalformedURLException;
32 185 jones
import java.net.URL;
33 2893 sgarg
import java.util.HashMap;
34 309 bojilova
import java.util.Hashtable;
35 1545 tao
import java.util.Stack;
36 887 berkley
import java.util.Vector;
37 2558 sgarg
import java.util.regex.PatternSyntaxException;
38 50 jones
39 2591 sgarg
import org.apache.log4j.Logger;
40
41 777 bojilova
import edu.ucsb.nceas.dbadapter.AbstractDatabase;
42 1951 jones
import edu.ucsb.nceas.utilities.Options;
43 747 bojilova
44 50 jones
/**
45
 * A suite of utility classes for the metadata catalog server
46
 */
47 2068 jones
public class MetaCatUtil
48
{
49 50 jones
50 2068 jones
    public static AbstractDatabase dbAdapter;
51 109 bojilova
52 2521 sgarg
    public static Vector pathsForIndexing;
53 2893 sgarg
54
    public static HashMap skinconfigs = new HashMap();
55 2521 sgarg
56 3034 perry
    private static edu.ucsb.nceas.utilities.Options options = null;
57 747 bojilova
58 2068 jones
    private static boolean debug = true;
59 2558 sgarg
60
    private static String[] administrators;
61
62
    private static String[] moderators;
63 2068 jones
64 2576 sgarg
    private static String[] allowedSubmitters;
65
66
    private static String[] deniedSubmitters;
67 2665 sgarg
68
    private static Logger logMetacat = Logger.getLogger(MetaCatUtil.class);
69 2576 sgarg
70 2068 jones
    static {
71 2591 sgarg
    	// Determine our db adapter class and create an instance of that class
72 2068 jones
        try {
73
            dbAdapter = (AbstractDatabase) createObject(getOption("dbAdapter"));
74
        } catch (Exception e) {
75
            System.err.println("Error in MetaCatUtil static block:"
76
                    + e.getMessage());
77 3034 perry
            e.printStackTrace();
78 2068 jones
        }
79 2558 sgarg
80
        // read administrator and moderator lists from metacat.properties
81 2576 sgarg
        getUserAccessControlLists();
82 747 bojilova
    }
83 2665 sgarg
84 2068 jones
    /**
85
     * Instantiate a class using the name of the class at runtime
86 2165 tao
     *
87 2068 jones
     * @param className the fully qualified name of the class to instantiate
88
     */
89
    public static Object createObject(String className) throws Exception
90
    {
91 747 bojilova
92 2068 jones
        Object object = null;
93
        try {
94
            Class classDefinition = Class.forName(className);
95
            object = classDefinition.newInstance();
96
        } catch (InstantiationException e) {
97
            throw e;
98
        } catch (IllegalAccessException e) {
99
            throw e;
100
        } catch (ClassNotFoundException e) {
101
            throw e;
102
        }
103
        return object;
104
    }
105 1217 tao
106 2068 jones
    /**
107
     * Utility method to get an option value from the properties file
108 2165 tao
     *
109 2068 jones
     * @param optionName the name of the option requested
110
     * @return the String value for the option, or null if not set
111
     */
112
    public static String getOption(String optionName)
113
    {
114
        if (options == null) {
115 3034 perry
            options = edu.ucsb.nceas.utilities.Options.getInstance();
116 2068 jones
        }
117 3034 perry
        if (options == null) {
118
        	MetaCatUtil.printMessage("options is null");
119
        }
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
229 2068 jones
    /**
230
     * Utility method to print debugging messages. User can set debug level for
231
     * this message. The number is fewer, the message is more important
232 2165 tao
     *
233 2068 jones
     * @param msg, the content of the message
234
     * @param debugLevel, an integer indicating the message debug leve
235
     */
236 2665 sgarg
    /**
237
     * Commenting out the function for now...
238
     * public static void debugMessage(String msg, int debugLevel)
239
     * {
240
     *   if (debug) {
241
     *       int limit = 1;
242
     *       try {
243
     *           limit = Integer.parseInt(getOption("debuglevel"));
244
     *
245
     *       } catch (Exception e) {
246
     *           System.out.println(e.getMessage());
247
     *       }
248
     *       //don't allow the user set debugLevel less than or equals 0
249
     *       if (debugLevel <= 0) {
250
     *           debugLevel = 1;
251
     *       }
252
     *
253
     *       if (debugLevel < limit) {
254
     *           System.err.println("@debugprefix@ " + msg);
255
     *       }
256
     *   }
257
     *}
258
     */
259 1538 berkley
260
261 2512 sgarg
    /**
262
     * Utility method to print debugging messages. User can set debug level for
263 2665 sgarg
     * this message. The number is fewer, the message is more important
264 2512 sgarg
     *
265
     * @param msg, the content of the message
266 2665 sgarg
     * @param debugLevel, an integer indicating the message debug leve
267 2512 sgarg
     */
268 2665 sgarg
    public static void printMessage(String msg)
269 2512 sgarg
    {
270 2665 sgarg
    	System.err.println("@debugprefix@ " + msg);
271 2512 sgarg
    }
272 2665 sgarg
273
274 2068 jones
    public static Vector getOptionList(String optiontext)
275
    {
276
        Vector optionsVector = new Vector();
277
        if (optiontext.indexOf(",") == -1) {
278
            optionsVector.addElement(optiontext);
279
            return optionsVector;
280
        }
281 1538 berkley
282 2068 jones
        while (optiontext.indexOf(",") != -1) {
283
            String s = optiontext.substring(0, optiontext.indexOf(","));
284
            optionsVector.addElement(s.trim());
285
            optiontext = optiontext.substring(optiontext.indexOf(",") + 1,
286
                    optiontext.length());
287
            if (optiontext.indexOf(",") == -1) { //catch the last list entry
288
                optionsVector.addElement(optiontext.trim());
289
            }
290
        }
291
        return optionsVector;
292 887 berkley
    }
293 1538 berkley
294 2068 jones
    /** Normalizes the given string. Taken from configXML.java */
295
    public static String normalize(String s)
296 887 berkley
    {
297 2068 jones
        StringBuffer str = new StringBuffer();
298
299 2339 sgarg
             int len = (s != null) ? s.length() : 0;
300
             for (int i = 0; i < len; i++) {
301
                 char ch = s.charAt(i);
302
                 switch (ch) {
303
                     case '<': {
304
                         str.append("&lt;");
305
                         break;
306
                     }
307
                     case '>': {
308
                         str.append("&gt;");
309
                         break;
310
                     }
311
                     case '&': {
312 2449 sgarg
                         /*
313
                          * patch provided by Johnoel Ancheta from U of Hawaii
314
                          */
315
                         // check if & is for a character reference &#xnnnn;
316
                         if (i + 1 < len - 1 && s.charAt(i + 1) == '#') {
317
                             str.append("&#");
318
                             i += 2;
319
320
                             ch = s.charAt(i);
321
                             while (i < len && ch != ';') {
322
                                 str.append(ch);
323
                                 i++;
324
                                 ch = s.charAt(i);
325
                             }
326
                             str.append(';');
327 2557 sgarg
                         } else
328
                         // check if & is in front of amp;
329
                         // (we dont yet check for other HTML 4.0 Character entities)
330
                         if (i + 4 < len -1 && s.charAt(i + 1) == 'a'
331
                        	 && s.charAt(i + 2) == 'm'
332
                        		 && s.charAt(i + 3) == 'p'
333
                        			 && s.charAt(i + 4) == ';'){
334 2449 sgarg
                             str.append("&amp;");
335 2997 sgarg
                             i += 4;
336 2557 sgarg
                         } else
337
                             str.append("&amp;");
338 2449 sgarg
                         /////////
339 2339 sgarg
                         break;
340
                     }
341 2449 sgarg
                    default: {
342
                         if ( (ch<128) && (ch>31) ) {
343 2339 sgarg
                             str.append(ch);
344
                         }
345
                         else if (ch<32) {
346 2449 sgarg
                             if (ch == 10) { // new line
347 2339 sgarg
                                 str.append(ch);
348
                             }
349 2449 sgarg
                             if (ch == 13) { // carriage return
350 2339 sgarg
                                 str.append(ch);
351
                             }
352 2449 sgarg
                             if (ch == 9) {  // tab
353 2339 sgarg
                                 str.append(ch);
354
                             }
355
                             // otherwise skip
356
                         }
357
                         else {
358
                             str.append("&#");
359
                             str.append(Integer.toString(ch));
360
                             str.append(';');
361
                         }
362
                     }
363
                 }
364
             }
365 2437 sgarg
             return str.toString();
366 887 berkley
    }
367 1538 berkley
368 2068 jones
    /**
369
     * Get docid from online/url string
370
     */
371
    public static String getDocIdWithRevFromOnlineURL(String url)
372 894 berkley
    {
373 2068 jones
        String docid = null;
374
        String DOCID = "docid";
375
        boolean find = false;
376
        char limited = '&';
377
        int count = 0; //keep track how many & was found
378
        Vector list = new Vector();// keep index number for &
379
        if (url == null) {
380 2665 sgarg
            logMetacat.info("url is null and null will be returned");
381 2068 jones
            return docid;
382
        }
383
        // the first element in list is 0
384
        list.add(new Integer(0));
385
        for (int i = 0; i < url.length(); i++) {
386
            if (url.charAt(i) == limited) {
387
                // count plus 1
388
                count++;
389
                list.add(new Integer(i));
390
                // get substring beween two &
391
                String str = url.substring(
392
                        ((Integer) list.elementAt(count - 1)).intValue(), i);
393 2665 sgarg
                logMetacat.info("substring between two & is: " + str);
394 2068 jones
                //if the subString contains docid, we got it
395
                if (str.indexOf(DOCID) != -1) {
396
                    //get index of '="
397
                    int start = getIndexForGivenChar(str, '=') + 1;
398
                    int end = str.length();
399
                    docid = str.substring(start, end);
400
                    find = true;
401
                }//if
402
            }//if
403
        }//for
404
        //if not find, we need check the subtring between the index of last &
405
        // and
406
        // the end of string
407
        if (!find) {
408 2665 sgarg
            logMetacat.info("Checking the last substring");
409 2068 jones
            String str = url.substring(((Integer) list.elementAt(count))
410
                    .intValue() + 1, url.length());
411 2665 sgarg
            logMetacat.info("Last substring is: " + str);
412 2068 jones
            if (str.indexOf(DOCID) != -1) {
413
                //get index of '="
414
                int start = getIndexForGivenChar(str, '=') + 1;
415
                int end = str.length();
416
                docid = str.substring(start, end);
417
                find = true;
418
            }//if
419
        }//if
420 2665 sgarg
        logMetacat.info("The docid from online url is:" + docid);
421 2068 jones
        return docid.trim();
422 894 berkley
    }
423 2068 jones
424 2165 tao
425
    /**
426
     * Eocgorid identifier will look like: ecogrid://knb/tao.1.1
427
     * The AccessionNumber tao.1.1 will be returned. If the given doesn't
428
     * contains ecogrid, null will be returned.
429
     * @param identifier String
430
     * @return String
431
     */
432
    public static String getAccessionNumberFromEcogridIdentifier(String identifier)
433
    {
434
      String accessionNumber = null;
435
      if (identifier != null && identifier.startsWith(DBSAXHandler.ECOGRID))
436
      {
437
        // find the last "/" in identifier
438
        int indexOfLastSlash = identifier.lastIndexOf("/");
439
        int start = indexOfLastSlash+1;
440
        int end   = identifier.length();
441
        accessionNumber = identifier.substring(start, end);
442
      }
443 2665 sgarg
      logMetacat.warn("The accession number from url is " +
444
                                 accessionNumber);
445 2165 tao
      return accessionNumber;
446
    }
447
448 2068 jones
    private static int getIndexForGivenChar(String str, char character)
449 1557 tao
    {
450 2068 jones
        int index = -1;
451
        // make sure str is not null
452
        if (str == null) {
453 2665 sgarg
            logMetacat.info(
454
                    "The given str is null and -1 will be returned");
455 2068 jones
            return index;
456
        }
457
        // got though the string
458
        for (int i = 0; i < str.length(); i++) {
459
            // find the first one then break the loop
460
            if (str.charAt(i) == character) {
461
                index = i;
462
                break;
463
            }//if
464
        }//for
465 2665 sgarg
        logMetacat.info("the index for char " + character + " is: "
466
                + index);
467 2068 jones
        return index;
468 1557 tao
    }
469 2068 jones
470
    /**
471
     * Utility method to get docid from a given string
472 2165 tao
     *
473 2068 jones
     * @param string, the given string should be these two format: 1) str1.str2
474
     *            in this case docid= str1.str2 2) str1.str2.str3, in this case
475
     *            docid =str1.str2
476
     * @param the sperator char
477
     */
478
    public static String getDocIdFromString(String str)
479 1557 tao
    {
480 2068 jones
        String docId = null;
481
        if (str == null) {
482 2665 sgarg
            logMetacat.info(
483 2068 jones
                    "The given str is null and null will be returned"
484 2665 sgarg
                            + " in getDocIdfromString");
485 2068 jones
            return docId;
486
        } //make sure docid is not null
487
        int dotNumber = 0;//count how many dots in given string
488
        int indexOfLastDot = 0;
489 1538 berkley
490 2068 jones
        //assume that seperator is one charactor string
491
        char seperator = getOption("accNumSeparator").charAt(0);
492 1538 berkley
493 2068 jones
        for (int i = 0; i < str.length(); i++) {
494
            if (str.charAt(i) == seperator) {
495
                dotNumber++;//count how many dots
496
                indexOfLastDot = i;//keep the last dot postion
497
            }
498
        }//for
499 1538 berkley
500 2068 jones
        //The string formatt is wrong, because it has more than two or less
501
        // than
502
        //one seperator
503
        if (dotNumber > 2 || dotNumber < 1) {
504
            docId = null;
505
        } else if (dotNumber == 2) //the case for str1.str2.str3
506
        {
507
            docId = str.substring(0, indexOfLastDot);
508
        } else if (dotNumber == 1) //the case for str1.str2
509
        {
510
            docId = str;
511
        }
512
513
        return docId;
514
    }//getDocIdFromString
515
516
    /**
517
     * Utility method to get version number from a given string
518 2165 tao
     *
519 2068 jones
     * @param string, the given string should be these two format: 1)
520
     *            str1.str2(no version) version =-1; 2) str1.str2.str3, in this
521
     *            case version = str3; 3) other, vresion =-2
522
     */
523
    public static int getVersionFromString(String str)
524
            throws NumberFormatException
525 942 tao
    {
526 2068 jones
        int version = -1;
527
        String versionString = null;
528
        int dotNumber = 0;//count how many dots in given string
529
        int indexOfLastDot = 0;
530 1538 berkley
531 2068 jones
        //assume that seperator is one charactor string
532
        char seperator = getOption("accNumSeparator").charAt(0);
533 942 tao
534 2068 jones
        for (int i = 0; i < str.length(); i++) {
535
            if (str.charAt(i) == seperator) {
536
                dotNumber++;//count how many dots
537
                indexOfLastDot = i;//keep the last dot postion
538
            }
539
        }//for
540 2045 tao
541 2068 jones
        //The string formatt is wrong, because it has more than two or less
542
        // than
543
        //one seperator
544
        if (dotNumber > 2 || dotNumber < 1) {
545
            version = -2;
546
        } else if (dotNumber == 2 && (indexOfLastDot != (str.length() - 1)))
547
        //the case for str1.str2.str3
548
        {
549
            versionString = str.substring((indexOfLastDot + 1), str.length());
550
            version = Integer.parseInt(versionString);
551
        } else if (dotNumber == 1) //the case for str1.str2
552
        {
553
            version = -1;
554
        }
555 1538 berkley
556 2068 jones
        return version;
557
    }//getVersionFromString
558 1538 berkley
559 2068 jones
    /**
560
     * Utility method to get version string from a given string
561 2165 tao
     *
562 2068 jones
     * @param string, the given string should be these two format: 1)
563
     *            str1.str2(no version) version=null; 2) str1.str2.str3, in
564
     *            this case version = str3; 3) other, vresion =null;
565
     */
566
    public static String getRevisionStringFromString(String str)
567
            throws NumberFormatException
568 942 tao
    {
569 2068 jones
        // String to store the version
570
        String versionString = null;
571
        int dotNumber = 0;//count how many dots in given string
572
        int indexOfLastDot = 0;
573 1538 berkley
574 2068 jones
        //assume that seperator is one charactor string
575
        char seperator = getOption("accNumSeparator").charAt(0);
576 1538 berkley
577 2068 jones
        for (int i = 0; i < str.length(); i++) {
578
            if (str.charAt(i) == seperator) {
579
                dotNumber++;//count how many dots
580
                indexOfLastDot = i;//keep the last dot postion
581
            }
582
        }//for
583 1538 berkley
584 2068 jones
        //The string formatt is wrong, because it has more than two or less
585
        // than
586
        //one seperator
587
        if (dotNumber > 2 || dotNumber < 1) {
588
            versionString = null;
589
        } else if (dotNumber == 2 && (indexOfLastDot != (str.length() - 1))) {
590
            //the case for str1.str2.str3
591
            // indexOfLastDot != (str.length() -1) means get rid of str1.str2.
592
            versionString = str.substring((indexOfLastDot + 1), str.length());
593
        } else if (dotNumber == 1) //the case for str1.str2 or str1.str2.
594
        {
595
            versionString = null;
596
        }
597 1538 berkley
598 2068 jones
        return versionString;
599
    }//getVersionFromString
600 1538 berkley
601 2068 jones
    /**
602
     * This method will get docid from an AccessionNumber. There is no
603
     * assumption the accessnumber will be str1.str2.str3. It can be more. So
604
     * we think the docid will be get rid of last part
605
     */
606
    public static String getDocIdFromAccessionNumber(String accessionNumber)
607 1292 tao
    {
608 2068 jones
        String docid = null;
609
        if (accessionNumber == null) { return docid; }
610
        String seperator = getOption("accNumSeparator");
611
        int indexOfLastSeperator = accessionNumber.lastIndexOf(seperator);
612
        docid = accessionNumber.substring(0, indexOfLastSeperator);
613 2665 sgarg
        logMetacat.info("after parsing accessionnumber, docid is "
614
                + docid);
615 2068 jones
        return docid;
616
    }
617 1538 berkley
618 2068 jones
    /**
619 2290 sgarg
     * This method will get inline data id without the revision number.
620
     * So if inlineData.1.2 is passed as input, inlineData.2 is returned.
621
     */
622
    public static String getInlineDataIdWithoutRev(String accessionNumber)
623
    {
624
        String docid = null;
625
        if (accessionNumber == null) { return docid; }
626
        String seperator = getOption("accNumSeparator");
627
        int indexOfLastSeperator = accessionNumber.lastIndexOf(seperator);
628
        String version = accessionNumber.substring(indexOfLastSeperator,
629
                                                   accessionNumber.length());
630
        accessionNumber = accessionNumber.substring(0, indexOfLastSeperator);
631
        indexOfLastSeperator = accessionNumber.lastIndexOf(seperator);
632
        docid = accessionNumber.substring(0, indexOfLastSeperator) + version;
633 2665 sgarg
        logMetacat.info("after parsing accessionnumber, docid is "
634
                                 + docid);
635 2290 sgarg
636
        return docid;
637
    }
638
639
    /**
640 2068 jones
     * This method will call both getDocIdFromString and
641
     * getDocIdFromAccessionNumber. So first, if the string looks str1.str2,
642
     * the docid will be str1.str2. If the string is str1.str2.str3, the docid
643
     * will be str1.str2. If the string is str1.str2.str3.str4 or more, the
644
     * docid will be str1.str2.str3. If the string look like str1, null will be
645
     * returned
646 2165 tao
     *
647 2068 jones
     */
648
    public static String getSmartDocId(String str)
649 1292 tao
    {
650 2068 jones
        String docid = null;
651
        //call geDocIdFromString first.
652
        docid = getDocIdFromString(str);
653
        // If docid is null, try to call getDocIdFromAccessionNumber
654
        // it will handle the seperator more than2
655
        if (docid == null) {
656
            docid = getDocIdFromAccessionNumber(str);
657
        }
658 2665 sgarg
        logMetacat.info("The docid get from smart docid getor is "
659
                + docid);
660 2068 jones
        return docid;
661 1292 tao
    }
662 2068 jones
663
    /**
664
     * This method will get revision from an AccessionNumber. There is no
665
     * assumption the accessnumber will be str1.str2.str3. It can be more. So
666
     * we think the docid will be get rid of last part
667
     */
668
    public static int getRevisionFromAccessionNumber(String accessionNumber)
669
            throws NumberFormatException
670 1292 tao
    {
671 2068 jones
        String rev = null;
672
        int revNumber = -1;
673
        if (accessionNumber == null) { return revNumber; }
674
        String seperator = getOption("accNumSeparator");
675
        int indexOfLastSeperator = accessionNumber.lastIndexOf(seperator);
676
        rev = accessionNumber.substring(indexOfLastSeperator + 1,
677
                accessionNumber.length());
678
        revNumber = Integer.parseInt(rev);
679 2665 sgarg
        logMetacat.info("after parsing accessionnumber, rev is "
680
                + revNumber);
681 2068 jones
        return revNumber;
682 1292 tao
    }
683 2068 jones
684
    /**
685
     * Method to get the name of local replication server
686
     */
687
    public static String getLocalReplicationServerName()
688 1292 tao
    {
689 2068 jones
        String replicationServerName = null;
690
        String serverHost = null;
691
        serverHost = getOption("server");
692
        // append "context/servelet/replication" to the host name
693 2574 tao
        replicationServerName = serverHost.trim() + getOption("replicationpath").trim();
694 2068 jones
        return replicationServerName;
695
696 1292 tao
    }
697 1538 berkley
698 2068 jones
    /**
699
     * Method to get docidwithrev from eml2 inline data id The eml inline data
700
     * id would look like eml.200.2.3
701
     */
702
    public static String getDocIdWithoutRevFromInlineDataID(String inlineDataID)
703 2045 tao
    {
704 2068 jones
        String docidWithoutRev = null;
705
        if (inlineDataID == null) { return docidWithoutRev; }
706
        String seperator = MetaCatUtil.getOption("accNumSeparator");
707
        char charSeperator = seperator.charAt(0);
708
        int targetNumberOfSeperator = 2;// we want to know his index
709
        int numberOfSeperator = 0;
710
        for (int i = 0; i < inlineDataID.length(); i++) {
711
            // meet seperator, increase number of seperator
712
            if (inlineDataID.charAt(i) == charSeperator) {
713
                numberOfSeperator++;
714
            }
715
            // if number of seperator reach the target one, record the index(i)
716
            // and get substring and terminate the loop
717
            if (numberOfSeperator == targetNumberOfSeperator) {
718
                docidWithoutRev = inlineDataID.substring(0, i);
719
                break;
720
            }
721
        }
722 1538 berkley
723 2665 sgarg
        logMetacat.info("Docid without rev from inlinedata id: "
724
                + docidWithoutRev);
725 2068 jones
        return docidWithoutRev;
726 1538 berkley
727 2068 jones
    }
728 1538 berkley
729 2068 jones
    /**
730
     * Revise stack change a stack to opposite order
731
     */
732
    public static Stack reviseStack(Stack stack)
733
    {
734
        Stack result = new Stack();
735
        // make sure the parameter is correct
736
        if (stack == null || stack.isEmpty()) {
737
            result = stack;
738
            return result;
739
        }
740 1538 berkley
741 2068 jones
        while (!stack.isEmpty()) {
742
            Object obj = stack.pop();
743
            result.push(obj);
744
        }
745
        return result;
746 1598 tao
    }
747 1538 berkley
748 2068 jones
    /** A method to replace whitespace in url */
749
    public static String replaceWhiteSpaceForURL(String urlHasWhiteSpace)
750 1598 tao
    {
751 2068 jones
        StringBuffer newUrl = new StringBuffer();
752
        String whiteSpaceReplace = "%20";
753
        if (urlHasWhiteSpace == null || urlHasWhiteSpace.trim().equals("")) { return null; }
754 1598 tao
755 2068 jones
        for (int i = 0; i < urlHasWhiteSpace.length(); i++) {
756
            char ch = urlHasWhiteSpace.charAt(i);
757
            if (!Character.isWhitespace(ch)) {
758
                newUrl.append(ch);
759
            } else {
760
                //it is white sapce, replace it by %20
761
                newUrl = newUrl.append(whiteSpaceReplace);
762
            }
763 1598 tao
764 2068 jones
        }//for
765 2665 sgarg
        logMetacat.info("The new string without space is:"
766
                + newUrl.toString());
767 2068 jones
        return newUrl.toString();
768 1598 tao
769 2068 jones
    }// replaceWhiteSpaceForUR
770
771 2558 sgarg
    /**
772
     * A method to read administrators and moderators list from the metacat.properties
773
     **/
774 2576 sgarg
    public static void getUserAccessControlLists(){
775
    	administrators = getListFromOption("administrators");
776
    	moderators = getListFromOption("moderators");
777
    	allowedSubmitters = getListFromOption("allowedSubmitters");
778
    	deniedSubmitters = getListFromOption("deniedSubmitters");
779
    }
780
781
    /**
782
     * A method to read value of a given option from the metacat.properties
783
     * into specified String array
784
     **/
785
    private static String[] getListFromOption(String optionName){
786
    	String[] list = null;
787
    	String listString = MetaCatUtil.getOption(optionName);
788
789 2558 sgarg
        try {
790 2576 sgarg
            if ( listString != null && !listString.trim().equals("")) {
791
            	list = listString.split(":");
792
            } else {
793
            	list = null;
794 2566 tao
            }
795
796 2558 sgarg
        } catch (PatternSyntaxException pse) {
797 2576 sgarg
        	list = null;
798 2665 sgarg
            logMetacat.error("Error in MetacatServlet.init: "
799
                + pse.getMessage());
800 2558 sgarg
        }
801 2576 sgarg
        return list;
802 2558 sgarg
    }
803 2576 sgarg
804 2558 sgarg
    /**
805 2576 sgarg
     * A method to check if the specified user is part of the moderators list
806 2558 sgarg
     **/
807 2576 sgarg
    private static boolean onList(String list[], String username, String[] groups){
808
809
    	if(list == null){
810
    		return false;
811
    	}
812
813
    	// Check that the user is authenticated as an administrator account
814
        for (int i = 0; i < list.length; i++) {
815 2558 sgarg
            // check the given admin dn is a group dn...
816 2585 tao
        	if(groups != null && list[i].startsWith("cn=")){
817 2576 sgarg
            	// is a group dn
818 2558 sgarg
        		for (int j = 0; j < groups.length; j++) {
819 2576 sgarg
        			if (groups[j].equals(list[i])) {
820 2558 sgarg
                		return true;
821
                	}
822
        		}
823
            } else {
824
            	// is a user dn
825 2585 tao
            	if (username != null && username.equals(list[i])) {
826 2576 sgarg
    	    		return true;
827 2558 sgarg
            	}
828
            }
829
        }
830
        return false;
831
    }
832 2576 sgarg
833
    /**
834
     * A method to check if the specified user is part of the administrators list
835
     **/
836
    public static boolean isAdministrator(String username, String[] groups){
837
    	return (onList(administrators, username, groups));
838
    }
839 2558 sgarg
840
    /**
841
     * A method to check if the specified user is part of the moderators list
842
     **/
843
    public static boolean isModerator(String username, String[] groups){
844 2576 sgarg
    	return (onList(moderators, username, groups));
845 2558 sgarg
    }
846 2576 sgarg
847
    /**
848
     * A method to check if the specified user is part of the moderators list
849
     **/
850
    public static boolean isAllowedSubmitter(String username, String[] groups){
851
    	if(allowedSubmitters != null){
852
    		return (onList(allowedSubmitters, username, groups));
853
    	} else {
854
    		// no allowedSubmitters list specified -
855
    		// hence everyone should be allowed
856
    		return true;
857
    	}
858
   }
859
860
    /**
861
     * A method to check if the specified user is part of the moderators list
862
     **/
863
    public static boolean isDeniedSubmitter(String username, String[] groups){
864
		return (onList(deniedSubmitters, username, groups));
865
    }
866
867
    /**
868
     * A method to check if the specified user can insert the document
869
     **/
870
    public static boolean canInsertOrUpdate(String username, String[] groups){
871
    	return (isAllowedSubmitter(username, groups)
872
    			&& !isDeniedSubmitter(username, groups));
873
    }
874 50 jones
}