Search in sources :

Example 16 with CheckstyleException

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

the class CheckstyleAntTask method createRootModule.

/**
     * Creates new instance of the root module.
     * @return new instance of the root module
     */
private RootModule createRootModule() {
    final RootModule rootModule;
    try {
        final Properties props = createOverridingProperties();
        final Configuration config = ConfigurationLoader.loadConfiguration(configLocation, new PropertiesExpander(props), omitIgnoredModules);
        final ClassLoader moduleClassLoader = Checker.class.getClassLoader();
        final ModuleFactory factory = new PackageObjectFactory(Checker.class.getPackage().getName() + ".", moduleClassLoader);
        rootModule = (RootModule) factory.createModule(config.getName());
        rootModule.setModuleClassLoader(moduleClassLoader);
        if (rootModule instanceof Checker) {
            final ClassLoader loader = new AntClassLoader(getProject(), classpath);
            ((Checker) rootModule).setClassLoader(loader);
        }
        rootModule.configure(config);
    } catch (final CheckstyleException ex) {
        throw new BuildException(String.format(Locale.ROOT, "Unable to create Root Module: " + "configLocation {%s}, classpath {%s}.", configLocation, classpath), ex);
    }
    return rootModule;
}
Also used : ModuleFactory(com.puppycrawl.tools.checkstyle.ModuleFactory) Checker(com.puppycrawl.tools.checkstyle.Checker) Configuration(com.puppycrawl.tools.checkstyle.api.Configuration) RootModule(com.puppycrawl.tools.checkstyle.api.RootModule) PropertiesExpander(com.puppycrawl.tools.checkstyle.PropertiesExpander) AntClassLoader(org.apache.tools.ant.AntClassLoader) AntClassLoader(org.apache.tools.ant.AntClassLoader) CheckstyleException(com.puppycrawl.tools.checkstyle.api.CheckstyleException) BuildException(org.apache.tools.ant.BuildException) Properties(java.util.Properties) PackageObjectFactory(com.puppycrawl.tools.checkstyle.PackageObjectFactory)

Example 17 with CheckstyleException

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

the class CheckstyleAntTask method processFiles.

/**
     * Scans and processes files by means given root module.
     * @param rootModule Root module to process files
     * @param warningCounter Root Module's counter of warnings
     * @param checkstyleVersion Checkstyle compile version
     */
private void processFiles(RootModule rootModule, final SeverityLevelCounter warningCounter, final String checkstyleVersion) {
    final long startTime = System.currentTimeMillis();
    final List<File> files = scanFileSets();
    final long endTime = System.currentTimeMillis();
    log("To locate the files took " + (endTime - startTime) + TIME_SUFFIX, Project.MSG_VERBOSE);
    log("Running Checkstyle " + checkstyleVersion + " on " + files.size() + " files", Project.MSG_INFO);
    log("Using configuration " + configLocation, Project.MSG_VERBOSE);
    final int numErrs;
    try {
        final long processingStartTime = System.currentTimeMillis();
        numErrs = rootModule.process(files);
        final long processingEndTime = System.currentTimeMillis();
        log("To process the files took " + (processingEndTime - processingStartTime) + TIME_SUFFIX, Project.MSG_VERBOSE);
    } catch (CheckstyleException ex) {
        throw new BuildException("Unable to process files: " + files, ex);
    }
    final int numWarnings = warningCounter.getCount();
    final boolean okStatus = numErrs <= maxErrors && numWarnings <= maxWarnings;
    // Handle the return status
    if (!okStatus) {
        final String failureMsg = "Got " + numErrs + " errors and " + numWarnings + " warnings.";
        if (failureProperty != null) {
            getProject().setProperty(failureProperty, failureMsg);
        }
        if (failOnViolation) {
            throw new BuildException(failureMsg, getLocation());
        }
    }
}
Also used : CheckstyleException(com.puppycrawl.tools.checkstyle.api.CheckstyleException) BuildException(org.apache.tools.ant.BuildException) File(java.io.File)

Example 18 with CheckstyleException

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

the class Main method main.

/**
     * Loops over the files specified checking them for errors. The exit code
     * is the number of errors found in all the files.
     * @param args the command line arguments.
     * @throws IOException if there is a problem with files access
     * @noinspection CallToPrintStackTrace
     **/
public static void main(String... args) throws IOException {
    int errorCounter = 0;
    boolean cliViolations = false;
    // provide proper exit code based on results.
    final int exitWithCliViolation = -1;
    int exitStatus = 0;
    try {
        //parse CLI arguments
        final CommandLine commandLine = parseCli(args);
        // show version and exit if it is requested
        if (commandLine.hasOption(OPTION_V_NAME)) {
            System.out.println("Checkstyle version: " + Main.class.getPackage().getImplementationVersion());
            exitStatus = 0;
        } else {
            final List<File> filesToProcess = getFilesToProcess(getExclusions(commandLine), commandLine.getArgs());
            // return error if something is wrong in arguments
            final List<String> messages = validateCli(commandLine, filesToProcess);
            cliViolations = !messages.isEmpty();
            if (cliViolations) {
                exitStatus = exitWithCliViolation;
                errorCounter = 1;
                messages.forEach(System.out::println);
            } else {
                errorCounter = runCli(commandLine, filesToProcess);
                exitStatus = errorCounter;
            }
        }
    } catch (ParseException pex) {
        // something wrong with arguments - print error and manual
        cliViolations = true;
        exitStatus = exitWithCliViolation;
        errorCounter = 1;
        System.out.println(pex.getMessage());
        printUsage();
    } catch (CheckstyleException ex) {
        exitStatus = EXIT_WITH_CHECKSTYLE_EXCEPTION_CODE;
        errorCounter = 1;
        ex.printStackTrace();
    } finally {
        // return exit code base on validation of Checker
        if (errorCounter != 0 && !cliViolations) {
            System.out.println(String.format("Checkstyle ends with %d errors.", errorCounter));
        }
        if (exitStatus != 0) {
            System.exit(exitStatus);
        }
    }
}
Also used : CommandLine(org.apache.commons.cli.CommandLine) CheckstyleException(com.puppycrawl.tools.checkstyle.api.CheckstyleException) ParseException(org.apache.commons.cli.ParseException) File(java.io.File)

Example 19 with CheckstyleException

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

the class Checker method setupChild.

@Override
protected void setupChild(Configuration childConf) throws CheckstyleException {
    final String name = childConf.getName();
    final Object child;
    try {
        child = moduleFactory.createModule(name);
        if (child instanceof AutomaticBean) {
            final AutomaticBean bean = (AutomaticBean) child;
            bean.contextualize(childContext);
            bean.configure(childConf);
        }
    } catch (final CheckstyleException ex) {
        throw new CheckstyleException("cannot initialize module " + name + " - " + ex.getMessage(), ex);
    }
    if (child instanceof FileSetCheck) {
        final FileSetCheck fsc = (FileSetCheck) child;
        fsc.init();
        addFileSetCheck(fsc);
    } else if (child instanceof BeforeExecutionFileFilter) {
        final BeforeExecutionFileFilter filter = (BeforeExecutionFileFilter) child;
        addBeforeExecutionFileFilter(filter);
    } else if (child instanceof Filter) {
        final Filter filter = (Filter) child;
        addFilter(filter);
    } else if (child instanceof AuditListener) {
        final AuditListener listener = (AuditListener) child;
        addListener(listener);
    } else {
        throw new CheckstyleException(name + " is not allowed as a child in Checker");
    }
}
Also used : FileSetCheck(com.puppycrawl.tools.checkstyle.api.FileSetCheck) BeforeExecutionFileFilter(com.puppycrawl.tools.checkstyle.api.BeforeExecutionFileFilter) Filter(com.puppycrawl.tools.checkstyle.api.Filter) BeforeExecutionFileFilter(com.puppycrawl.tools.checkstyle.api.BeforeExecutionFileFilter) CheckstyleException(com.puppycrawl.tools.checkstyle.api.CheckstyleException) AuditListener(com.puppycrawl.tools.checkstyle.api.AuditListener) AutomaticBean(com.puppycrawl.tools.checkstyle.api.AutomaticBean)

Example 20 with CheckstyleException

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

the class ConstantNameCheckTest method testIllegalRegexp.

@Test
public void testIllegalRegexp() throws Exception {
    final DefaultConfiguration checkConfig = createCheckConfig(ConstantNameCheck.class);
    checkConfig.addAttribute("format", "\\");
    try {
        createChecker(checkConfig);
        fail("CheckstyleException is expected");
    } catch (CheckstyleException ex) {
        assertEquals("cannot initialize module" + " com.puppycrawl.tools.checkstyle.TreeWalker - illegal value" + " '\\' for property 'format' of module" + " com.puppycrawl.tools.checkstyle.checks.naming.ConstantNameCheck", ex.getMessage());
    }
}
Also used : DefaultConfiguration(com.puppycrawl.tools.checkstyle.DefaultConfiguration) CheckstyleException(com.puppycrawl.tools.checkstyle.api.CheckstyleException) Test(org.junit.Test)

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