1 /* 2 * #%L 3 * settings4j 4 * =============================================================== 5 * Copyright (C) 2008 - 2015 Brabenetz Harald, Austria 6 * =============================================================== 7 * Licensed under the Apache License, Version 2.0 (the "License"); 8 * you may not use this file except in compliance with the License. 9 * You may obtain a copy of the License at 10 * 11 * http://www.apache.org/licenses/LICENSE-2.0 12 * 13 * Unless required by applicable law or agreed to in writing, software 14 * distributed under the License is distributed on an "AS IS" BASIS, 15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 * See the License for the specific language governing permissions and 17 * limitations under the License. 18 * #L% 19 */ 20 package org.settings4j.util; 21 22 import java.util.regex.Matcher; 23 import java.util.regex.Pattern; 24 25 import org.apache.commons.collections4.Transformer; 26 27 /** 28 * This Transformer implements the function for a {@link org.apache.commons.collections4.map.LazyMap} 29 * with Key=String (=RegEx) and Value=Boolean (=Result). 30 * 31 * <pre> 32 * Example: 33 * 34 * <% 35 * request.setAttribute("matchPatternMap", LazyMap.decorate(new HashMap(), new MatchPatternTransformer("testString"))); 36 * %> 37 * <html> 38 * <head></head> 39 * <body> 40 * ${matchPatternMap['testString']} == true <br /> 41 * ${matchPatternMap['.*String']} == true <br /> 42 * ${matchPatternMap['test.*']} == true <br /> 43 * ${matchPatternMap['.*string']} == false <br /> 44 * </body> 45 * <html> 46 * </pre> 47 * 48 * @see java.util.regex.Pattern 49 * @author Harald.Brabenetz 50 */ 51 public class MatchPatternTransformer implements Transformer<String, Boolean> { 52 53 /** General Logger for this Class. */ 54 private static final org.slf4j.Logger LOG = org.slf4j.LoggerFactory.getLogger(MatchPatternTransformer.class); 55 56 private final String compareValue; 57 58 /** 59 * @param compareValue The String which should be Compared with a RegEx. see {@link Pattern}. 60 */ 61 public MatchPatternTransformer(final String compareValue) { 62 super(); 63 this.compareValue = compareValue; 64 } 65 66 @Override 67 public Boolean transform(final String patternString) { 68 Boolean result = Boolean.FALSE; 69 if (patternString != null) { 70 try { 71 final Pattern pattern = Pattern.compile(patternString); 72 final Matcher matcher = pattern.matcher(this.compareValue); 73 if (matcher.matches()) { 74 result = Boolean.TRUE; 75 LOG.debug("TRUE - found '{}' in '{}'", patternString, this.compareValue); 76 } else { 77 result = Boolean.FALSE; 78 LOG.debug("FALSE - do not found '{}' in '{}'", patternString, this.compareValue); 79 } 80 } catch (final Exception e) { 81 LOG.warn("Cann't matche Pattern '{}' with compareValue '{}'", patternString, this.compareValue, e); 82 result = Boolean.FALSE; 83 } 84 } 85 return result; 86 } 87 88 }