001/*-----------------------------------------------------------------------+
002 | com.teamscale.checks
003 |                                                                       |
004   $Id$            
005 |                                                                       |
006 | Copyright (c)  2009-2015 CQSE GmbH                                 |
007 +-----------------------------------------------------------------------*/
008package eu.cqse.check.framework.core.xpath.functions;
009
010import java.util.List;
011import java.util.regex.Pattern;
012import java.util.regex.PatternSyntaxException;
013
014import org.jaxen.FunctionCallException;
015
016import eu.cqse.check.framework.shallowparser.framework.ShallowEntity;
017
018/**
019 * A function for matching an {@link ShallowEntity}'s name against a set of
020 * regular expressions.
021 */
022public class NameMatchesFunction extends FunctionBase<Pattern> {
023
024        /** The function's name. */
025        public final static String NAME = "name-matches";
026
027        /** {@inheritDoc} */
028        @Override
029        protected Pattern parseArguments(List<?> args) throws FunctionCallException {
030                if (args.size() != 1) {
031                        throw new FunctionCallException(NAME + "(<regex>) expects exactly one argument.");
032                }
033                String regex = args.get(0).toString();
034                try {
035                        return Pattern.compile(regex);
036                } catch (PatternSyntaxException e) {
037                        throw new FunctionCallException("'" + regex + "' is not a valid regular expression.");
038                }
039        }
040
041        /** {@inheritDoc} */
042        @Override
043        protected boolean checkNode(ShallowEntity node, Pattern arguments) {
044                return node.getName() != null && arguments.matcher(node.getName()).matches();
045        }
046}