001//////////////////////////////////////////////////////////////////////////////// 002// checkstyle: Checks Java source code for adherence to a set of rules. 003// Copyright (C) 2001-2019 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.api; 021 022import java.io.BufferedReader; 023import java.io.File; 024import java.io.FileNotFoundException; 025import java.io.IOException; 026import java.io.InputStream; 027import java.io.InputStreamReader; 028import java.io.Reader; 029import java.io.StringReader; 030import java.nio.charset.Charset; 031import java.nio.charset.CharsetDecoder; 032import java.nio.charset.CodingErrorAction; 033import java.nio.charset.UnsupportedCharsetException; 034import java.nio.file.Files; 035import java.util.ArrayList; 036import java.util.Arrays; 037import java.util.List; 038import java.util.regex.Matcher; 039import java.util.regex.Pattern; 040 041import com.puppycrawl.tools.checkstyle.utils.CommonUtil; 042 043/** 044 * Represents the text contents of a file of arbitrary plain text type. 045 * <p> 046 * This class will be passed to instances of class FileSetCheck by 047 * Checker. 048 * </p> 049 * 050 */ 051public final class FileText { 052 053 /** 054 * The number of characters to read in one go. 055 */ 056 private static final int READ_BUFFER_SIZE = 1024; 057 058 /** 059 * Regular expression pattern matching all line terminators. 060 */ 061 private static final Pattern LINE_TERMINATOR = Pattern.compile("\\n|\\r\\n?"); 062 063 // For now, we always keep both full text and lines array. 064 // In the long run, however, the one passed at initialization might be 065 // enough, while the other could be lazily created when requested. 066 // This would save memory but cost CPU cycles. 067 068 /** 069 * The name of the file. 070 * {@code null} if no file name is available for whatever reason. 071 */ 072 private final File file; 073 074 /** 075 * The charset used to read the file. 076 * {@code null} if the file was reconstructed from a list of lines. 077 */ 078 private final Charset charset; 079 080 /** 081 * The lines of the file, without terminators. 082 */ 083 private final String[] lines; 084 085 /** 086 * The full text contents of the file. 087 * 088 * <p>Field is not final to ease reaching full test coverage. 089 * @noinspection FieldMayBeFinal 090 */ 091 private String fullText; 092 093 /** 094 * The first position of each line within the full text. 095 */ 096 private int[] lineBreaks; 097 098 /** 099 * Creates a new file text representation. 100 * 101 * <p>The file will be read using the specified encoding, replacing 102 * malformed input and unmappable characters with the default 103 * replacement character. 104 * 105 * @param file the name of the file 106 * @param charsetName the encoding to use when reading the file 107 * @throws NullPointerException if the text is null 108 * @throws IOException if the file could not be read 109 */ 110 public FileText(File file, String charsetName) throws IOException { 111 this.file = file; 112 113 // We use our own decoder, to be sure we have complete control 114 // about replacements. 115 final CharsetDecoder decoder; 116 try { 117 charset = Charset.forName(charsetName); 118 decoder = charset.newDecoder(); 119 decoder.onMalformedInput(CodingErrorAction.REPLACE); 120 decoder.onUnmappableCharacter(CodingErrorAction.REPLACE); 121 } 122 catch (final UnsupportedCharsetException ex) { 123 final String message = "Unsupported charset: " + charsetName; 124 throw new IllegalStateException(message, ex); 125 } 126 127 fullText = readFile(file, decoder); 128 129 // Use the BufferedReader to break down the lines as this 130 // is about 30% faster than using the 131 // LINE_TERMINATOR.split(fullText, -1) method 132 try (BufferedReader reader = new BufferedReader(new StringReader(fullText))) { 133 final ArrayList<String> textLines = new ArrayList<>(); 134 while (true) { 135 final String line = reader.readLine(); 136 if (line == null) { 137 break; 138 } 139 textLines.add(line); 140 } 141 lines = textLines.toArray(CommonUtil.EMPTY_STRING_ARRAY); 142 } 143 } 144 145 /** 146 * Copy constructor. 147 * @param fileText to make copy of 148 */ 149 public FileText(FileText fileText) { 150 file = fileText.file; 151 charset = fileText.charset; 152 fullText = fileText.fullText; 153 lines = fileText.lines.clone(); 154 if (fileText.lineBreaks == null) { 155 lineBreaks = null; 156 } 157 else { 158 lineBreaks = fileText.lineBreaks.clone(); 159 } 160 } 161 162 /** 163 * Compatibility constructor. 164 * 165 * <p>This constructor reconstructs the text of the file by joining 166 * lines with linefeed characters. This process does not restore 167 * the original line terminators and should therefore be avoided. 168 * 169 * @param file the name of the file 170 * @param lines the lines of the text, without terminators 171 * @throws NullPointerException if the lines array is null 172 */ 173 public FileText(File file, List<String> lines) { 174 final StringBuilder buf = new StringBuilder(1024); 175 for (final String line : lines) { 176 buf.append(line).append('\n'); 177 } 178 179 this.file = file; 180 charset = null; 181 fullText = buf.toString(); 182 this.lines = lines.toArray(CommonUtil.EMPTY_STRING_ARRAY); 183 } 184 185 /** 186 * Reads file using specific decoder and returns all its content as a String. 187 * @param inputFile File to read 188 * @param decoder Charset decoder 189 * @return File's text 190 * @throws IOException Unable to open or read the file 191 */ 192 private static String readFile(final File inputFile, final CharsetDecoder decoder) 193 throws IOException { 194 if (!inputFile.exists()) { 195 throw new FileNotFoundException(inputFile.getPath() + " (No such file or directory)"); 196 } 197 final StringBuilder buf = new StringBuilder(1024); 198 final InputStream stream = Files.newInputStream(inputFile.toPath()); 199 try (Reader reader = new InputStreamReader(stream, decoder)) { 200 final char[] chars = new char[READ_BUFFER_SIZE]; 201 while (true) { 202 final int len = reader.read(chars); 203 if (len == -1) { 204 break; 205 } 206 buf.append(chars, 0, len); 207 } 208 } 209 return buf.toString(); 210 } 211 212 /** 213 * Get the name of the file. 214 * @return an object containing the name of the file 215 */ 216 public File getFile() { 217 return file; 218 } 219 220 /** 221 * Get the character set which was used to read the file. 222 * Will be {@code null} for a file reconstructed from its lines. 223 * @return the charset used when the file was read 224 */ 225 public Charset getCharset() { 226 return charset; 227 } 228 229 /** 230 * Retrieve the full text of the file. 231 * @return the full text of the file 232 */ 233 public CharSequence getFullText() { 234 return fullText; 235 } 236 237 /** 238 * Returns an array of all lines. 239 * {@code text.toLinesArray()} is equivalent to 240 * {@code text.toArray(new String[text.size()])}. 241 * @return an array of all lines of the text 242 */ 243 public String[] toLinesArray() { 244 return lines.clone(); 245 } 246 247 /** 248 * Find positions of line breaks in the full text. 249 * @return an array giving the first positions of each line. 250 */ 251 private int[] findLineBreaks() { 252 if (lineBreaks == null) { 253 final int[] lineBreakPositions = new int[size() + 1]; 254 lineBreakPositions[0] = 0; 255 int lineNo = 1; 256 final Matcher matcher = LINE_TERMINATOR.matcher(fullText); 257 while (matcher.find()) { 258 lineBreakPositions[lineNo] = matcher.end(); 259 lineNo++; 260 } 261 if (lineNo < lineBreakPositions.length) { 262 lineBreakPositions[lineNo] = fullText.length(); 263 } 264 lineBreaks = lineBreakPositions; 265 } 266 return lineBreaks; 267 } 268 269 /** 270 * Determine line and column numbers in full text. 271 * @param pos the character position in the full text 272 * @return the line and column numbers of this character 273 */ 274 public LineColumn lineColumn(int pos) { 275 final int[] lineBreakPositions = findLineBreaks(); 276 int lineNo = Arrays.binarySearch(lineBreakPositions, pos); 277 if (lineNo < 0) { 278 // we have: lineNo = -(insertion point) - 1 279 // we want: lineNo = (insertion point) - 1 280 lineNo = -lineNo - 2; 281 } 282 final int startOfLine = lineBreakPositions[lineNo]; 283 final int columnNo = pos - startOfLine; 284 // now we have lineNo and columnNo, both starting at zero. 285 return new LineColumn(lineNo + 1, columnNo); 286 } 287 288 /** 289 * Retrieves a line of the text by its number. 290 * The returned line will not contain a trailing terminator. 291 * @param lineNo the number of the line to get, starting at zero 292 * @return the line with the given number 293 */ 294 public String get(final int lineNo) { 295 return lines[lineNo]; 296 } 297 298 /** 299 * Counts the lines of the text. 300 * @return the number of lines in the text 301 */ 302 public int size() { 303 return lines.length; 304 } 305 306}