1 16 package org.apache.cocoon.selection; 17 18 import java.util.HashMap ; 19 import java.util.Map ; 20 21 import org.apache.avalon.framework.configuration.Configurable; 22 import org.apache.avalon.framework.configuration.Configuration; 23 import org.apache.avalon.framework.configuration.ConfigurationException; 24 import org.apache.avalon.framework.thread.ThreadSafe; 25 import org.apache.regexp.RE; 26 import org.apache.regexp.RECompiler; 27 import org.apache.regexp.REProgram; 28 import org.apache.regexp.RESyntaxException; 29 30 73 public abstract class AbstractRegexpSelector extends AbstractSwitchSelector 74 implements Configurable, ThreadSafe { 75 76 77 protected Map patterns = new HashMap (); 78 79 82 protected AbstractRegexpSelector() { 83 super(); 84 } 85 86 93 public boolean select(String patternName, Object selectorContext) { 94 95 96 if (selectorContext == null) return(false); 97 98 99 REProgram pattern = (REProgram) this.patterns.get(patternName); 100 if (pattern == null) { 101 if (this.getLogger().isWarnEnabled()) { 102 this.getLogger().warn("The specified pattern name \"" + patternName 103 + "\" was not configured in this instance"); 104 } 105 return(false); 106 } 107 108 109 return(new RE(pattern).match(selectorContext.toString())); 110 } 111 112 120 public void configure(Configuration configuration) 121 throws ConfigurationException { 122 Configuration patterns[] = configuration.getChildren("pattern"); 123 for (int x = 0; x < patterns.length; x++) { 124 String name = patterns[x].getAttribute("name"); 125 String pattern = patterns[x].getValue(); 126 this.patterns.put(name, this.compile(pattern)); 127 } 128 } 129 130 137 protected REProgram compile(String pattern) 138 throws ConfigurationException { 139 if (pattern == null) { 140 throw new ConfigurationException("Null pattern"); 141 } 142 143 if (pattern.length() == 0) { 144 pattern = "^$"; 145 if (this.getLogger().isWarnEnabled()) { 146 this.getLogger().warn("The empty pattern string was rewritten to " 147 + "'^$' to match for empty strings. If you " 148 + "intended to match all strings, please " 149 + "change your pattern to '.*'"); 150 } 151 } 152 153 try { 154 RECompiler compiler = new RECompiler(); 155 REProgram program = compiler.compile(pattern); 156 return program; 157 } catch (RESyntaxException rse) { 158 getLogger().debug("Failed to compile the pattern '" + pattern + "'", rse); 159 throw new ConfigurationException(rse.getMessage(), rse); 160 } 161 } 162 } 163 | Popular Tags |