Search in sources :

Example 21 with Checker

use of com.puppycrawl.tools.checkstyle.Checker in project checkstyle by checkstyle.

the class HeaderCheckTest method testCacheHeaderWithoutFile.

@Test
public void testCacheHeaderWithoutFile() throws Exception {
    final DefaultConfiguration checkConfig = createCheckConfig(HeaderCheck.class);
    checkConfig.addAttribute("header", "Test");
    final DefaultConfiguration checkerConfig = new DefaultConfiguration("checkstyle_checks");
    checkerConfig.addChild(checkConfig);
    checkerConfig.addAttribute("cacheFile", temporaryFolder.newFile().getPath());
    final Checker checker = new Checker();
    checker.setModuleClassLoader(Thread.currentThread().getContextClassLoader());
    checker.configure(checkerConfig);
    checker.addListener(new BriefUtLogger(stream));
    final String[] expected = { "1: " + getCheckMessage(MSG_MISMATCH, "Test") };
    verify(checker, getPath("InputHeader.java"), expected);
}
Also used : Checker(com.puppycrawl.tools.checkstyle.Checker) DefaultConfiguration(com.puppycrawl.tools.checkstyle.DefaultConfiguration) BriefUtLogger(com.puppycrawl.tools.checkstyle.BriefUtLogger) Test(org.junit.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 22 with Checker

use of com.puppycrawl.tools.checkstyle.Checker in project maven-plugins by apache.

the class DefaultCheckstyleExecutor method executeCheckstyle.

public CheckstyleResults executeCheckstyle(CheckstyleExecutorRequest request) throws CheckstyleExecutorException, CheckstyleException {
    if (getLogger().isDebugEnabled()) {
        getLogger().debug("executeCheckstyle start headerLocation : " + request.getHeaderLocation());
    }
    MavenProject project = request.getProject();
    configureResourceLocator(locator, request, null);
    configureResourceLocator(licenseLocator, request, request.getLicenseArtifacts());
    // Config is less critical than License, locator can still be used.
    // configureResourceLocator( configurationLocator, request, request.getConfigurationArtifacts() );
    List<File> files;
    try {
        files = getFilesToProcess(request);
    } catch (IOException e) {
        throw new CheckstyleExecutorException("Error getting files to process", e);
    }
    final String suppressionsFilePath = getSuppressionsFilePath(request);
    FilterSet filterSet = getSuppressionsFilterSet(suppressionsFilePath);
    Checker checker = new Checker();
    // setup classloader, needed to avoid "Unable to get class information for ..." errors
    List<String> classPathStrings = new ArrayList<>();
    List<String> outputDirectories = new ArrayList<>();
    // stand-alone
    Collection<File> sourceDirectories = null;
    Collection<File> testSourceDirectories = request.getTestSourceDirectories();
    // aggregator
    Map<MavenProject, Collection<File>> sourceDirectoriesByProject = new HashMap<>();
    Map<MavenProject, Collection<File>> testSourceDirectoriesByProject = new HashMap<>();
    if (request.isAggregate()) {
        for (MavenProject childProject : request.getReactorProjects()) {
            sourceDirectories = new ArrayList<>(childProject.getCompileSourceRoots().size());
            List<String> compileSourceRoots = childProject.getCompileSourceRoots();
            for (String compileSourceRoot : compileSourceRoots) {
                sourceDirectories.add(new File(compileSourceRoot));
            }
            sourceDirectoriesByProject.put(childProject, sourceDirectories);
            testSourceDirectories = new ArrayList<>(childProject.getTestCompileSourceRoots().size());
            List<String> testCompileSourceRoots = childProject.getTestCompileSourceRoots();
            for (String testCompileSourceRoot : testCompileSourceRoots) {
                testSourceDirectories.add(new File(testCompileSourceRoot));
            }
            testSourceDirectoriesByProject.put(childProject, testSourceDirectories);
            prepareCheckstylePaths(request, childProject, classPathStrings, outputDirectories, sourceDirectories, testSourceDirectories);
        }
    } else {
        sourceDirectories = request.getSourceDirectories();
        prepareCheckstylePaths(request, project, classPathStrings, outputDirectories, sourceDirectories, testSourceDirectories);
    }
    final List<URL> urls = new ArrayList<>(classPathStrings.size());
    for (String path : classPathStrings) {
        try {
            urls.add(new File(path).toURI().toURL());
        } catch (MalformedURLException e) {
            throw new CheckstyleExecutorException(e.getMessage(), e);
        }
    }
    for (String outputDirectoryString : outputDirectories) {
        try {
            if (outputDirectoryString != null) {
                File outputDirectoryFile = new File(outputDirectoryString);
                if (outputDirectoryFile.exists()) {
                    URL outputDirectoryUrl = outputDirectoryFile.toURI().toURL();
                    getLogger().debug("Adding the outputDirectory " + outputDirectoryUrl.toString() + " to the Checkstyle class path");
                    urls.add(outputDirectoryUrl);
                }
            }
        } catch (MalformedURLException e) {
            throw new CheckstyleExecutorException(e.getMessage(), e);
        }
    }
    URLClassLoader projectClassLoader = AccessController.doPrivileged(new PrivilegedAction<URLClassLoader>() {

        public URLClassLoader run() {
            return new URLClassLoader(urls.toArray(new URL[urls.size()]), null);
        }
    });
    checker.setClassLoader(projectClassLoader);
    checker.setModuleClassLoader(Thread.currentThread().getContextClassLoader());
    if (filterSet != null) {
        checker.addFilter(filterSet);
    }
    Configuration configuration = getConfiguration(request);
    checker.configure(configuration);
    AuditListener listener = request.getListener();
    if (listener != null) {
        checker.addListener(listener);
    }
    if (request.isConsoleOutput()) {
        checker.addListener(request.getConsoleListener());
    }
    CheckstyleCheckerListener checkerListener = new CheckstyleCheckerListener(configuration);
    if (request.isAggregate()) {
        for (MavenProject childProject : request.getReactorProjects()) {
            sourceDirectories = sourceDirectoriesByProject.get(childProject);
            testSourceDirectories = testSourceDirectoriesByProject.get(childProject);
            addSourceDirectory(checkerListener, sourceDirectories, testSourceDirectories, childProject.getResources(), request);
        }
    } else {
        addSourceDirectory(checkerListener, sourceDirectories, testSourceDirectories, request.getResources(), request);
    }
    checker.addListener(checkerListener);
    int nbErrors = checker.process(files);
    checker.destroy();
    if (projectClassLoader instanceof Closeable) {
        try {
            ((Closeable) projectClassLoader).close();
        } catch (IOException ex) {
            // Nothing we can do - and not detrimental to the build (save running out of file handles).
            getLogger().info("Failed to close custom Classloader - this indicated a bug in the code.", ex);
        }
    }
    if (request.getStringOutputStream() != null) {
        String message = request.getStringOutputStream().toString().trim();
        if (message.length() > 0) {
            getLogger().info(message);
        }
    }
    if (nbErrors > 0) {
        StringBuilder message = new StringBuilder("There ");
        if (nbErrors == 1) {
            message.append("is");
        } else {
            message.append("are");
        }
        message.append(" ");
        message.append(nbErrors);
        message.append(" error");
        if (nbErrors != 1) {
            message.append("s");
        }
        message.append(" reported by Checkstyle");
        String version = getCheckstyleVersion();
        if (version != null) {
            message.append(" ");
            message.append(version);
        }
        message.append(" with ");
        message.append(request.getConfigLocation());
        message.append(" ruleset.");
        if (request.isFailsOnError()) {
            // work regardless of config), but should record this information
            throw new CheckstyleExecutorException(message.toString());
        } else {
            getLogger().info(message.toString());
        }
    }
    return checkerListener.getResults();
}
Also used : MalformedURLException(java.net.MalformedURLException) FilterSet(com.puppycrawl.tools.checkstyle.api.FilterSet) Configuration(com.puppycrawl.tools.checkstyle.api.Configuration) DefaultConfiguration(com.puppycrawl.tools.checkstyle.DefaultConfiguration) HashMap(java.util.HashMap) Closeable(java.io.Closeable) ArrayList(java.util.ArrayList) AuditListener(com.puppycrawl.tools.checkstyle.api.AuditListener) URL(java.net.URL) MavenProject(org.apache.maven.project.MavenProject) Checker(com.puppycrawl.tools.checkstyle.Checker) IOException(java.io.IOException) URLClassLoader(java.net.URLClassLoader) Collection(java.util.Collection) File(java.io.File)

Aggregations

Checker (com.puppycrawl.tools.checkstyle.Checker)22 DefaultConfiguration (com.puppycrawl.tools.checkstyle.DefaultConfiguration)17 Test (org.junit.Test)13 BriefUtLogger (com.puppycrawl.tools.checkstyle.BriefUtLogger)10 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)6 Locale (java.util.Locale)5 Configuration (com.puppycrawl.tools.checkstyle.api.Configuration)4 File (java.io.File)4 IllegalCatchCheck (com.puppycrawl.tools.checkstyle.checks.coding.IllegalCatchCheck)3 ArrayList (java.util.ArrayList)3 PropertiesExpander (com.puppycrawl.tools.checkstyle.PropertiesExpander)2 AuditEvent (com.puppycrawl.tools.checkstyle.api.AuditEvent)2 CheckstyleException (com.puppycrawl.tools.checkstyle.api.CheckstyleException)2 LocalizedMessage (com.puppycrawl.tools.checkstyle.api.LocalizedMessage)2 FileContentsHolder (com.puppycrawl.tools.checkstyle.checks.FileContentsHolder)2 Field (java.lang.reflect.Field)2 Properties (java.util.Properties)2 BaseCheckTestSupport (com.puppycrawl.tools.checkstyle.BaseCheckTestSupport)1 ModuleFactory (com.puppycrawl.tools.checkstyle.ModuleFactory)1 PackageObjectFactory (com.puppycrawl.tools.checkstyle.PackageObjectFactory)1