1 16 package org.apache.cocoon.matching; 17 18 import org.apache.avalon.framework.parameters.Parameters; 19 import org.apache.avalon.framework.thread.ThreadSafe; 20 import org.apache.cocoon.sitemap.PatternException; 21 import org.apache.cocoon.sitemap.SitemapParameters; 22 import org.apache.regexp.RE; 23 import org.apache.regexp.RECompiler; 24 import org.apache.regexp.REProgram; 25 import org.apache.regexp.RESyntaxException; 26 27 import java.util.HashMap ; 28 import java.util.Map ; 29 30 38 39 public abstract class AbstractRegexpMatcher extends AbstractPreparableMatcher implements ThreadSafe { 40 41 44 public Object preparePattern(String pattern) throws PatternException { 45 if (pattern == null) { 47 return null; 48 } 49 50 if (pattern.length() == 0) { 51 pattern = "^$"; 52 if (getLogger().isWarnEnabled()) { 53 getLogger().warn("The empty pattern string was rewritten to '^$'" 54 + " to match for empty strings. If you intended" 55 + " to match all strings, please change your" 56 + " pattern to '.*'"); 57 } 58 } 59 60 try { 61 RECompiler compiler = new RECompiler(); 62 REProgram program = compiler.compile(pattern); 63 return program; 64 65 } catch (RESyntaxException rse) { 66 getLogger().debug("Failed to compile the pattern '" + pattern + "'", rse); 67 throw new PatternException(rse.getMessage(), rse); 68 } 69 } 70 71 74 public Map preparedMatch(Object preparedPattern, Map objectModel, Parameters parameters) throws PatternException { 75 76 if(preparedPattern == null) { 77 throw new PatternException("A pattern is needed at " + SitemapParameters.getStatementLocation(parameters)); 78 } 79 80 RE re = new RE((REProgram)preparedPattern); 81 String match = getMatchString(objectModel, parameters); 82 83 if (match == null) 84 return null; 85 86 if(re.match(match)) { 87 91 int parenCount = re.getParenCount(); 92 Map map = new HashMap (); 93 for (int paren = 0; paren <= parenCount; paren++) { 94 map.put(Integer.toString(paren), re.getParen(paren)); 95 } 96 97 return map; 98 } 99 100 return null; 101 } 102 103 107 protected abstract String getMatchString(Map objectModel, Parameters parameters); 108 } 109 | Popular Tags |