001////////////////////////////////////////////////////////////////////////////////
002// checkstyle: Checks Java source code for adherence to a set of rules.
003// Copyright (C) 2001-2017 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;
021
022import java.io.File;
023import java.io.IOException;
024import java.io.RandomAccessFile;
025import java.util.List;
026import java.util.Locale;
027
028import org.apache.commons.beanutils.ConversionException;
029
030import com.google.common.io.Closeables;
031import com.puppycrawl.tools.checkstyle.api.AbstractFileSetCheck;
032
033/**
034 * <p>
035 * Checks that there is a newline at the end of each file.
036 * </p>
037 * <p>
038 * An example of how to configure the check is:
039 * </p>
040 * <pre>
041 * &lt;module name="NewlineAtEndOfFile"/&gt;</pre>
042 * <p>
043 * This will check against the platform-specific default line separator.
044 * </p>
045 * <p>
046 * It is also possible to enforce the use of a specific line-separator across
047 * platforms, with the 'lineSeparator' property:
048 * </p>
049 * <pre>
050 * &lt;module name="NewlineAtEndOfFile"&gt;
051 *   &lt;property name="lineSeparator" value="lf"/&gt;
052 * &lt;/module&gt;</pre>
053 * <p>
054 * Valid values for the 'lineSeparator' property are 'system' (system default),
055 * 'crlf' (windows), 'cr' (mac), 'lf' (unix) and 'lf_cr_crlf' (lf, cr or crlf).
056 * </p>
057 *
058 * @author Christopher Lenz
059 * @author lkuehne
060 */
061public class NewlineAtEndOfFileCheck
062    extends AbstractFileSetCheck {
063
064    /**
065     * A key is pointing to the warning message text in "messages.properties"
066     * file.
067     */
068    public static final String MSG_KEY_UNABLE_OPEN = "unable.open";
069
070    /**
071     * A key is pointing to the warning message text in "messages.properties"
072     * file.
073     */
074    public static final String MSG_KEY_NO_NEWLINE_EOF = "noNewlineAtEOF";
075
076    /** The line separator to check against. */
077    private LineSeparatorOption lineSeparator = LineSeparatorOption.SYSTEM;
078
079    @Override
080    protected void processFiltered(File file, List<String> lines) {
081        // Cannot use lines as the line separators have been removed!
082        try {
083            final RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r");
084            boolean threw = true;
085            try {
086                if (!endsWithNewline(randomAccessFile)) {
087                    log(0, MSG_KEY_NO_NEWLINE_EOF, file.getPath());
088                }
089                threw = false;
090            }
091            finally {
092                Closeables.close(randomAccessFile, threw);
093            }
094        }
095        catch (final IOException ignored) {
096            log(0, MSG_KEY_UNABLE_OPEN, file.getPath());
097        }
098    }
099
100    /**
101     * Sets the line separator to one of 'crlf', 'lf','cr', 'lf_cr_crlf' or 'system'.
102     *
103     * @param lineSeparatorParam The line separator to set
104     * @throws IllegalArgumentException If the specified line separator is not
105     *         one of 'crlf', 'lf', 'cr', 'lf_cr_crlf' or 'system'
106     */
107    public void setLineSeparator(String lineSeparatorParam) {
108        try {
109            lineSeparator =
110                Enum.valueOf(LineSeparatorOption.class, lineSeparatorParam.trim()
111                    .toUpperCase(Locale.ENGLISH));
112        }
113        catch (IllegalArgumentException iae) {
114            throw new ConversionException("unable to parse " + lineSeparatorParam,
115                iae);
116        }
117    }
118
119    /**
120     * Checks whether the content provided by the Reader ends with the platform
121     * specific line separator.
122     * @param randomAccessFile The reader for the content to check
123     * @return boolean Whether the content ends with a line separator
124     * @throws IOException When an IO error occurred while reading from the
125     *         provided reader
126     */
127    private boolean endsWithNewline(RandomAccessFile randomAccessFile)
128            throws IOException {
129        final int len = lineSeparator.length();
130        if (randomAccessFile.length() < len) {
131            return false;
132        }
133        randomAccessFile.seek(randomAccessFile.length() - len);
134        final byte[] lastBytes = new byte[len];
135        final int readBytes = randomAccessFile.read(lastBytes);
136        if (readBytes != len) {
137            throw new IOException("Unable to read " + len + " bytes, got "
138                    + readBytes);
139        }
140        return lineSeparator.matches(lastBytes);
141    }
142}