001//////////////////////////////////////////////////////////////////////////////// 002// checkstyle: Checks Java source code for adherence to a set of rules. 003// Copyright (C) 2001-2021 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; 021 022import java.io.File; 023import java.io.IOException; 024import java.io.PrintWriter; 025import java.io.StringWriter; 026import java.io.UnsupportedEncodingException; 027import java.nio.charset.Charset; 028import java.nio.charset.StandardCharsets; 029import java.util.ArrayList; 030import java.util.List; 031import java.util.Locale; 032import java.util.Set; 033import java.util.SortedSet; 034import java.util.TreeSet; 035import java.util.stream.Collectors; 036import java.util.stream.Stream; 037 038import org.apache.commons.logging.Log; 039import org.apache.commons.logging.LogFactory; 040 041import com.puppycrawl.tools.checkstyle.api.AuditEvent; 042import com.puppycrawl.tools.checkstyle.api.AuditListener; 043import com.puppycrawl.tools.checkstyle.api.AutomaticBean; 044import com.puppycrawl.tools.checkstyle.api.BeforeExecutionFileFilter; 045import com.puppycrawl.tools.checkstyle.api.BeforeExecutionFileFilterSet; 046import com.puppycrawl.tools.checkstyle.api.CheckstyleException; 047import com.puppycrawl.tools.checkstyle.api.Configuration; 048import com.puppycrawl.tools.checkstyle.api.Context; 049import com.puppycrawl.tools.checkstyle.api.ExternalResourceHolder; 050import com.puppycrawl.tools.checkstyle.api.FileSetCheck; 051import com.puppycrawl.tools.checkstyle.api.FileText; 052import com.puppycrawl.tools.checkstyle.api.Filter; 053import com.puppycrawl.tools.checkstyle.api.FilterSet; 054import com.puppycrawl.tools.checkstyle.api.MessageDispatcher; 055import com.puppycrawl.tools.checkstyle.api.RootModule; 056import com.puppycrawl.tools.checkstyle.api.SeverityLevel; 057import com.puppycrawl.tools.checkstyle.api.SeverityLevelCounter; 058import com.puppycrawl.tools.checkstyle.api.Violation; 059import com.puppycrawl.tools.checkstyle.utils.CommonUtil; 060 061/** 062 * This class provides the functionality to check a set of files. 063 */ 064public class Checker extends AutomaticBean implements MessageDispatcher, RootModule { 065 066 /** Message to use when an exception occurs and should be printed as a violation. */ 067 public static final String EXCEPTION_MSG = "general.exception"; 068 069 /** Logger for Checker. */ 070 private final Log log; 071 072 /** Maintains error count. */ 073 private final SeverityLevelCounter counter = new SeverityLevelCounter( 074 SeverityLevel.ERROR); 075 076 /** Vector of listeners. */ 077 private final List<AuditListener> listeners = new ArrayList<>(); 078 079 /** Vector of fileset checks. */ 080 private final List<FileSetCheck> fileSetChecks = new ArrayList<>(); 081 082 /** The audit event before execution file filters. */ 083 private final BeforeExecutionFileFilterSet beforeExecutionFileFilters = 084 new BeforeExecutionFileFilterSet(); 085 086 /** The audit event filters. */ 087 private final FilterSet filters = new FilterSet(); 088 089 /** The basedir to strip off in file names. */ 090 private String basedir; 091 092 /** Locale country to report messages . **/ 093 private String localeCountry = Locale.getDefault().getCountry(); 094 /** Locale language to report messages . **/ 095 private String localeLanguage = Locale.getDefault().getLanguage(); 096 097 /** The factory for instantiating submodules. */ 098 private ModuleFactory moduleFactory; 099 100 /** The classloader used for loading Checkstyle module classes. */ 101 private ClassLoader moduleClassLoader; 102 103 /** The context of all child components. */ 104 private Context childContext; 105 106 /** The file extensions that are accepted. */ 107 private String[] fileExtensions = CommonUtil.EMPTY_STRING_ARRAY; 108 109 /** 110 * The severity level of any violations found by submodules. 111 * The value of this property is passed to submodules via 112 * contextualize(). 113 * 114 * <p>Note: Since the Checker is merely a container for modules 115 * it does not make sense to implement logging functionality 116 * here. Consequently Checker does not extend AbstractViolationReporter, 117 * leading to a bit of duplicated code for severity level setting. 118 */ 119 private SeverityLevel severity = SeverityLevel.ERROR; 120 121 /** Name of a charset. */ 122 private String charset = StandardCharsets.UTF_8.name(); 123 124 /** Cache file. **/ 125 private PropertyCacheFile cacheFile; 126 127 /** Controls whether exceptions should halt execution or not. */ 128 private boolean haltOnException = true; 129 130 /** The tab width for column reporting. */ 131 private int tabWidth = CommonUtil.DEFAULT_TAB_WIDTH; 132 133 /** 134 * Creates a new {@code Checker} instance. 135 * The instance needs to be contextualized and configured. 136 */ 137 public Checker() { 138 addListener(counter); 139 log = LogFactory.getLog(Checker.class); 140 } 141 142 /** 143 * Sets cache file. 144 * 145 * @param fileName the cache file. 146 * @throws IOException if there are some problems with file loading. 147 */ 148 public void setCacheFile(String fileName) throws IOException { 149 final Configuration configuration = getConfiguration(); 150 cacheFile = new PropertyCacheFile(configuration, fileName); 151 cacheFile.load(); 152 } 153 154 /** 155 * Removes before execution file filter. 156 * 157 * @param filter before execution file filter to remove. 158 */ 159 public void removeBeforeExecutionFileFilter(BeforeExecutionFileFilter filter) { 160 beforeExecutionFileFilters.removeBeforeExecutionFileFilter(filter); 161 } 162 163 /** 164 * Removes filter. 165 * 166 * @param filter filter to remove. 167 */ 168 public void removeFilter(Filter filter) { 169 filters.removeFilter(filter); 170 } 171 172 @Override 173 public void destroy() { 174 listeners.clear(); 175 fileSetChecks.clear(); 176 beforeExecutionFileFilters.clear(); 177 filters.clear(); 178 if (cacheFile != null) { 179 try { 180 cacheFile.persist(); 181 } 182 catch (IOException ex) { 183 throw new IllegalStateException("Unable to persist cache file.", ex); 184 } 185 } 186 } 187 188 /** 189 * Removes a given listener. 190 * 191 * @param listener a listener to remove 192 */ 193 public void removeListener(AuditListener listener) { 194 listeners.remove(listener); 195 } 196 197 /** 198 * Sets base directory. 199 * 200 * @param basedir the base directory to strip off in file names 201 */ 202 public void setBasedir(String basedir) { 203 this.basedir = basedir; 204 } 205 206 @Override 207 public int process(List<File> files) throws CheckstyleException { 208 if (cacheFile != null) { 209 cacheFile.putExternalResources(getExternalResourceLocations()); 210 } 211 212 // Prepare to start 213 fireAuditStarted(); 214 for (final FileSetCheck fsc : fileSetChecks) { 215 fsc.beginProcessing(charset); 216 } 217 218 final List<File> targetFiles = files.stream() 219 .filter(file -> CommonUtil.matchesFileExtension(file, fileExtensions)) 220 .collect(Collectors.toList()); 221 processFiles(targetFiles); 222 223 // Finish up 224 // It may also log!!! 225 fileSetChecks.forEach(FileSetCheck::finishProcessing); 226 227 // It may also log!!! 228 fileSetChecks.forEach(FileSetCheck::destroy); 229 230 final int errorCount = counter.getCount(); 231 fireAuditFinished(); 232 return errorCount; 233 } 234 235 /** 236 * Returns a set of external configuration resource locations which are used by all file set 237 * checks and filters. 238 * 239 * @return a set of external configuration resource locations which are used by all file set 240 * checks and filters. 241 */ 242 private Set<String> getExternalResourceLocations() { 243 return Stream.concat(fileSetChecks.stream(), filters.getFilters().stream()) 244 .filter(ExternalResourceHolder.class::isInstance) 245 .map(ExternalResourceHolder.class::cast) 246 .flatMap(resource -> resource.getExternalResourceLocations().stream()) 247 .collect(Collectors.toSet()); 248 } 249 250 /** Notify all listeners about the audit start. */ 251 private void fireAuditStarted() { 252 final AuditEvent event = new AuditEvent(this); 253 for (final AuditListener listener : listeners) { 254 listener.auditStarted(event); 255 } 256 } 257 258 /** Notify all listeners about the audit end. */ 259 private void fireAuditFinished() { 260 final AuditEvent event = new AuditEvent(this); 261 for (final AuditListener listener : listeners) { 262 listener.auditFinished(event); 263 } 264 } 265 266 /** 267 * Processes a list of files with all FileSetChecks. 268 * 269 * @param files a list of files to process. 270 * @throws CheckstyleException if error condition within Checkstyle occurs. 271 * @throws Error wraps any java.lang.Error happened during execution 272 * @noinspection ProhibitedExceptionThrown 273 */ 274 // -@cs[CyclomaticComplexity] no easy way to split this logic of processing the file 275 private void processFiles(List<File> files) throws CheckstyleException { 276 for (final File file : files) { 277 String fileName = null; 278 try { 279 fileName = file.getAbsolutePath(); 280 final long timestamp = file.lastModified(); 281 if (cacheFile != null && cacheFile.isInCache(fileName, timestamp) 282 || !acceptFileStarted(fileName)) { 283 continue; 284 } 285 if (cacheFile != null) { 286 cacheFile.put(fileName, timestamp); 287 } 288 fireFileStarted(fileName); 289 final SortedSet<Violation> fileMessages = processFile(file); 290 fireErrors(fileName, fileMessages); 291 fireFileFinished(fileName); 292 } 293 // -@cs[IllegalCatch] There is no other way to deliver filename that was under 294 // processing. See https://github.com/checkstyle/checkstyle/issues/2285 295 catch (Exception ex) { 296 if (fileName != null && cacheFile != null) { 297 cacheFile.remove(fileName); 298 } 299 300 // We need to catch all exceptions to put a reason failure (file name) in exception 301 throw new CheckstyleException("Exception was thrown while processing " 302 + file.getPath(), ex); 303 } 304 catch (Error error) { 305 if (fileName != null && cacheFile != null) { 306 cacheFile.remove(fileName); 307 } 308 309 // We need to catch all errors to put a reason failure (file name) in error 310 throw new Error("Error was thrown while processing " + file.getPath(), error); 311 } 312 } 313 } 314 315 /** 316 * Processes a file with all FileSetChecks. 317 * 318 * @param file a file to process. 319 * @return a sorted set of violations to be logged. 320 * @throws CheckstyleException if error condition within Checkstyle occurs. 321 * @noinspection ProhibitedExceptionThrown 322 */ 323 private SortedSet<Violation> processFile(File file) throws CheckstyleException { 324 final SortedSet<Violation> fileMessages = new TreeSet<>(); 325 try { 326 final FileText theText = new FileText(file.getAbsoluteFile(), charset); 327 for (final FileSetCheck fsc : fileSetChecks) { 328 fileMessages.addAll(fsc.process(file, theText)); 329 } 330 } 331 catch (final IOException ioe) { 332 log.debug("IOException occurred.", ioe); 333 fileMessages.add(new Violation(1, 334 Definitions.CHECKSTYLE_BUNDLE, EXCEPTION_MSG, 335 new String[] {ioe.getMessage()}, null, getClass(), null)); 336 } 337 // -@cs[IllegalCatch] There is no other way to obey haltOnException field 338 catch (Exception ex) { 339 if (haltOnException) { 340 throw ex; 341 } 342 343 log.debug("Exception occurred.", ex); 344 345 final StringWriter sw = new StringWriter(); 346 final PrintWriter pw = new PrintWriter(sw, true); 347 348 ex.printStackTrace(pw); 349 350 fileMessages.add(new Violation(1, 351 Definitions.CHECKSTYLE_BUNDLE, EXCEPTION_MSG, 352 new String[] {sw.getBuffer().toString()}, 353 null, getClass(), null)); 354 } 355 return fileMessages; 356 } 357 358 /** 359 * Check if all before execution file filters accept starting the file. 360 * 361 * @param fileName 362 * the file to be audited 363 * @return {@code true} if the file is accepted. 364 */ 365 private boolean acceptFileStarted(String fileName) { 366 final String stripped = CommonUtil.relativizeAndNormalizePath(basedir, fileName); 367 return beforeExecutionFileFilters.accept(stripped); 368 } 369 370 /** 371 * Notify all listeners about the beginning of a file audit. 372 * 373 * @param fileName 374 * the file to be audited 375 */ 376 @Override 377 public void fireFileStarted(String fileName) { 378 final String stripped = CommonUtil.relativizeAndNormalizePath(basedir, fileName); 379 final AuditEvent event = new AuditEvent(this, stripped); 380 for (final AuditListener listener : listeners) { 381 listener.fileStarted(event); 382 } 383 } 384 385 /** 386 * Notify all listeners about the errors in a file. 387 * 388 * @param fileName the audited file 389 * @param errors the audit errors from the file 390 */ 391 @Override 392 public void fireErrors(String fileName, SortedSet<Violation> errors) { 393 final String stripped = CommonUtil.relativizeAndNormalizePath(basedir, fileName); 394 boolean hasNonFilteredViolations = false; 395 for (final Violation element : errors) { 396 final AuditEvent event = new AuditEvent(this, stripped, element); 397 if (filters.accept(event)) { 398 hasNonFilteredViolations = true; 399 for (final AuditListener listener : listeners) { 400 listener.addError(event); 401 } 402 } 403 } 404 if (hasNonFilteredViolations && cacheFile != null) { 405 cacheFile.remove(fileName); 406 } 407 } 408 409 /** 410 * Notify all listeners about the end of a file audit. 411 * 412 * @param fileName 413 * the audited file 414 */ 415 @Override 416 public void fireFileFinished(String fileName) { 417 final String stripped = CommonUtil.relativizeAndNormalizePath(basedir, fileName); 418 final AuditEvent event = new AuditEvent(this, stripped); 419 for (final AuditListener listener : listeners) { 420 listener.fileFinished(event); 421 } 422 } 423 424 @Override 425 protected void finishLocalSetup() throws CheckstyleException { 426 final Locale locale = new Locale(localeLanguage, localeCountry); 427 Violation.setLocale(locale); 428 429 if (moduleFactory == null) { 430 if (moduleClassLoader == null) { 431 throw new CheckstyleException( 432 "if no custom moduleFactory is set, " 433 + "moduleClassLoader must be specified"); 434 } 435 436 final Set<String> packageNames = PackageNamesLoader 437 .getPackageNames(moduleClassLoader); 438 moduleFactory = new PackageObjectFactory(packageNames, 439 moduleClassLoader); 440 } 441 442 final DefaultContext context = new DefaultContext(); 443 context.add("charset", charset); 444 context.add("moduleFactory", moduleFactory); 445 context.add("severity", severity.getName()); 446 context.add("basedir", basedir); 447 context.add("tabWidth", String.valueOf(tabWidth)); 448 childContext = context; 449 } 450 451 /** 452 * {@inheritDoc} Creates child module. 453 * 454 * @noinspection ChainOfInstanceofChecks 455 */ 456 @Override 457 protected void setupChild(Configuration childConf) 458 throws CheckstyleException { 459 final String name = childConf.getName(); 460 final Object child; 461 462 try { 463 child = moduleFactory.createModule(name); 464 465 if (child instanceof AutomaticBean) { 466 final AutomaticBean bean = (AutomaticBean) child; 467 bean.contextualize(childContext); 468 bean.configure(childConf); 469 } 470 } 471 catch (final CheckstyleException ex) { 472 throw new CheckstyleException("cannot initialize module " + name 473 + " - " + ex.getMessage(), ex); 474 } 475 if (child instanceof FileSetCheck) { 476 final FileSetCheck fsc = (FileSetCheck) child; 477 fsc.init(); 478 addFileSetCheck(fsc); 479 } 480 else if (child instanceof BeforeExecutionFileFilter) { 481 final BeforeExecutionFileFilter filter = (BeforeExecutionFileFilter) child; 482 addBeforeExecutionFileFilter(filter); 483 } 484 else if (child instanceof Filter) { 485 final Filter filter = (Filter) child; 486 addFilter(filter); 487 } 488 else if (child instanceof AuditListener) { 489 final AuditListener listener = (AuditListener) child; 490 addListener(listener); 491 } 492 else { 493 throw new CheckstyleException(name 494 + " is not allowed as a child in Checker"); 495 } 496 } 497 498 /** 499 * Adds a FileSetCheck to the list of FileSetChecks 500 * that is executed in process(). 501 * 502 * @param fileSetCheck the additional FileSetCheck 503 */ 504 public void addFileSetCheck(FileSetCheck fileSetCheck) { 505 fileSetCheck.setMessageDispatcher(this); 506 fileSetChecks.add(fileSetCheck); 507 } 508 509 /** 510 * Adds a before execution file filter to the end of the event chain. 511 * 512 * @param filter the additional filter 513 */ 514 public void addBeforeExecutionFileFilter(BeforeExecutionFileFilter filter) { 515 beforeExecutionFileFilters.addBeforeExecutionFileFilter(filter); 516 } 517 518 /** 519 * Adds a filter to the end of the audit event filter chain. 520 * 521 * @param filter the additional filter 522 */ 523 public void addFilter(Filter filter) { 524 filters.addFilter(filter); 525 } 526 527 @Override 528 public final void addListener(AuditListener listener) { 529 listeners.add(listener); 530 } 531 532 /** 533 * Sets the file extensions that identify the files that pass the 534 * filter of this FileSetCheck. 535 * 536 * @param extensions the set of file extensions. A missing 537 * initial '.' character of an extension is automatically added. 538 */ 539 public final void setFileExtensions(String... extensions) { 540 if (extensions == null) { 541 fileExtensions = null; 542 } 543 else { 544 fileExtensions = new String[extensions.length]; 545 for (int i = 0; i < extensions.length; i++) { 546 final String extension = extensions[i]; 547 if (CommonUtil.startsWithChar(extension, '.')) { 548 fileExtensions[i] = extension; 549 } 550 else { 551 fileExtensions[i] = "." + extension; 552 } 553 } 554 } 555 } 556 557 /** 558 * Sets the factory for creating submodules. 559 * 560 * @param moduleFactory the factory for creating FileSetChecks 561 */ 562 public void setModuleFactory(ModuleFactory moduleFactory) { 563 this.moduleFactory = moduleFactory; 564 } 565 566 /** 567 * Sets locale country. 568 * 569 * @param localeCountry the country to report messages 570 */ 571 public void setLocaleCountry(String localeCountry) { 572 this.localeCountry = localeCountry; 573 } 574 575 /** 576 * Sets locale language. 577 * 578 * @param localeLanguage the language to report messages 579 */ 580 public void setLocaleLanguage(String localeLanguage) { 581 this.localeLanguage = localeLanguage; 582 } 583 584 /** 585 * Sets the severity level. The string should be one of the names 586 * defined in the {@code SeverityLevel} class. 587 * 588 * @param severity The new severity level 589 * @see SeverityLevel 590 */ 591 public final void setSeverity(String severity) { 592 this.severity = SeverityLevel.getInstance(severity); 593 } 594 595 @Override 596 public final void setModuleClassLoader(ClassLoader moduleClassLoader) { 597 this.moduleClassLoader = moduleClassLoader; 598 } 599 600 /** 601 * Sets a named charset. 602 * 603 * @param charset the name of a charset 604 * @throws UnsupportedEncodingException if charset is unsupported. 605 */ 606 public void setCharset(String charset) 607 throws UnsupportedEncodingException { 608 if (!Charset.isSupported(charset)) { 609 final String message = "unsupported charset: '" + charset + "'"; 610 throw new UnsupportedEncodingException(message); 611 } 612 this.charset = charset; 613 } 614 615 /** 616 * Sets the field haltOnException. 617 * 618 * @param haltOnException the new value. 619 */ 620 public void setHaltOnException(boolean haltOnException) { 621 this.haltOnException = haltOnException; 622 } 623 624 /** 625 * Set the tab width to report audit events with. 626 * 627 * @param tabWidth an {@code int} value 628 */ 629 public final void setTabWidth(int tabWidth) { 630 this.tabWidth = tabWidth; 631 } 632 633 /** 634 * Clears the cache. 635 */ 636 public void clearCache() { 637 if (cacheFile != null) { 638 cacheFile.reset(); 639 } 640 } 641 642}