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
        	MetaCatUtil.printMessage("options is null");
118
        }
119 2068 jones
        String value = options.getOption(optionName);
120
        return value;
121
    }
122 2554 tao
123
    /**
124
     * Utility method to set an option value from the properties file
125
     *
126
     * @param optionName the name of the option requested
127
     */
128
    public static void setOption(String optionName, String newValue)
129
    {
130
        if (options == null) {
131 3034 perry
            options = edu.ucsb.nceas.utilities.Options.getInstance();
132 2554 tao
        }
133
        options.setOption(optionName, newValue);
134
135
    }
136 1538 berkley
137 2068 jones
    /** Utility method to convert a file handle into a URL */
138
    public static URL fileToURL(File file)
139
    {
140
        String path = file.getAbsolutePath();
141
        String fSep = System.getProperty("file.separator");
142
        if (fSep != null && fSep.length() == 1)
143
                path = path.replace(fSep.charAt(0), '/');
144
        if (path.length() > 0 && path.charAt(0) != '/') path = '/' + path;
145
        try {
146
            return new URL("file", null, path);
147
        } catch (java.net.MalformedURLException e) {
148
            /*
149
             * According to the spec this could only happen if the file
150
             */
151
            throw new Error("unexpected MalformedURLException");
152
        }
153 747 bojilova
    }
154
155 2068 jones
    /**
156
     * Utility method to parse the query part of a URL into parameters. This
157
     * method assumes the format of the query par tof the url is an ampersand
158
     * separated list of name/value pairs, with equal signs separating the name
159
     * from the value (e.g., name=tom&zip=99801 ). Returns a has of the name
160
     * value pairs, hashed on name.
161
     */
162
    public static Hashtable parseQuery(String query)
163
            throws MalformedURLException
164
    {
165
        String[][] params = new String[200][2];
166
        Hashtable parameters = new Hashtable();
167 747 bojilova
168 2068 jones
        String temp = "";
169
        boolean ampflag = true;
170
        boolean poundflag = false;
171
        int arrcount = 0;
172 185 jones
173 2068 jones
        if (query != null) {
174
            for (int i = 0; i < query.length(); i++) {
175 566 jones
176 2068 jones
                // go throught the remainder of the query one character at a
177
                // time.
178
                if (query.charAt(i) == '=') {
179
                    // if the current char is a # then the preceding should be
180
                    // a name
181
                    if (!poundflag && ampflag) {
182
                        params[arrcount][0] = temp.trim();
183
                        temp = "";
184
                    } else {
185
                        //if there are two #s or &s in a row throw an
186
                        // exception.
187
                        throw new MalformedURLException(
188
                                "metacatURL: Two parameter names "
189
                                        + "not allowed in sequence");
190
                    }
191
                    poundflag = true;
192
                    ampflag = false;
193
                } else if (query.charAt(i) == '&' || i == query.length() - 1) {
194
                    //the text preceding the & should be the param value.
195
                    if (i == query.length() - 1) {
196
                        //if at the end of the string grab the last value and
197
                        // append it.
198
                        if (query.charAt(i) != '=') {
199
                            //ignore an extra & on the end of the string
200
                            temp += query.charAt(i);
201
                        }
202
                    }
203 566 jones
204 2068 jones
                    if (!ampflag && poundflag) {
205
                        params[arrcount][1] = temp.trim();
206
                        parameters
207
                                .put(params[arrcount][0], params[arrcount][1]);
208
                        temp = "";
209
                        arrcount++; //increment the array to the next row.
210
                    } else {
211
                        //if there are two =s or &s in a row through an
212
                        // exception
213
                        throw new MalformedURLException(
214
                                "metacatURL: Two parameter values "
215
                                        + "not allowed in sequence");
216
                    }
217
                    poundflag = false;
218
                    ampflag = true;
219
                } else {
220
                    //get the next character in the string
221
                    temp += query.charAt(i);
222
                }
223 731 bojilova
            }
224 566 jones
        }
225 2068 jones
        return parameters;
226 566 jones
    }
227
228 2068 jones
    /**
229
     * Utility method to print debugging messages. User can set debug level for
230
     * this message. The number is fewer, the message is more important
231 2165 tao
     *
232 2068 jones
     * @param msg, the content of the message
233
     * @param debugLevel, an integer indicating the message debug leve
234
     */
235 2665 sgarg
    /**
236
     * Commenting out the function for now...
237
     * public static void debugMessage(String msg, int debugLevel)
238
     * {
239
     *   if (debug) {
240
     *       int limit = 1;
241
     *       try {
242
     *           limit = Integer.parseInt(getOption("debuglevel"));
243
     *
244
     *       } catch (Exception e) {
245
     *           System.out.println(e.getMessage());
246
     *       }
247
     *       //don't allow the user set debugLevel less than or equals 0
248
     *       if (debugLevel <= 0) {
249
     *           debugLevel = 1;
250
     *       }
251
     *
252
     *       if (debugLevel < limit) {
253
     *           System.err.println("@debugprefix@ " + msg);
254
     *       }
255
     *   }
256
     *}
257
     */
258 1538 berkley
259
260 2512 sgarg
    /**
261
     * Utility method to print debugging messages. User can set debug level for
262 2665 sgarg
     * this message. The number is fewer, the message is more important
263 2512 sgarg
     *
264
     * @param msg, the content of the message
265 2665 sgarg
     * @param debugLevel, an integer indicating the message debug leve
266 2512 sgarg
     */
267 2665 sgarg
    public static void printMessage(String msg)
268 2512 sgarg
    {
269 2665 sgarg
    	System.err.println("@debugprefix@ " + msg);
270 2512 sgarg
    }
271 2665 sgarg
272
273 2068 jones
    public static Vector getOptionList(String optiontext)
274
    {
275
        Vector optionsVector = new Vector();
276
        if (optiontext.indexOf(",") == -1) {
277
            optionsVector.addElement(optiontext);
278
            return optionsVector;
279
        }
280 1538 berkley
281 2068 jones
        while (optiontext.indexOf(",") != -1) {
282
            String s = optiontext.substring(0, optiontext.indexOf(","));
283
            optionsVector.addElement(s.trim());
284
            optiontext = optiontext.substring(optiontext.indexOf(",") + 1,
285
                    optiontext.length());
286
            if (optiontext.indexOf(",") == -1) { //catch the last list entry
287
                optionsVector.addElement(optiontext.trim());
288
            }
289
        }
290
        return optionsVector;
291 887 berkley
    }
292 1538 berkley
293 2068 jones
    /** Normalizes the given string. Taken from configXML.java */
294
    public static String normalize(String s)
295 887 berkley
    {
296 2068 jones
        StringBuffer str = new StringBuffer();
297
298 2339 sgarg
             int len = (s != null) ? s.length() : 0;
299
             for (int i = 0; i < len; i++) {
300
                 char ch = s.charAt(i);
301
                 switch (ch) {
302
                     case '<': {
303
                         str.append("&lt;");
304
                         break;
305
                     }
306
                     case '>': {
307
                         str.append("&gt;");
308
                         break;
309
                     }
310
                     case '&': {
311 2449 sgarg
                         /*
312
                          * patch provided by Johnoel Ancheta from U of Hawaii
313
                          */
314
                         // check if & is for a character reference &#xnnnn;
315
                         if (i + 1 < len - 1 && s.charAt(i + 1) == '#') {
316
                             str.append("&#");
317
                             i += 2;
318
319
                             ch = s.charAt(i);
320
                             while (i < len && ch != ';') {
321
                                 str.append(ch);
322
                                 i++;
323
                                 ch = s.charAt(i);
324
                             }
325
                             str.append(';');
326 2557 sgarg
                         } else
327
                         // check if & is in front of amp;
328
                         // (we dont yet check for other HTML 4.0 Character entities)
329
                         if (i + 4 < len -1 && s.charAt(i + 1) == 'a'
330
                        	 && s.charAt(i + 2) == 'm'
331
                        		 && s.charAt(i + 3) == 'p'
332
                        			 && s.charAt(i + 4) == ';'){
333 2449 sgarg
                             str.append("&amp;");
334 2997 sgarg
                             i += 4;
335 2557 sgarg
                         } else
336
                             str.append("&amp;");
337 2449 sgarg
                         /////////
338 2339 sgarg
                         break;
339
                     }
340 2449 sgarg
                    default: {
341
                         if ( (ch<128) && (ch>31) ) {
342 2339 sgarg
                             str.append(ch);
343
                         }
344
                         else if (ch<32) {
345 2449 sgarg
                             if (ch == 10) { // new line
346 2339 sgarg
                                 str.append(ch);
347
                             }
348 2449 sgarg
                             if (ch == 13) { // carriage return
349 2339 sgarg
                                 str.append(ch);
350
                             }
351 2449 sgarg
                             if (ch == 9) {  // tab
352 2339 sgarg
                                 str.append(ch);
353
                             }
354
                             // otherwise skip
355
                         }
356
                         else {
357
                             str.append("&#");
358
                             str.append(Integer.toString(ch));
359
                             str.append(';');
360
                         }
361
                     }
362
                 }
363
             }
364 2437 sgarg
             return str.toString();
365 887 berkley
    }
366 1538 berkley
367 2068 jones
    /**
368
     * Get docid from online/url string
369
     */
370
    public static String getDocIdWithRevFromOnlineURL(String url)
371 894 berkley
    {
372 2068 jones
        String docid = null;
373
        String DOCID = "docid";
374
        boolean find = false;
375
        char limited = '&';
376
        int count = 0; //keep track how many & was found
377
        Vector list = new Vector();// keep index number for &
378
        if (url == null) {
379 2665 sgarg
            logMetacat.info("url is null and null will be returned");
380 2068 jones
            return docid;
381
        }
382
        // the first element in list is 0
383
        list.add(new Integer(0));
384
        for (int i = 0; i < url.length(); i++) {
385
            if (url.charAt(i) == limited) {
386
                // count plus 1
387
                count++;
388
                list.add(new Integer(i));
389
                // get substring beween two &
390
                String str = url.substring(
391
                        ((Integer) list.elementAt(count - 1)).intValue(), i);
392 2665 sgarg
                logMetacat.info("substring between two & is: " + str);
393 2068 jones
                //if the subString contains docid, we got it
394
                if (str.indexOf(DOCID) != -1) {
395
                    //get index of '="
396
                    int start = getIndexForGivenChar(str, '=') + 1;
397
                    int end = str.length();
398
                    docid = str.substring(start, end);
399
                    find = true;
400
                }//if
401
            }//if
402
        }//for
403
        //if not find, we need check the subtring between the index of last &
404
        // and
405
        // the end of string
406
        if (!find) {
407 2665 sgarg
            logMetacat.info("Checking the last substring");
408 2068 jones
            String str = url.substring(((Integer) list.elementAt(count))
409
                    .intValue() + 1, url.length());
410 2665 sgarg
            logMetacat.info("Last substring is: " + str);
411 2068 jones
            if (str.indexOf(DOCID) != -1) {
412
                //get index of '="
413
                int start = getIndexForGivenChar(str, '=') + 1;
414
                int end = str.length();
415
                docid = str.substring(start, end);
416
                find = true;
417
            }//if
418
        }//if
419 2665 sgarg
        logMetacat.info("The docid from online url is:" + docid);
420 2068 jones
        return docid.trim();
421 894 berkley
    }
422 2068 jones
423 2165 tao
424
    /**
425
     * Eocgorid identifier will look like: ecogrid://knb/tao.1.1
426
     * The AccessionNumber tao.1.1 will be returned. If the given doesn't
427
     * contains ecogrid, null will be returned.
428
     * @param identifier String
429
     * @return String
430
     */
431
    public static String getAccessionNumberFromEcogridIdentifier(String identifier)
432
    {
433
      String accessionNumber = null;
434
      if (identifier != null && identifier.startsWith(DBSAXHandler.ECOGRID))
435
      {
436
        // find the last "/" in identifier
437
        int indexOfLastSlash = identifier.lastIndexOf("/");
438
        int start = indexOfLastSlash+1;
439
        int end   = identifier.length();
440
        accessionNumber = identifier.substring(start, end);
441
      }
442 2665 sgarg
      logMetacat.warn("The accession number from url is " +
443
                                 accessionNumber);
444 2165 tao
      return accessionNumber;
445
    }
446
447 2068 jones
    private static int getIndexForGivenChar(String str, char character)
448 1557 tao
    {
449 2068 jones
        int index = -1;
450
        // make sure str is not null
451
        if (str == null) {
452 2665 sgarg
            logMetacat.info(
453
                    "The given str is null and -1 will be returned");
454 2068 jones
            return index;
455
        }
456
        // got though the string
457
        for (int i = 0; i < str.length(); i++) {
458
            // find the first one then break the loop
459
            if (str.charAt(i) == character) {
460
                index = i;
461
                break;
462
            }//if
463
        }//for
464 2665 sgarg
        logMetacat.info("the index for char " + character + " is: "
465
                + index);
466 2068 jones
        return index;
467 1557 tao
    }
468 2068 jones
469
    /**
470
     * Utility method to get docid from a given string
471 2165 tao
     *
472 2068 jones
     * @param string, the given string should be these two format: 1) str1.str2
473
     *            in this case docid= str1.str2 2) str1.str2.str3, in this case
474
     *            docid =str1.str2
475
     * @param the sperator char
476
     */
477
    public static String getDocIdFromString(String str)
478 1557 tao
    {
479 2068 jones
        String docId = null;
480
        if (str == null) {
481 2665 sgarg
            logMetacat.info(
482 2068 jones
                    "The given str is null and null will be returned"
483 2665 sgarg
                            + " in getDocIdfromString");
484 2068 jones
            return docId;
485
        } //make sure docid is not null
486
        int dotNumber = 0;//count how many dots in given string
487
        int indexOfLastDot = 0;
488 1538 berkley
489 2068 jones
        //assume that seperator is one charactor string
490
        char seperator = getOption("accNumSeparator").charAt(0);
491 1538 berkley
492 2068 jones
        for (int i = 0; i < str.length(); i++) {
493
            if (str.charAt(i) == seperator) {
494
                dotNumber++;//count how many dots
495
                indexOfLastDot = i;//keep the last dot postion
496
            }
497
        }//for
498 1538 berkley
499 2068 jones
        //The string formatt is wrong, because it has more than two or less
500
        // than
501
        //one seperator
502
        if (dotNumber > 2 || dotNumber < 1) {
503
            docId = null;
504
        } else if (dotNumber == 2) //the case for str1.str2.str3
505
        {
506
            docId = str.substring(0, indexOfLastDot);
507
        } else if (dotNumber == 1) //the case for str1.str2
508
        {
509
            docId = str;
510
        }
511
512
        return docId;
513
    }//getDocIdFromString
514
515
    /**
516
     * Utility method to get version number from a given string
517 2165 tao
     *
518 2068 jones
     * @param string, the given string should be these two format: 1)
519
     *            str1.str2(no version) version =-1; 2) str1.str2.str3, in this
520
     *            case version = str3; 3) other, vresion =-2
521
     */
522
    public static int getVersionFromString(String str)
523
            throws NumberFormatException
524 942 tao
    {
525 2068 jones
        int version = -1;
526
        String versionString = null;
527
        int dotNumber = 0;//count how many dots in given string
528
        int indexOfLastDot = 0;
529 1538 berkley
530 2068 jones
        //assume that seperator is one charactor string
531
        char seperator = getOption("accNumSeparator").charAt(0);
532 942 tao
533 2068 jones
        for (int i = 0; i < str.length(); i++) {
534
            if (str.charAt(i) == seperator) {
535
                dotNumber++;//count how many dots
536
                indexOfLastDot = i;//keep the last dot postion
537
            }
538
        }//for
539 2045 tao
540 2068 jones
        //The string formatt is wrong, because it has more than two or less
541
        // than
542
        //one seperator
543
        if (dotNumber > 2 || dotNumber < 1) {
544
            version = -2;
545
        } else if (dotNumber == 2 && (indexOfLastDot != (str.length() - 1)))
546
        //the case for str1.str2.str3
547
        {
548
            versionString = str.substring((indexOfLastDot + 1), str.length());
549
            version = Integer.parseInt(versionString);
550
        } else if (dotNumber == 1) //the case for str1.str2
551
        {
552
            version = -1;
553
        }
554 1538 berkley
555 2068 jones
        return version;
556
    }//getVersionFromString
557 1538 berkley
558 2068 jones
    /**
559
     * Utility method to get version string from a given string
560 2165 tao
     *
561 2068 jones
     * @param string, the given string should be these two format: 1)
562
     *            str1.str2(no version) version=null; 2) str1.str2.str3, in
563
     *            this case version = str3; 3) other, vresion =null;
564
     */
565
    public static String getRevisionStringFromString(String str)
566
            throws NumberFormatException
567 942 tao
    {
568 2068 jones
        // String to store the version
569
        String versionString = null;
570
        int dotNumber = 0;//count how many dots in given string
571
        int indexOfLastDot = 0;
572 1538 berkley
573 2068 jones
        //assume that seperator is one charactor string
574
        char seperator = getOption("accNumSeparator").charAt(0);
575 1538 berkley
576 2068 jones
        for (int i = 0; i < str.length(); i++) {
577
            if (str.charAt(i) == seperator) {
578
                dotNumber++;//count how many dots
579
                indexOfLastDot = i;//keep the last dot postion
580
            }
581
        }//for
582 1538 berkley
583 2068 jones
        //The string formatt is wrong, because it has more than two or less
584
        // than
585
        //one seperator
586
        if (dotNumber > 2 || dotNumber < 1) {
587
            versionString = null;
588
        } else if (dotNumber == 2 && (indexOfLastDot != (str.length() - 1))) {
589
            //the case for str1.str2.str3
590
            // indexOfLastDot != (str.length() -1) means get rid of str1.str2.
591
            versionString = str.substring((indexOfLastDot + 1), str.length());
592
        } else if (dotNumber == 1) //the case for str1.str2 or str1.str2.
593
        {
594
            versionString = null;
595
        }
596 1538 berkley
597 2068 jones
        return versionString;
598
    }//getVersionFromString
599 1538 berkley
600 2068 jones
    /**
601
     * This method will get docid from an AccessionNumber. There is no
602
     * assumption the accessnumber will be str1.str2.str3. It can be more. So
603
     * we think the docid will be get rid of last part
604
     */
605
    public static String getDocIdFromAccessionNumber(String accessionNumber)
606 1292 tao
    {
607 2068 jones
        String docid = null;
608
        if (accessionNumber == null) { return docid; }
609
        String seperator = getOption("accNumSeparator");
610
        int indexOfLastSeperator = accessionNumber.lastIndexOf(seperator);
611
        docid = accessionNumber.substring(0, indexOfLastSeperator);
612 2665 sgarg
        logMetacat.info("after parsing accessionnumber, docid is "
613
                + docid);
614 2068 jones
        return docid;
615
    }
616 1538 berkley
617 2068 jones
    /**
618 2290 sgarg
     * This method will get inline data id without the revision number.
619
     * So if inlineData.1.2 is passed as input, inlineData.2 is returned.
620
     */
621
    public static String getInlineDataIdWithoutRev(String accessionNumber)
622
    {
623
        String docid = null;
624
        if (accessionNumber == null) { return docid; }
625
        String seperator = getOption("accNumSeparator");
626
        int indexOfLastSeperator = accessionNumber.lastIndexOf(seperator);
627
        String version = accessionNumber.substring(indexOfLastSeperator,
628
                                                   accessionNumber.length());
629
        accessionNumber = accessionNumber.substring(0, indexOfLastSeperator);
630
        indexOfLastSeperator = accessionNumber.lastIndexOf(seperator);
631
        docid = accessionNumber.substring(0, indexOfLastSeperator) + version;
632 2665 sgarg
        logMetacat.info("after parsing accessionnumber, docid is "
633
                                 + docid);
634 2290 sgarg
635
        return docid;
636
    }
637
638
    /**
639 2068 jones
     * This method will call both getDocIdFromString and
640
     * getDocIdFromAccessionNumber. So first, if the string looks str1.str2,
641
     * the docid will be str1.str2. If the string is str1.str2.str3, the docid
642
     * will be str1.str2. If the string is str1.str2.str3.str4 or more, the
643
     * docid will be str1.str2.str3. If the string look like str1, null will be
644
     * returned
645 2165 tao
     *
646 2068 jones
     */
647
    public static String getSmartDocId(String str)
648 1292 tao
    {
649 2068 jones
        String docid = null;
650
        //call geDocIdFromString first.
651
        docid = getDocIdFromString(str);
652
        // If docid is null, try to call getDocIdFromAccessionNumber
653
        // it will handle the seperator more than2
654
        if (docid == null) {
655
            docid = getDocIdFromAccessionNumber(str);
656
        }
657 2665 sgarg
        logMetacat.info("The docid get from smart docid getor is "
658
                + docid);
659 2068 jones
        return docid;
660 1292 tao
    }
661 2068 jones
662
    /**
663
     * This method will get revision from an AccessionNumber. There is no
664
     * assumption the accessnumber will be str1.str2.str3. It can be more. So
665
     * we think the docid will be get rid of last part
666
     */
667
    public static int getRevisionFromAccessionNumber(String accessionNumber)
668
            throws NumberFormatException
669 1292 tao
    {
670 2068 jones
        String rev = null;
671
        int revNumber = -1;
672
        if (accessionNumber == null) { return revNumber; }
673
        String seperator = getOption("accNumSeparator");
674
        int indexOfLastSeperator = accessionNumber.lastIndexOf(seperator);
675
        rev = accessionNumber.substring(indexOfLastSeperator + 1,
676
                accessionNumber.length());
677
        revNumber = Integer.parseInt(rev);
678 2665 sgarg
        logMetacat.info("after parsing accessionnumber, rev is "
679
                + revNumber);
680 2068 jones
        return revNumber;
681 1292 tao
    }
682 2068 jones
683
    /**
684
     * Method to get the name of local replication server
685
     */
686
    public static String getLocalReplicationServerName()
687 1292 tao
    {
688 2068 jones
        String replicationServerName = null;
689
        String serverHost = null;
690
        serverHost = getOption("server");
691
        // append "context/servelet/replication" to the host name
692 2574 tao
        replicationServerName = serverHost.trim() + getOption("replicationpath").trim();
693 2068 jones
        return replicationServerName;
694
695 1292 tao
    }
696 1538 berkley
697 2068 jones
    /**
698
     * Method to get docidwithrev from eml2 inline data id The eml inline data
699
     * id would look like eml.200.2.3
700
     */
701
    public static String getDocIdWithoutRevFromInlineDataID(String inlineDataID)
702 2045 tao
    {
703 2068 jones
        String docidWithoutRev = null;
704
        if (inlineDataID == null) { return docidWithoutRev; }
705
        String seperator = MetaCatUtil.getOption("accNumSeparator");
706
        char charSeperator = seperator.charAt(0);
707
        int targetNumberOfSeperator = 2;// we want to know his index
708
        int numberOfSeperator = 0;
709
        for (int i = 0; i < inlineDataID.length(); i++) {
710
            // meet seperator, increase number of seperator
711
            if (inlineDataID.charAt(i) == charSeperator) {
712
                numberOfSeperator++;
713
            }
714
            // if number of seperator reach the target one, record the index(i)
715
            // and get substring and terminate the loop
716
            if (numberOfSeperator == targetNumberOfSeperator) {
717
                docidWithoutRev = inlineDataID.substring(0, i);
718
                break;
719
            }
720
        }
721 1538 berkley
722 2665 sgarg
        logMetacat.info("Docid without rev from inlinedata id: "
723
                + docidWithoutRev);
724 2068 jones
        return docidWithoutRev;
725 1538 berkley
726 2068 jones
    }
727 1538 berkley
728 2068 jones
    /**
729
     * Revise stack change a stack to opposite order
730
     */
731
    public static Stack reviseStack(Stack stack)
732
    {
733
        Stack result = new Stack();
734
        // make sure the parameter is correct
735
        if (stack == null || stack.isEmpty()) {
736
            result = stack;
737
            return result;
738
        }
739 1538 berkley
740 2068 jones
        while (!stack.isEmpty()) {
741
            Object obj = stack.pop();
742
            result.push(obj);
743
        }
744
        return result;
745 1598 tao
    }
746 1538 berkley
747 2068 jones
    /** A method to replace whitespace in url */
748
    public static String replaceWhiteSpaceForURL(String urlHasWhiteSpace)
749 1598 tao
    {
750 2068 jones
        StringBuffer newUrl = new StringBuffer();
751
        String whiteSpaceReplace = "%20";
752
        if (urlHasWhiteSpace == null || urlHasWhiteSpace.trim().equals("")) { return null; }
753 1598 tao
754 2068 jones
        for (int i = 0; i < urlHasWhiteSpace.length(); i++) {
755
            char ch = urlHasWhiteSpace.charAt(i);
756
            if (!Character.isWhitespace(ch)) {
757
                newUrl.append(ch);
758
            } else {
759
                //it is white sapce, replace it by %20
760
                newUrl = newUrl.append(whiteSpaceReplace);
761
            }
762 1598 tao
763 2068 jones
        }//for
764 2665 sgarg
        logMetacat.info("The new string without space is:"
765
                + newUrl.toString());
766 2068 jones
        return newUrl.toString();
767 1598 tao
768 2068 jones
    }// replaceWhiteSpaceForUR
769
770 2558 sgarg
    /**
771
     * A method to read administrators and moderators list from the metacat.properties
772
     **/
773 2576 sgarg
    public static void getUserAccessControlLists(){
774
    	administrators = getListFromOption("administrators");
775
    	moderators = getListFromOption("moderators");
776
    	allowedSubmitters = getListFromOption("allowedSubmitters");
777
    	deniedSubmitters = getListFromOption("deniedSubmitters");
778
    }
779
780
    /**
781
     * A method to read value of a given option from the metacat.properties
782
     * into specified String array
783
     **/
784
    private static String[] getListFromOption(String optionName){
785
    	String[] list = null;
786
    	String listString = MetaCatUtil.getOption(optionName);
787
788 2558 sgarg
        try {
789 2576 sgarg
            if ( listString != null && !listString.trim().equals("")) {
790
            	list = listString.split(":");
791
            } else {
792
            	list = null;
793 2566 tao
            }
794
795 2558 sgarg
        } catch (PatternSyntaxException pse) {
796 2576 sgarg
        	list = null;
797 2665 sgarg
            logMetacat.error("Error in MetacatServlet.init: "
798
                + pse.getMessage());
799 2558 sgarg
        }
800 2576 sgarg
        return list;
801 2558 sgarg
    }
802 2576 sgarg
803 2558 sgarg
    /**
804 2576 sgarg
     * A method to check if the specified user is part of the moderators list
805 2558 sgarg
     **/
806 2576 sgarg
    private static boolean onList(String list[], String username, String[] groups){
807
808
    	if(list == null){
809
    		return false;
810
    	}
811
812
    	// Check that the user is authenticated as an administrator account
813
        for (int i = 0; i < list.length; i++) {
814 2558 sgarg
            // check the given admin dn is a group dn...
815 2585 tao
        	if(groups != null && list[i].startsWith("cn=")){
816 2576 sgarg
            	// is a group dn
817 2558 sgarg
        		for (int j = 0; j < groups.length; j++) {
818 2576 sgarg
        			if (groups[j].equals(list[i])) {
819 2558 sgarg
                		return true;
820
                	}
821
        		}
822
            } else {
823
            	// is a user dn
824 2585 tao
            	if (username != null && username.equals(list[i])) {
825 2576 sgarg
    	    		return true;
826 2558 sgarg
            	}
827
            }
828
        }
829
        return false;
830
    }
831 2576 sgarg
832
    /**
833
     * A method to check if the specified user is part of the administrators list
834
     **/
835
    public static boolean isAdministrator(String username, String[] groups){
836
    	return (onList(administrators, username, groups));
837
    }
838 2558 sgarg
839
    /**
840
     * A method to check if the specified user is part of the moderators list
841
     **/
842
    public static boolean isModerator(String username, String[] groups){
843 2576 sgarg
    	return (onList(moderators, username, groups));
844 2558 sgarg
    }
845 2576 sgarg
846
    /**
847
     * A method to check if the specified user is part of the moderators list
848
     **/
849
    public static boolean isAllowedSubmitter(String username, String[] groups){
850
    	if(allowedSubmitters != null){
851
    		return (onList(allowedSubmitters, username, groups));
852
    	} else {
853
    		// no allowedSubmitters list specified -
854
    		// hence everyone should be allowed
855
    		return true;
856
    	}
857
   }
858
859
    /**
860
     * A method to check if the specified user is part of the moderators list
861
     **/
862
    public static boolean isDeniedSubmitter(String username, String[] groups){
863
		return (onList(deniedSubmitters, username, groups));
864
    }
865
866
    /**
867
     * A method to check if the specified user can insert the document
868
     **/
869
    public static boolean canInsertOrUpdate(String username, String[] groups){
870
    	return (isAllowedSubmitter(username, groups)
871
    			&& !isDeniedSubmitter(username, groups));
872
    }
873 50 jones
}