Search in sources :

Example 36 with CheckstyleException

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

the class CheckstyleViolationCheckMojo method execute.

/** {@inheritDoc} */
public void execute() throws MojoExecutionException, MojoFailureException {
    checkDeprecatedParameterUsage(sourceDirectory, "sourceDirectory", "sourceDirectories");
    checkDeprecatedParameterUsage(testSourceDirectory, "testSourceDirectory", "testSourceDirectories");
    if (skip) {
        return;
    }
    outputXmlFile = outputFile;
    if (!skipExec) {
        if (checkstyleRules != null) {
            if (!"sun_checks.xml".equals(configLocation)) {
                throw new MojoExecutionException("If you use inline configuration for rules, don't specify " + "a configLocation");
            }
            if (checkstyleRules.getChildCount() > 1) {
                throw new MojoExecutionException("Currently only one root module is supported");
            }
            PlexusConfiguration checkerModule = checkstyleRules.getChild(0);
            try {
                FileUtils.forceMkdir(rulesFiles.getParentFile());
                FileUtils.fileWrite(rulesFiles, CHECKSTYLE_FILE_HEADER + checkerModule.toString());
            } catch (final IOException e) {
                throw new MojoExecutionException(e.getMessage(), e);
            }
            configLocation = rulesFiles.getAbsolutePath();
        }
        ClassLoader currentClassLoader = Thread.currentThread().getContextClassLoader();
        try {
            CheckstyleExecutorRequest request = new CheckstyleExecutorRequest();
            request.setConsoleListener(getConsoleListener()).setConsoleOutput(consoleOutput).setExcludes(excludes).setFailsOnError(failsOnError).setIncludes(includes).setResourceIncludes(resourceIncludes).setResourceExcludes(resourceExcludes).setIncludeResources(includeResources).setIncludeTestResources(includeTestResources).setIncludeTestSourceDirectory(includeTestSourceDirectory).setListener(getListener()).setProject(project).setSourceDirectories(getSourceDirectories()).setResources(resources).setTestResources(testResources).setStringOutputStream(stringOutputStream).setSuppressionsLocation(suppressionsLocation).setTestSourceDirectories(getTestSourceDirectories()).setConfigLocation(configLocation).setConfigurationArtifacts(collectArtifacts("config")).setPropertyExpansion(propertyExpansion).setHeaderLocation(headerLocation).setLicenseArtifacts(collectArtifacts("license")).setCacheFile(cacheFile).setSuppressionsFileExpression(suppressionsFileExpression).setEncoding(encoding).setPropertiesLocation(propertiesLocation).setOmitIgnoredModules(omitIgnoredModules);
            checkstyleExecutor.executeCheckstyle(request);
        } catch (CheckstyleException e) {
            throw new MojoExecutionException("Failed during checkstyle configuration", e);
        } catch (CheckstyleExecutorException e) {
            throw new MojoExecutionException("Failed during checkstyle execution", e);
        } finally {
            //be sure to restore original context classloader
            Thread.currentThread().setContextClassLoader(currentClassLoader);
        }
    }
    if (!"xml".equals(outputFileFormat) && skipExec) {
        throw new MojoExecutionException("Output format is '" + outputFileFormat + "', checkstyle:check requires format to be 'xml' when using skipExec.");
    }
    if (!outputXmlFile.exists()) {
        getLog().info("Unable to perform checkstyle:check, unable to find checkstyle:checkstyle outputFile.");
        return;
    }
    try (Reader reader = new BufferedReader(ReaderFactory.newXmlReader(outputXmlFile))) {
        XmlPullParser xpp = new MXParser();
        xpp.setInput(reader);
        int violations = countViolations(xpp);
        if (violations > maxAllowedViolations) {
            if (failOnViolation) {
                String msg = "You have " + violations + " Checkstyle violation" + ((violations > 1) ? "s" : "") + ".";
                if (maxAllowedViolations > 0) {
                    msg += " The maximum number of allowed violations is " + maxAllowedViolations + ".";
                }
                throw new MojoFailureException(msg);
            }
            getLog().warn("checkstyle:check violations detected but failOnViolation set to false");
        }
    } catch (IOException | XmlPullParserException e) {
        throw new MojoExecutionException("Unable to read Checkstyle results xml: " + outputXmlFile.getAbsolutePath(), e);
    }
}
Also used : PlexusConfiguration(org.codehaus.plexus.configuration.PlexusConfiguration) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) MXParser(org.codehaus.plexus.util.xml.pull.MXParser) CheckstyleExecutorRequest(org.apache.maven.plugins.checkstyle.exec.CheckstyleExecutorRequest) CheckstyleExecutorException(org.apache.maven.plugins.checkstyle.exec.CheckstyleExecutorException) XmlPullParser(org.codehaus.plexus.util.xml.pull.XmlPullParser) MojoFailureException(org.apache.maven.plugin.MojoFailureException) Reader(java.io.Reader) BufferedReader(java.io.BufferedReader) CheckstyleException(com.puppycrawl.tools.checkstyle.api.CheckstyleException) IOException(java.io.IOException) BufferedReader(java.io.BufferedReader) XmlPullParserException(org.codehaus.plexus.util.xml.pull.XmlPullParserException)

Example 37 with CheckstyleException

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

the class AbstractCheckstyleReport method executeReport.

/** {@inheritDoc} */
public void executeReport(Locale locale) throws MavenReportException {
    checkDeprecatedParameterUsage(sourceDirectory, "sourceDirectory", "sourceDirectories");
    checkDeprecatedParameterUsage(testSourceDirectory, "testSourceDirectory", "testSourceDirectories");
    locator.addSearchPath(FileResourceLoader.ID, project.getFile().getParentFile().getAbsolutePath());
    locator.addSearchPath("url", "");
    locator.setOutputDirectory(new File(project.getBuild().getDirectory()));
    // for when we start using maven-shared-io and maven-shared-monitor...
    // locator = new Locator( new MojoLogMonitorAdaptor( getLog() ) );
    // locator = new Locator( getLog(), new File( project.getBuild().getDirectory() ) );
    ClassLoader currentClassLoader = Thread.currentThread().getContextClassLoader();
    try {
        CheckstyleExecutorRequest request = createRequest().setLicenseArtifacts(collectArtifacts("license")).setConfigurationArtifacts(collectArtifacts("configuration")).setOmitIgnoredModules(omitIgnoredModules);
        CheckstyleResults results = checkstyleExecutor.executeCheckstyle(request);
        ResourceBundle bundle = getBundle(locale);
        generateReportStatics();
        generateMainReport(results, bundle);
        if (enableRSS) {
            CheckstyleRssGeneratorRequest checkstyleRssGeneratorRequest = new CheckstyleRssGeneratorRequest(this.project, this.getCopyright(), outputDirectory, getLog());
            checkstyleRssGenerator.generateRSS(results, checkstyleRssGeneratorRequest);
        }
    } catch (CheckstyleException e) {
        throw new MavenReportException("Failed during checkstyle configuration", e);
    } catch (CheckstyleExecutorException e) {
        throw new MavenReportException("Failed during checkstyle execution", e);
    } finally {
        //be sure to restore original context classloader
        Thread.currentThread().setContextClassLoader(currentClassLoader);
    }
}
Also used : CheckstyleResults(org.apache.maven.plugins.checkstyle.exec.CheckstyleResults) CheckstyleRssGeneratorRequest(org.apache.maven.plugins.checkstyle.rss.CheckstyleRssGeneratorRequest) CheckstyleExecutorRequest(org.apache.maven.plugins.checkstyle.exec.CheckstyleExecutorRequest) CheckstyleExecutorException(org.apache.maven.plugins.checkstyle.exec.CheckstyleExecutorException) ResourceBundle(java.util.ResourceBundle) CheckstyleException(com.puppycrawl.tools.checkstyle.api.CheckstyleException) File(java.io.File) MavenReportException(org.apache.maven.reporting.MavenReportException)

Example 38 with CheckstyleException

use of com.puppycrawl.tools.checkstyle.api.CheckstyleException in project checkstyle by checkstyle.

the class PropertyCacheFile method loadExternalResource.

/**
     * Loads the content of external resource.
     * @param location external resource location.
     * @return array of bytes which respresents the content of external resource in binary form.
     * @throws CheckstyleException if error while loading occurs.
     */
private static byte[] loadExternalResource(String location) throws CheckstyleException {
    final byte[] content;
    final URI uri = CommonUtils.getUriByFilename(location);
    try {
        content = ByteStreams.toByteArray(new BufferedInputStream(uri.toURL().openStream()));
    } catch (IOException ex) {
        throw new CheckstyleException("Unable to load external resource file " + location, ex);
    }
    return content;
}
Also used : BufferedInputStream(java.io.BufferedInputStream) CheckstyleException(com.puppycrawl.tools.checkstyle.api.CheckstyleException) IOException(java.io.IOException) URI(java.net.URI)

Example 39 with CheckstyleException

use of com.puppycrawl.tools.checkstyle.api.CheckstyleException in project checkstyle by checkstyle.

the class TreeWalker method processFiltered.

@Override
protected void processFiltered(File file, List<String> lines) throws CheckstyleException {
    // check if already checked and passed the file
    if (CommonUtils.matchesFileExtension(file, getFileExtensions())) {
        final String msg = "%s occurred during the analysis of file %s.";
        final String fileName = file.getPath();
        try {
            final FileText text = FileText.fromLines(file, lines);
            final FileContents contents = new FileContents(text);
            final DetailAST rootAST = parse(contents);
            getMessageCollector().reset();
            walk(rootAST, contents, AstState.ORDINARY);
            final DetailAST astWithComments = appendHiddenCommentNodes(rootAST);
            walk(astWithComments, contents, AstState.WITH_COMMENTS);
        } catch (final TokenStreamRecognitionException tre) {
            final String exceptionMsg = String.format(Locale.ROOT, msg, "TokenStreamRecognitionException", fileName);
            throw new CheckstyleException(exceptionMsg, tre);
        } catch (RecognitionException | TokenStreamException ex) {
            final String exceptionMsg = String.format(Locale.ROOT, msg, ex.getClass().getSimpleName(), fileName);
            throw new CheckstyleException(exceptionMsg, ex);
        }
    }
}
Also used : TokenStreamException(antlr.TokenStreamException) TokenStreamRecognitionException(antlr.TokenStreamRecognitionException) FileContents(com.puppycrawl.tools.checkstyle.api.FileContents) DetailAST(com.puppycrawl.tools.checkstyle.api.DetailAST) CheckstyleException(com.puppycrawl.tools.checkstyle.api.CheckstyleException) FileText(com.puppycrawl.tools.checkstyle.api.FileText) TokenStreamRecognitionException(antlr.TokenStreamRecognitionException) RecognitionException(antlr.RecognitionException)

Example 40 with CheckstyleException

use of com.puppycrawl.tools.checkstyle.api.CheckstyleException in project checkstyle by checkstyle.

the class SuppressionFilter method suppressionSourceExists.

/**
     * Checks if suppression source with given fileName exists.
     * @param fileName name of the suppressions file.
     * @return true if suppression file exists, otherwise false
     */
private static boolean suppressionSourceExists(String fileName) {
    boolean suppressionSourceExists = true;
    InputStream sourceInput = null;
    try {
        final URI uriByFilename = CommonUtils.getUriByFilename(fileName);
        final URL url = uriByFilename.toURL();
        sourceInput = url.openStream();
    } catch (CheckstyleException | IOException ignored) {
        suppressionSourceExists = false;
    } finally {
        if (sourceInput != null) {
            try {
                sourceInput.close();
            } catch (IOException ignored) {
                suppressionSourceExists = false;
            }
        }
    }
    return suppressionSourceExists;
}
Also used : InputStream(java.io.InputStream) CheckstyleException(com.puppycrawl.tools.checkstyle.api.CheckstyleException) IOException(java.io.IOException) URI(java.net.URI) URL(java.net.URL)

Aggregations

CheckstyleException (com.puppycrawl.tools.checkstyle.api.CheckstyleException)78 Test (org.junit.Test)46 DefaultConfiguration (com.puppycrawl.tools.checkstyle.DefaultConfiguration)33 File (java.io.File)15 IOException (java.io.IOException)15 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)15 Configuration (com.puppycrawl.tools.checkstyle.api.Configuration)9 Properties (java.util.Properties)8 URL (java.net.URL)6 SAXException (org.xml.sax.SAXException)5 PropertiesExpander (com.puppycrawl.tools.checkstyle.PropertiesExpander)4 URI (java.net.URI)4 Checker (com.puppycrawl.tools.checkstyle.Checker)3 DetailAST (com.puppycrawl.tools.checkstyle.api.DetailAST)3 BufferedInputStream (java.io.BufferedInputStream)3 FileInputStream (java.io.FileInputStream)3 Method (java.lang.reflect.Method)3 MalformedURLException (java.net.MalformedURLException)3 ArrayList (java.util.ArrayList)3 ParserConfigurationException (javax.xml.parsers.ParserConfigurationException)3