1 package com.puppycrawl.tools.checkstyle.checks; 20 21 import java.io.File ; 22 import java.io.FileNotFoundException ; 23 import java.io.IOException ; 24 import java.io.RandomAccessFile ; 25 26 import com.puppycrawl.tools.checkstyle.Defn; 27 import com.puppycrawl.tools.checkstyle.api.AbstractFileSetCheck; 28 import com.puppycrawl.tools.checkstyle.api.LocalizedMessage; 29 import com.puppycrawl.tools.checkstyle.api.MessageDispatcher; 30 import com.puppycrawl.tools.checkstyle.api.Utils; 31 import org.apache.commons.beanutils.ConversionException; 32 33 62 public class NewlineAtEndOfFileCheck 63 extends AbstractFileSetCheck 64 { 65 66 private LineSeparatorOption mLineSeparator = 67 LineSeparatorOption.SYSTEM; 68 69 72 public void process(File [] aFiles) 73 { 74 final File [] files = filter(aFiles); 75 final MessageDispatcher dispatcher = getMessageDispatcher(); 76 for (int i = 0; i < files.length; i++) { 77 final File file = files[i]; 78 final String path = file.getPath(); 79 dispatcher.fireFileStarted(path); 80 RandomAccessFile randomAccessFile = null; 81 try { 82 randomAccessFile = new RandomAccessFile (file, "r"); 83 if (!endsWithNewline(randomAccessFile)) { 84 log(0, "noNewlineAtEOF", path); 85 } 86 } 87 catch (final IOException e) { 88 logIOException(e); 90 } 92 finally { 93 if (randomAccessFile != null) { 94 try { 95 randomAccessFile.close(); 96 } 97 catch (final IOException e) { 98 logIOException(e); 100 } 102 } 103 } 104 fireErrors(path); 105 dispatcher.fireFileFinished(path); 106 } 107 } 108 109 116 public void setLineSeparator(String aLineSeparator) 117 { 118 final AbstractOption option = 119 LineSeparatorOption.SYSTEM.decode(aLineSeparator); 120 121 if (option == null) { 122 throw new ConversionException("unable to parse " + aLineSeparator); 123 } 124 125 mLineSeparator = (LineSeparatorOption) option; 126 } 127 128 136 private boolean endsWithNewline(RandomAccessFile aRandomAccessFile) 137 throws IOException 138 { 139 final int len = mLineSeparator.length(); 140 if (aRandomAccessFile.length() < len) { 141 return false; 142 } 143 aRandomAccessFile.seek(aRandomAccessFile.length() - len); 144 final byte lastBytes[] = new byte[len]; 145 aRandomAccessFile.read(lastBytes); 146 return mLineSeparator.matches(lastBytes); 147 } 148 149 153 private void logIOException(IOException aEx) 155 { 156 String [] args = null; 157 String key = "general.fileNotFound"; 158 if (!(aEx instanceof FileNotFoundException )) { 159 args = new String [] {aEx.getMessage()}; 160 key = "general.exception"; 161 } 162 final LocalizedMessage message = 163 new LocalizedMessage( 164 0, 165 Defn.CHECKSTYLE_BUNDLE, 166 key, 167 args, 168 getId(), 169 this.getClass()); 170 getMessageCollector().add(message); 171 Utils.getExceptionLogger().debug("IOException occured.", aEx); 172 } 173 } 175 | Popular Tags |