001////////////////////////////////////////////////////////////////////////////////
002// checkstyle: Checks Java source code for adherence to a set of rules.
003// Copyright (C) 2001-2015 the original author or authors.
004//
005// This library is free software; you can redistribute it and/or
006// modify it under the terms of the GNU Lesser General Public
007// License as published by the Free Software Foundation; either
008// version 2.1 of the License, or (at your option) any later version.
009//
010// This library is distributed in the hope that it will be useful,
011// but WITHOUT ANY WARRANTY; without even the implied warranty of
012// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
013// Lesser General Public License for more details.
014//
015// You should have received a copy of the GNU Lesser General Public
016// License along with this library; if not, write to the Free Software
017// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
018////////////////////////////////////////////////////////////////////////////////
019
020package com.puppycrawl.tools.checkstyle.checks.header;
021
022import java.io.File;
023import java.util.Arrays;
024import java.util.List;
025import java.util.regex.Pattern;
026import java.util.regex.PatternSyntaxException;
027
028import org.apache.commons.beanutils.ConversionException;
029import org.apache.commons.lang3.StringUtils;
030
031import com.google.common.collect.Lists;
032import com.puppycrawl.tools.checkstyle.utils.CommonUtils;
033
034/**
035 * Checks the header of the source against a header file that contains a
036 * {@link Pattern regular expression}
037 * for each line of the source header. In default configuration,
038 * if header is not specified, the default value of header is set to null
039 * and the check does not rise any violations.
040 *
041 * @author Lars Kühne
042 * @author o_sukhodolsky
043 */
044public class RegexpHeaderCheck extends AbstractHeaderCheck {
045    /** Empty array to avoid instantiations. */
046    private static final int[] EMPTY_INT_ARRAY = new int[0];
047
048    /**
049     * A key is pointing to the warning message text in "messages.properties"
050     * file.
051     */
052    private static final String MSG_HEADER_MISSING = "header.missing";
053
054    /**
055     * A key is pointing to the warning message text in "messages.properties"
056     * file.
057     */
058    private static final String MSG_HEADER_MISMATCH = "header.mismatch";
059
060    /** The compiled regular expressions. */
061    private final List<Pattern> headerRegexps = Lists.newArrayList();
062
063    /** The header lines to repeat (0 or more) in the check, sorted. */
064    private int[] multiLines = EMPTY_INT_ARRAY;
065
066    /**
067     * Set the lines numbers to repeat in the header check.
068     * @param list comma separated list of line numbers to repeat in header.
069     */
070    public void setMultiLines(int... list) {
071        if (list.length == 0) {
072            multiLines = EMPTY_INT_ARRAY;
073            return;
074        }
075
076        multiLines = new int[list.length];
077        System.arraycopy(list, 0, multiLines, 0, list.length);
078        Arrays.sort(multiLines);
079    }
080
081    @Override
082    protected void processFiltered(File file, List<String> lines) {
083        final int headerSize = getHeaderLines().size();
084        final int fileSize = lines.size();
085
086        if (headerSize - multiLines.length > fileSize) {
087            log(1, MSG_HEADER_MISSING);
088        }
089        else {
090            int headerLineNo = 0;
091            int index;
092            for (index = 0; headerLineNo < headerSize && index < fileSize; index++) {
093                final String line = lines.get(index);
094                boolean isMatch = isMatch(line, headerLineNo);
095                while (!isMatch && isMultiLine(headerLineNo)) {
096                    headerLineNo++;
097                    isMatch = headerLineNo == headerSize
098                            || isMatch(line, headerLineNo);
099                }
100                if (!isMatch) {
101                    log(index + 1, MSG_HEADER_MISMATCH, getHeaderLines().get(
102                            headerLineNo));
103                    break;
104                }
105                if (!isMultiLine(headerLineNo)) {
106                    headerLineNo++;
107                }
108            }
109            if (index == fileSize) {
110                // if file finished, but we have at least one non-multi-line
111                // header isn't completed
112                logFirstSinglelineLine(headerLineNo, headerSize);
113            }
114        }
115    }
116
117    /**
118     * Logs warning if any non-multiline lines left in header regexp.
119     * @param startHeaderLine header line number to start from
120     * @param headerSize whole header size
121     */
122    private void logFirstSinglelineLine(int startHeaderLine, int headerSize) {
123        for (int lineNum = startHeaderLine; lineNum < headerSize; lineNum++) {
124            if (!isMultiLine(lineNum)) {
125                log(1, MSG_HEADER_MISSING);
126                break;
127            }
128        }
129    }
130
131    /**
132     * Checks if a code line matches the required header line.
133     * @param line the code line
134     * @param headerLineNo the header line number.
135     * @return true if and only if the line matches the required header line.
136     */
137    private boolean isMatch(String line, int headerLineNo) {
138        return headerRegexps.get(headerLineNo).matcher(line).find();
139    }
140
141    /**
142     * @param lineNo a line number
143     * @return if {@code lineNo} is one of the repeat header lines.
144     */
145    private boolean isMultiLine(int lineNo) {
146        return Arrays.binarySearch(multiLines, lineNo + 1) >= 0;
147    }
148
149    @Override
150    protected void postProcessHeaderLines() {
151        final List<String> headerLines = getHeaderLines();
152        headerRegexps.clear();
153        for (String line : headerLines) {
154            try {
155                headerRegexps.add(Pattern.compile(line));
156            }
157            catch (final PatternSyntaxException ex) {
158                throw new ConversionException("line "
159                        + (headerRegexps.size() + 1)
160                        + " in header specification"
161                        + " is not a regular expression", ex);
162            }
163        }
164    }
165
166    /**
167     * Validates the {@code header} by compiling it with
168     * {@link Pattern#compile(String) } and throws
169     * {@link PatternSyntaxException} if {@code header} isn't a valid pattern.
170     * @param header the header value to validate and set (in that order)
171     */
172    @Override
173    public void setHeader(String header) {
174        if (StringUtils.isBlank(header)) {
175            return;
176        }
177        if (!CommonUtils.isPatternValid(header)) {
178            throw new ConversionException("Unable to parse format: " + header);
179        }
180        super.setHeader(header);
181    }
182
183}