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