001package eu.cqse.check.base;
002
003import java.util.regex.MatchResult;
004import java.util.regex.Matcher;
005import java.util.regex.Pattern;
006
007import eu.cqse.check.framework.core.CheckException;
008import eu.cqse.check.framework.scanner.IToken;
009
010/**
011 * Base class for checks which find unwanted expressions in any comment in a
012 * resource.
013 */
014public abstract class UnwantedExpressionInCommentCheckBase extends CommentCheckBase {
015
016        /** Stores the unwanted expression regex. */
017        private Pattern unwantedRegex;
018
019        /** {@inheritDoc} */
020        @Override
021        public void initialize() throws CheckException {
022                super.initialize();
023                unwantedRegex = getUnwantedRegex();
024        }
025
026        /** {@inheritDoc} */
027        @Override
028        protected void processComment(IToken token, int startLine, int endLine) throws CheckException {
029                Matcher commentMatcher = unwantedRegex.matcher(token.getText());
030
031                // The pattern might appear anywhere in the token text. Therefore, we
032                // use find() instead of matches() to search for it.
033                if (commentMatcher.find()) {
034                        createFinding(getFindingText(token, commentMatcher.toMatchResult()), startLine, endLine);
035                }
036        }
037
038        /**
039         * Provides the Regex pattern that specifies which expressions are unwanted
040         * in comments. Note that this method is only called once at the
041         * initialization of the check for performance reasons.
042         */
043        protected abstract Pattern getUnwantedRegex();
044
045        /**
046         * Gets the text for the finding.
047         *
048         * @param token
049         *            The token where the unwanted pattern was found.
050         * @param matchResult
051         *            The {@link MatchResult} which allows providing more details in
052         *            the findings text.
053         * @return The finding text.
054         */
055        protected abstract String getFindingText(IToken token, MatchResult matchResult);
056
057}