001////////////////////////////////////////////////////////////////////////////////
002// checkstyle: Checks Java source code for adherence to a set of rules.
003// Copyright (C) 2001-2016 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.BufferedInputStream;
023import java.io.IOException;
024import java.io.InputStreamReader;
025import java.io.LineNumberReader;
026import java.io.Reader;
027import java.io.StringReader;
028import java.io.UnsupportedEncodingException;
029import java.net.URI;
030import java.nio.charset.Charset;
031import java.util.List;
032import java.util.regex.Pattern;
033
034import org.apache.commons.beanutils.ConversionException;
035import org.apache.commons.lang3.StringUtils;
036
037import com.google.common.collect.ImmutableList;
038import com.google.common.collect.Lists;
039import com.google.common.io.Closeables;
040import com.puppycrawl.tools.checkstyle.api.AbstractFileSetCheck;
041import com.puppycrawl.tools.checkstyle.api.CheckstyleException;
042import com.puppycrawl.tools.checkstyle.utils.CommonUtils;
043
044/**
045 * Abstract super class for header checks.
046 * Provides support for header and headerFile properties.
047 * @author o_sukhosolsky
048 */
049public abstract class AbstractHeaderCheck extends AbstractFileSetCheck {
050    /** Pattern to detect occurrences of '\n' in text. */
051    private static final Pattern ESCAPED_LINE_FEED_PATTERN = Pattern.compile("\\\\n");
052
053    /** The lines of the header file. */
054    private final List<String> readerLines = Lists.newArrayList();
055
056    /** The file that contains the header to check against. */
057    private String headerFile;
058
059    /** Name of a charset to use for loading the header from a file. */
060    private String charset = System.getProperty("file.encoding", "UTF-8");
061
062    /**
063     * Hook method for post processing header lines.
064     * This implementation does nothing.
065     */
066    protected abstract void postProcessHeaderLines();
067
068    /**
069     * Return the header lines to check against.
070     * @return the header lines to check against.
071     */
072    protected ImmutableList<String> getHeaderLines() {
073        return ImmutableList.copyOf(readerLines);
074    }
075
076    /**
077     * Set the charset to use for loading the header from a file.
078     * @param charset the charset to use for loading the header from a file
079     * @throws UnsupportedEncodingException if charset is unsupported
080     */
081    public void setCharset(String charset) throws UnsupportedEncodingException {
082        if (!Charset.isSupported(charset)) {
083            final String message = "unsupported charset: '" + charset + "'";
084            throw new UnsupportedEncodingException(message);
085        }
086        this.charset = charset;
087    }
088
089    /**
090     * Set the header file to check against.
091     * @param fileName the file that contains the header to check against.
092     * @throws CheckstyleException if fileName is empty.
093     */
094    public void setHeaderFile(String fileName) throws CheckstyleException {
095        if (StringUtils.isBlank(fileName)) {
096            throw new CheckstyleException(
097                "property 'headerFile' is missing or invalid in module "
098                    + getConfiguration().getName());
099        }
100
101        headerFile = fileName;
102    }
103
104    /**
105     * Load the header from a file.
106     * @throws CheckstyleException if the file cannot be loaded
107     */
108    private void loadHeaderFile() throws CheckstyleException {
109        checkHeaderNotInitialized();
110        Reader headerReader = null;
111        try {
112            final URI uri = CommonUtils.getUriByFilename(headerFile);
113            headerReader = new InputStreamReader(new BufferedInputStream(
114                    uri.toURL().openStream()), charset);
115            loadHeader(headerReader);
116        }
117        catch (final IOException ex) {
118            throw new CheckstyleException(
119                    "unable to load header file " + headerFile, ex);
120        }
121        finally {
122            Closeables.closeQuietly(headerReader);
123        }
124    }
125
126    /**
127     * Called before initializing the header.
128     * @throws ConversionException if header has already been set
129     */
130    private void checkHeaderNotInitialized() {
131        if (!readerLines.isEmpty()) {
132            throw new ConversionException(
133                    "header has already been set - "
134                    + "set either header or headerFile, not both");
135        }
136    }
137
138    /**
139     * Set the header to check against. Individual lines in the header
140     * must be separated by '\n' characters.
141     * @param header header content to check against.
142     * @throws ConversionException if the header cannot be interpreted
143     */
144    public void setHeader(String header) {
145        if (StringUtils.isBlank(header)) {
146            return;
147        }
148
149        checkHeaderNotInitialized();
150
151        final String headerExpandedNewLines = ESCAPED_LINE_FEED_PATTERN
152                .matcher(header).replaceAll("\n");
153
154        final Reader headerReader = new StringReader(headerExpandedNewLines);
155        try {
156            loadHeader(headerReader);
157        }
158        catch (final IOException ex) {
159            throw new ConversionException("unable to load header", ex);
160        }
161        finally {
162            Closeables.closeQuietly(headerReader);
163        }
164    }
165
166    /**
167     * Load header to check against from a Reader into readerLines.
168     * @param headerReader delivers the header to check against
169     * @throws IOException if
170     */
171    private void loadHeader(final Reader headerReader) throws IOException {
172        final LineNumberReader lnr = new LineNumberReader(headerReader);
173        readerLines.clear();
174        while (true) {
175            final String line = lnr.readLine();
176            if (line == null) {
177                break;
178            }
179            readerLines.add(line);
180        }
181        postProcessHeaderLines();
182    }
183
184    @Override
185    protected final void finishLocalSetup() throws CheckstyleException {
186        if (headerFile != null) {
187            loadHeaderFile();
188        }
189        if (readerLines.isEmpty()) {
190            setHeader(null);
191        }
192    }
193}