001 /****************************************************************
002 * Licensed to the Apache Software Foundation (ASF) under one *
003 * or more contributor license agreements. See the NOTICE file *
004 * distributed with this work for additional information *
005 * regarding copyright ownership. The ASF licenses this file *
006 * to you under the Apache License, Version 2.0 (the *
007 * "License"); you may not use this file except in compliance *
008 * with the License. You may obtain a copy of the License at *
009 * *
010 * http://www.apache.org/licenses/LICENSE-2.0 *
011 * *
012 * Unless required by applicable law or agreed to in writing, *
013 * software distributed under the License is distributed on an *
014 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY *
015 * KIND, either express or implied. See the License for the *
016 * specific language governing permissions and limitations *
017 * under the License. *
018 ****************************************************************/
019
020 package org.apache.james.jspf.impl;
021
022
023 import org.apache.james.jspf.parser.TermDefinition;
024
025 import java.util.regex.Pattern;
026
027 /**
028 * Default implementation for the TermDefinition.
029 * This implementation try to retrieve the definition looking up a
030 * static REGEX field in the term class.
031 */
032 public class DefaultTermDefinition implements TermDefinition {
033
034 private Pattern pattern;
035
036 private Class<?> termDef;
037
038 private int matchSize = 0;
039
040 public DefaultTermDefinition(Class<?> tClass) throws IllegalArgumentException,
041 SecurityException, IllegalAccessException, NoSuchFieldException {
042 String pString = (String) tClass.getField("REGEX").get(null);
043 pattern = Pattern.compile(pString);
044 termDef = tClass;
045 calcGroups(pString);
046 }
047
048 /**
049 * This method should be done differently. We currently don't hanlde the
050 * escaping at all.
051 *
052 * @param pString
053 */
054 private void calcGroups(String pString) {
055 int i = 0;
056 int c = 0;
057 while (true) {
058 int p1 = pString.indexOf("(", i);
059 int p2 = pString.indexOf("(?:", i);
060 if (p1 < 0)
061 break;
062 if (p1 != p2)
063 c++;
064 i = p1 + 1;
065 }
066 matchSize = c;
067 }
068
069 /**
070 * @see org.apache.james.jspf.parser.TermDefinition#getPattern()
071 */
072 public Pattern getPattern() {
073 return pattern;
074 }
075
076 /**
077 * @see org.apache.james.jspf.parser.TermDefinition#getTermDef()
078 */
079 public Class<?> getTermDef() {
080 return termDef;
081 }
082
083 /**
084 * @see org.apache.james.jspf.parser.TermDefinition#getMatchSize()
085 */
086 public int getMatchSize() {
087 return matchSize;
088 }
089 }