01: /* Copyright 2001 The JA-SIG Collaborative. All rights reserved.
02: * See license distributed with this file and
03: * available online at http://www.uportal.org/license.html
04: */
05:
06: package org.jasig.portal.utils;
07:
08: import java.io.BufferedReader;
09: import java.io.IOException;
10: import java.io.InputStream;
11: import java.io.InputStreamReader;
12: import java.util.StringTokenizer;
13: import java.util.Vector;
14:
15: import org.apache.oro.text.regex.MalformedPatternException;
16: import org.apache.oro.text.regex.Pattern;
17: import org.apache.oro.text.regex.PatternCompiler;
18: import org.apache.oro.text.regex.PatternMatcher;
19: import org.apache.oro.text.regex.Perl5Compiler;
20: import org.apache.oro.text.regex.Perl5Matcher;
21:
22: public class PropsMatcher {
23: Vector patterns;
24: Vector ids;
25: PatternMatcher matcher;
26:
27: public PropsMatcher(InputStream is) throws IOException {
28: PatternCompiler compiler = new Perl5Compiler();
29: matcher = new Perl5Matcher();
30:
31: // read in a properties file
32: Vector v = readPropertiesVector(is);
33:
34: patterns = new Vector();
35: ids = new Vector(v.size());
36:
37: // prepare separate vectors of compiled patterns
38: // and mapped ids
39: for (int i = 0; i < v.size(); i++) {
40: String[] temp = (String[]) v.elementAt(i);
41:
42: // compile a pattern
43: try {
44: Pattern p = compiler.compile(temp[0]);
45: patterns.addElement(p);
46: // save the id
47: ids.addElement(temp[1]);
48: } catch (MalformedPatternException mpe) {
49: // omit entry, give warning*
50: System.out
51: .println("PropsMatcher::PropsMatcher() : invalid pattern: "
52: + temp[0]);
53: System.out.println("PropsMatcher::PropsMatcher() : "
54: + mpe.getMessage());
55: }
56:
57: }
58: }
59:
60: public String match(String input) {
61: // sequentially try to match to every pattern
62: for (int i = 0; i < patterns.size(); i++) {
63: if (matcher.matches(input, (Pattern) patterns.elementAt(i))) {
64: return (String) ids.elementAt(i);
65: }
66: }
67: return null;
68: }
69:
70: private Vector readPropertiesVector(InputStream inputStream)
71: throws IOException {
72: Vector v = new Vector(10);
73: BufferedReader input = new BufferedReader(
74: new InputStreamReader(inputStream));
75: String currentLine, Key = null;
76: StringTokenizer currentTokens;
77: while ((currentLine = input.readLine()) != null) {
78: currentTokens = new StringTokenizer(currentLine, "=\t\r\n");
79: if (currentTokens.hasMoreTokens()) {
80: Key = currentTokens.nextToken().trim();
81: }
82: if ((Key != null) && !Key.startsWith("#")
83: && currentTokens.hasMoreTokens()) {
84: String temp[] = new String[2];
85: temp[0] = Key;
86: temp[1] = currentTokens.nextToken().trim();
87: v.addElement(temp);
88: }
89: }
90: return v;
91: }
92: }
|