001///////////////////////////////////////////////////////////////////////////////////////////////
002// checkstyle: Checks Java source code and other text files 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     * @noinspectionreason ProhibitedExceptionThrown - There is no other way to
277     *      deliver filename that was under processing.
278     */
279    // -@cs[CyclomaticComplexity] no easy way to split this logic of processing the file
280    private void processFiles(List<File> files) throws CheckstyleException {
281        for (final File file : files) {
282            String fileName = null;
283            try {
284                fileName = file.getAbsolutePath();
285                final long timestamp = file.lastModified();
286                if (cacheFile != null && cacheFile.isInCache(fileName, timestamp)
287                        || !acceptFileStarted(fileName)) {
288                    continue;
289                }
290                if (cacheFile != null) {
291                    cacheFile.put(fileName, timestamp);
292                }
293                fireFileStarted(fileName);
294                final SortedSet<Violation> fileMessages = processFile(file);
295                fireErrors(fileName, fileMessages);
296                fireFileFinished(fileName);
297            }
298            // -@cs[IllegalCatch] There is no other way to deliver filename that was under
299            // processing. See https://github.com/checkstyle/checkstyle/issues/2285
300            catch (Exception ex) {
301                if (fileName != null && cacheFile != null) {
302                    cacheFile.remove(fileName);
303                }
304
305                // We need to catch all exceptions to put a reason failure (file name) in exception
306                throw new CheckstyleException("Exception was thrown while processing "
307                        + file.getPath(), ex);
308            }
309            catch (Error error) {
310                if (fileName != null && cacheFile != null) {
311                    cacheFile.remove(fileName);
312                }
313
314                // We need to catch all errors to put a reason failure (file name) in error
315                throw new Error("Error was thrown while processing " + file.getPath(), error);
316            }
317        }
318    }
319
320    /**
321     * Processes a file with all FileSetChecks.
322     *
323     * @param file a file to process.
324     * @return a sorted set of violations to be logged.
325     * @throws CheckstyleException if error condition within Checkstyle occurs.
326     * @noinspection ProhibitedExceptionThrown
327     */
328    private SortedSet<Violation> processFile(File file) throws CheckstyleException {
329        final SortedSet<Violation> fileMessages = new TreeSet<>();
330        try {
331            final FileText theText = new FileText(file.getAbsoluteFile(), charset);
332            for (final FileSetCheck fsc : fileSetChecks) {
333                fileMessages.addAll(fsc.process(file, theText));
334            }
335        }
336        catch (final IOException ioe) {
337            log.debug("IOException occurred.", ioe);
338            fileMessages.add(new Violation(1,
339                    Definitions.CHECKSTYLE_BUNDLE, EXCEPTION_MSG,
340                    new String[] {ioe.getMessage()}, null, getClass(), null));
341        }
342        // -@cs[IllegalCatch] There is no other way to obey haltOnException field
343        catch (Exception ex) {
344            if (haltOnException) {
345                throw ex;
346            }
347
348            log.debug("Exception occurred.", ex);
349
350            final StringWriter sw = new StringWriter();
351            final PrintWriter pw = new PrintWriter(sw, true);
352
353            ex.printStackTrace(pw);
354
355            fileMessages.add(new Violation(1,
356                    Definitions.CHECKSTYLE_BUNDLE, EXCEPTION_MSG,
357                    new String[] {sw.getBuffer().toString()},
358                    null, getClass(), null));
359        }
360        return fileMessages;
361    }
362
363    /**
364     * Check if all before execution file filters accept starting the file.
365     *
366     * @param fileName
367     *            the file to be audited
368     * @return {@code true} if the file is accepted.
369     */
370    private boolean acceptFileStarted(String fileName) {
371        final String stripped = CommonUtil.relativizeAndNormalizePath(basedir, fileName);
372        return beforeExecutionFileFilters.accept(stripped);
373    }
374
375    /**
376     * Notify all listeners about the beginning of a file audit.
377     *
378     * @param fileName
379     *            the file to be audited
380     */
381    @Override
382    public void fireFileStarted(String fileName) {
383        final String stripped = CommonUtil.relativizeAndNormalizePath(basedir, fileName);
384        final AuditEvent event = new AuditEvent(this, stripped);
385        for (final AuditListener listener : listeners) {
386            listener.fileStarted(event);
387        }
388    }
389
390    /**
391     * Notify all listeners about the errors in a file.
392     *
393     * @param fileName the audited file
394     * @param errors the audit errors from the file
395     */
396    @Override
397    public void fireErrors(String fileName, SortedSet<Violation> errors) {
398        final String stripped = CommonUtil.relativizeAndNormalizePath(basedir, fileName);
399        boolean hasNonFilteredViolations = false;
400        for (final Violation element : errors) {
401            final AuditEvent event = new AuditEvent(this, stripped, element);
402            if (filters.accept(event)) {
403                hasNonFilteredViolations = true;
404                for (final AuditListener listener : listeners) {
405                    listener.addError(event);
406                }
407            }
408        }
409        if (hasNonFilteredViolations && cacheFile != null) {
410            cacheFile.remove(fileName);
411        }
412    }
413
414    /**
415     * Notify all listeners about the end of a file audit.
416     *
417     * @param fileName
418     *            the audited file
419     */
420    @Override
421    public void fireFileFinished(String fileName) {
422        final String stripped = CommonUtil.relativizeAndNormalizePath(basedir, fileName);
423        final AuditEvent event = new AuditEvent(this, stripped);
424        for (final AuditListener listener : listeners) {
425            listener.fileFinished(event);
426        }
427    }
428
429    @Override
430    protected void finishLocalSetup() throws CheckstyleException {
431        final Locale locale = new Locale(localeLanguage, localeCountry);
432        Violation.setLocale(locale);
433
434        if (moduleFactory == null) {
435            if (moduleClassLoader == null) {
436                throw new CheckstyleException(
437                        "if no custom moduleFactory is set, "
438                                + "moduleClassLoader must be specified");
439            }
440
441            final Set<String> packageNames = PackageNamesLoader
442                    .getPackageNames(moduleClassLoader);
443            moduleFactory = new PackageObjectFactory(packageNames,
444                    moduleClassLoader);
445        }
446
447        final DefaultContext context = new DefaultContext();
448        context.add("charset", charset);
449        context.add("moduleFactory", moduleFactory);
450        context.add("severity", severity.getName());
451        context.add("basedir", basedir);
452        context.add("tabWidth", String.valueOf(tabWidth));
453        childContext = context;
454    }
455
456    /**
457     * {@inheritDoc} Creates child module.
458     *
459     * @noinspection ChainOfInstanceofChecks
460     * @noinspectionreason ChainOfInstanceofChecks - we treat checks and filters differently
461     */
462    @Override
463    protected void setupChild(Configuration childConf)
464            throws CheckstyleException {
465        final String name = childConf.getName();
466        final Object child;
467
468        try {
469            child = moduleFactory.createModule(name);
470
471            if (child instanceof AutomaticBean) {
472                final AutomaticBean bean = (AutomaticBean) child;
473                bean.contextualize(childContext);
474                bean.configure(childConf);
475            }
476        }
477        catch (final CheckstyleException ex) {
478            throw new CheckstyleException("cannot initialize module " + name
479                    + " - " + ex.getMessage(), ex);
480        }
481        if (child instanceof FileSetCheck) {
482            final FileSetCheck fsc = (FileSetCheck) child;
483            fsc.init();
484            addFileSetCheck(fsc);
485        }
486        else if (child instanceof BeforeExecutionFileFilter) {
487            final BeforeExecutionFileFilter filter = (BeforeExecutionFileFilter) child;
488            addBeforeExecutionFileFilter(filter);
489        }
490        else if (child instanceof Filter) {
491            final Filter filter = (Filter) child;
492            addFilter(filter);
493        }
494        else if (child instanceof AuditListener) {
495            final AuditListener listener = (AuditListener) child;
496            addListener(listener);
497        }
498        else {
499            throw new CheckstyleException(name
500                    + " is not allowed as a child in Checker");
501        }
502    }
503
504    /**
505     * Adds a FileSetCheck to the list of FileSetChecks
506     * that is executed in process().
507     *
508     * @param fileSetCheck the additional FileSetCheck
509     */
510    public void addFileSetCheck(FileSetCheck fileSetCheck) {
511        fileSetCheck.setMessageDispatcher(this);
512        fileSetChecks.add(fileSetCheck);
513    }
514
515    /**
516     * Adds a before execution file filter to the end of the event chain.
517     *
518     * @param filter the additional filter
519     */
520    public void addBeforeExecutionFileFilter(BeforeExecutionFileFilter filter) {
521        beforeExecutionFileFilters.addBeforeExecutionFileFilter(filter);
522    }
523
524    /**
525     * Adds a filter to the end of the audit event filter chain.
526     *
527     * @param filter the additional filter
528     */
529    public void addFilter(Filter filter) {
530        filters.addFilter(filter);
531    }
532
533    @Override
534    public final void addListener(AuditListener listener) {
535        listeners.add(listener);
536    }
537
538    /**
539     * Sets the file extensions that identify the files that pass the
540     * filter of this FileSetCheck.
541     *
542     * @param extensions the set of file extensions. A missing
543     *     initial '.' character of an extension is automatically added.
544     */
545    public final void setFileExtensions(String... extensions) {
546        if (extensions == null) {
547            fileExtensions = null;
548        }
549        else {
550            fileExtensions = new String[extensions.length];
551            for (int i = 0; i < extensions.length; i++) {
552                final String extension = extensions[i];
553                if (CommonUtil.startsWithChar(extension, '.')) {
554                    fileExtensions[i] = extension;
555                }
556                else {
557                    fileExtensions[i] = "." + extension;
558                }
559            }
560        }
561    }
562
563    /**
564     * Sets the factory for creating submodules.
565     *
566     * @param moduleFactory the factory for creating FileSetChecks
567     */
568    public void setModuleFactory(ModuleFactory moduleFactory) {
569        this.moduleFactory = moduleFactory;
570    }
571
572    /**
573     * Sets locale country.
574     *
575     * @param localeCountry the country to report messages
576     */
577    public void setLocaleCountry(String localeCountry) {
578        this.localeCountry = localeCountry;
579    }
580
581    /**
582     * Sets locale language.
583     *
584     * @param localeLanguage the language to report messages
585     */
586    public void setLocaleLanguage(String localeLanguage) {
587        this.localeLanguage = localeLanguage;
588    }
589
590    /**
591     * Sets the severity level.  The string should be one of the names
592     * defined in the {@code SeverityLevel} class.
593     *
594     * @param severity  The new severity level
595     * @see SeverityLevel
596     */
597    public final void setSeverity(String severity) {
598        this.severity = SeverityLevel.getInstance(severity);
599    }
600
601    @Override
602    public final void setModuleClassLoader(ClassLoader moduleClassLoader) {
603        this.moduleClassLoader = moduleClassLoader;
604    }
605
606    /**
607     * Sets a named charset.
608     *
609     * @param charset the name of a charset
610     * @throws UnsupportedEncodingException if charset is unsupported.
611     */
612    public void setCharset(String charset)
613            throws UnsupportedEncodingException {
614        if (!Charset.isSupported(charset)) {
615            final String message = "unsupported charset: '" + charset + "'";
616            throw new UnsupportedEncodingException(message);
617        }
618        this.charset = charset;
619    }
620
621    /**
622     * Sets the field haltOnException.
623     *
624     * @param haltOnException the new value.
625     */
626    public void setHaltOnException(boolean haltOnException) {
627        this.haltOnException = haltOnException;
628    }
629
630    /**
631     * Set the tab width to report audit events with.
632     *
633     * @param tabWidth an {@code int} value
634     */
635    public final void setTabWidth(int tabWidth) {
636        this.tabWidth = tabWidth;
637    }
638
639    /**
640     * Clears the cache.
641     */
642    public void clearCache() {
643        if (cacheFile != null) {
644            cacheFile.reset();
645        }
646    }
647
648}