com.puppycrawl.tools.checkstyle.Checker Java Examples

The following examples show how to use com.puppycrawl.tools.checkstyle.Checker. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: CheckerFactory.java    From eclipse-cs with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Tries to reuse an already configured checker for this configuration.
 *
 * @param config
 *          the configuration file
 * @param cacheKey
 *          the key for cache access
 * @return the cached checker or null
 */
private static Checker tryCheckerCache(String cacheKey, long modificationStamp) {

  // try the cache
  Checker checker = sCheckerMap.getIfPresent(cacheKey);

  // if cache hit
  if (checker != null) {

    // compare modification times of the configs
    Long oldTime = sModifiedMap.get(cacheKey);
    Long newTime = Long.valueOf(modificationStamp);

    // no match - remove checker from cache
    if (oldTime == null || oldTime.compareTo(newTime) != 0) {
      checker = null;
      sCheckerMap.invalidate(cacheKey);
      sModifiedMap.remove(cacheKey);
    }
  }
  return checker;
}
 
Example #2
Source File: CommonsLoggingListener.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/** @see com.puppycrawl.tools.checkstyle.api.AuditListener */
public void auditFinished(AuditEvent aEvt)
{
    if (mInitialized) {
        final Log log = mLogFactory.getInstance(Checker.class);
        log.info("Audit finished.");
    }
}
 
Example #3
Source File: CheckStyleExecutor.java    From repositoryminer with Apache License 2.0 5 votes vote down vote up
public Map<String, List<StyleProblem>> execute() throws CheckstyleException {
	Properties properties;
	if (propertiesFile == null) {
		properties = System.getProperties();
	} else {
		properties = loadProperties(new File(propertiesFile));
	}

	if (configFile == null) {
		configFile = "/google_checks.xml";
	}
	
	// create configurations
	Configuration config = ConfigurationLoader.loadConfiguration(configFile, new PropertiesExpander(properties));

	// create our custom audit listener
	RepositoryMinerAudit listener = new RepositoryMinerAudit();
	listener.setRepositoryPathLength(repository.length());

	ClassLoader moduleClassLoader = Checker.class.getClassLoader();
	RootModule rootModule = getRootModule(config.getName(), moduleClassLoader);

	rootModule.setModuleClassLoader(moduleClassLoader);
	rootModule.configure(config);
	rootModule.addListener(listener);

	// executes checkstyle
	rootModule.process((List<File>) FileUtils.listFiles(new File(repository), EXTENSION_FILE_FILTER, true));
	rootModule.destroy();

	return listener.getFileErrors();
}
 
Example #4
Source File: CheckstyleProcessor.java    From sputnik with Apache License 2.0 5 votes vote down vote up
@NotNull
private Checker createChecker(@NotNull AuditListener auditListener) {
    try {
        Checker checker = new Checker();
        ClassLoader moduleClassLoader = Checker.class.getClassLoader();
        String configurationFile = getConfigurationFilename();
        Properties properties = System.getProperties();// loadProperties(new File(System.getProperty(CHECKSTYLE_PROPERTIES_FILE)));
        checker.setModuleClassLoader(moduleClassLoader);
        checker.configure(ConfigurationLoader.loadConfiguration(configurationFile, new PropertiesExpander(properties)));
        checker.addListener(auditListener);
        return checker;
    } catch (CheckstyleException e) {
        throw new ReviewException("Unable to create Checkstyle checker", e);
    }
}
 
Example #5
Source File: CheckstyleProcessor.java    From sputnik with Apache License 2.0 5 votes vote down vote up
private void innerProcess(@NotNull Review review, @NotNull AuditListener auditListener) {
    List<File> files = review.getFiles(new JavaFilter(), new IOFileTransformer());
    Checker checker = createChecker(auditListener);
    try {
        checker.process(files);
    } catch (CheckstyleException e) {
        throw new ReviewException("Unable to process files with Checkstyle", e);
    }
    checker.destroy();
}
 
Example #6
Source File: CheckstyleSourceCodeFileAnalyzerPlugin.java    From coderadar with MIT License 5 votes vote down vote up
private void init(Configuration configuration) {
  checker = new Checker();
  try {
    auditListener = new CoderadarAuditListener();
    final ClassLoader moduleClassLoader = Checker.class.getClassLoader();
    checker.setModuleClassLoader(moduleClassLoader);
    checker.configure(configuration);
    checker.addListener(auditListener);
  } catch (CheckstyleException e) {
    throw new AnalyzerConfigurationException(e);
  }
}
 
Example #7
Source File: CommonsLoggingListener.java    From contribution with GNU Lesser General Public License v2.1 5 votes vote down vote up
/** @see com.puppycrawl.tools.checkstyle.api.AuditListener */
public void fileFinished(AuditEvent aEvt)
{
    if (mInitialized) {
        final Log log = mLogFactory.getInstance(Checker.class);
        log.info("File \"" + aEvt.getFileName() + "\" finished.");
    }
}
 
Example #8
Source File: CommonsLoggingListener.java    From contribution with GNU Lesser General Public License v2.1 5 votes vote down vote up
/** @see com.puppycrawl.tools.checkstyle.api.AuditListener */
public void fileStarted(AuditEvent aEvt)
{
    if (mInitialized) {
        final Log log = mLogFactory.getInstance(Checker.class);
        log.info("File \"" + aEvt.getFileName() + "\" started.");
    }
}
 
Example #9
Source File: CommonsLoggingListener.java    From contribution with GNU Lesser General Public License v2.1 5 votes vote down vote up
/** @see com.puppycrawl.tools.checkstyle.api.AuditListener */
public void auditFinished(AuditEvent aEvt)
{
    if (mInitialized) {
        final Log log = mLogFactory.getInstance(Checker.class);
        log.info("Audit finished.");
    }
}
 
Example #10
Source File: CommonsLoggingListener.java    From contribution with GNU Lesser General Public License v2.1 5 votes vote down vote up
/** @see com.puppycrawl.tools.checkstyle.api.AuditListener */
public void auditStarted(AuditEvent aEvt)
{
    if (mInitialized) {
        final Log log = mLogFactory.getInstance(Checker.class);
        log.info("Audit started.");
    }
}
 
Example #11
Source File: CommonsLoggingListener.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/** @see com.puppycrawl.tools.checkstyle.api.AuditListener */
public void fileFinished(AuditEvent aEvt)
{
    if (mInitialized) {
        final Log log = mLogFactory.getInstance(Checker.class);
        log.info("File \"" + aEvt.getFileName() + "\" finished.");
    }
}
 
Example #12
Source File: CommonsLoggingListener.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/** @see com.puppycrawl.tools.checkstyle.api.AuditListener */
public void fileStarted(AuditEvent aEvt)
{
    if (mInitialized) {
        final Log log = mLogFactory.getInstance(Checker.class);
        log.info("File \"" + aEvt.getFileName() + "\" started.");
    }
}
 
Example #13
Source File: CommonsLoggingListener.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/** @see com.puppycrawl.tools.checkstyle.api.AuditListener */
public void auditStarted(AuditEvent aEvt)
{
    if (mInitialized) {
        final Log log = mLogFactory.getInstance(Checker.class);
        log.info("Audit started.");
    }
}
 
Example #14
Source File: CheckstyleExecutor.java    From sonar-checkstyle with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void executeWithClassLoader() {
    final Checker checker = new Checker();
    OutputStream xmlOutput = null;
    try {
        checker.setModuleClassLoader(Thread.currentThread().getContextClassLoader());
        checker.addListener(listener);

        final File xmlReport = configuration.getTargetXmlReport();
        if (xmlReport != null) {
            LOG.info("Checkstyle output report: {}", xmlReport.getAbsolutePath());
            xmlOutput = FileUtils.openOutputStream(xmlReport);
            checker.addListener(
                    new XMLLogger(xmlOutput, AutomaticBean.OutputStreamOptions.CLOSE));
        }

        checker.setCharset(configuration.getCharset().name());
        checker.configure(configuration.getCheckstyleConfiguration());
        checker.process(configuration
                .getSourceFiles()
                .stream()
                .map(InputFile::file)
                .collect(Collectors.toList()));
    }
    catch (Exception ex) {
        throw new IllegalStateException("Can not execute Checkstyle", ex);
    }
    finally {
        checker.destroy();
        if (Objects.nonNull(xmlOutput)) {
            close(xmlOutput);
        }
    }
}
 
Example #15
Source File: CheckerService.java    From vscode-checkstyle with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void initialize() {
    checker = new Checker();
    listener = new CheckerListener();
    // reset the basedir if it is set so it won't get into the plugins way
    // of determining workspace resources from checkstyle reported file names, see
    // https://sourceforge.net/tracker/?func=detail&aid=2880044&group_id=80344&atid=559497
    checker.setBasedir(null);
    checker.setModuleClassLoader(Checker.class.getClassLoader());
    checker.addListener(listener);
}
 
Example #16
Source File: CheckerFactory.java    From eclipse-cs with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Creates a checker for a given configuration file.
 *
 * @param config
 *          the check configuration data
 * @param project
 *          the project to create the checker for
 * @return the checker for the given configuration file
 * @throws CheckstyleException
 *           the configuration file had errors
 * @throws CheckstylePluginException
 *           the configuration could not be read
 */
public static Checker createChecker(ICheckConfiguration config, IProject project)
        throws CheckstyleException, CheckstylePluginException {

  String cacheKey = getCacheKey(config, project);

  CheckstyleConfigurationFile configFileData = config.getCheckstyleConfiguration();
  Checker checker = tryCheckerCache(cacheKey, configFileData.getModificationStamp());

  // clear Checkstyle internal caches upon checker reuse
  if (checker != null) {
    checker.clearCache();
  }

  // no cache hit
  if (checker == null) {
    PropertyResolver resolver = configFileData.getPropertyResolver();

    // set the project context if the property resolver needs the
    // context
    if (resolver instanceof IContextAware) {
      ((IContextAware) resolver).setProjectContext(project);
    }

    InputSource in = null;
    try {
      in = configFileData.getCheckConfigFileInputSource();
      checker = createCheckerInternal(in, resolver, project);
    } finally {
      Closeables.closeQuietly(in.getByteStream());
    }

    // store checker in cache
    Long modified = Long.valueOf(configFileData.getModificationStamp());
    sCheckerMap.put(cacheKey, checker);
    sModifiedMap.put(cacheKey, modified);
  }

  return checker;
}
 
Example #17
Source File: SpringChecksTests.java    From spring-javaformat with Apache License 2.0 5 votes vote down vote up
private RootModule createRootModule(Configuration configuration) throws CheckstyleException {
	ModuleFactory factory = new PackageObjectFactory(Checker.class.getPackage().getName(),
			getClass().getClassLoader());
	RootModule rootModule = (RootModule) factory.createModule(configuration.getName());
	rootModule.setModuleClassLoader(getClass().getClassLoader());
	rootModule.configure(configuration);
	return rootModule;
}
 
Example #18
Source File: SpringChecks.java    From spring-javaformat with Apache License 2.0 5 votes vote down vote up
@Override
public void beginProcessing(String charset) {
	super.beginProcessing(charset);
	try {
		SuppressFilterElement filter = new SuppressFilterElement("[\\\\/]src[\\\\/]test[\\\\/]java[\\\\/]",
				"Javadoc*", null, null, null, null);
		((Checker) getMessageDispatcher()).addFilter(filter);
	}
	catch (Exception ex) {
		// Ignore and let users configure their own suppressions
	}
}
 
Example #19
Source File: NoHttpCheckITest.java    From nohttp with Apache License 2.0 5 votes vote down vote up
private RootModule createRootModule(Configuration configuration)
		throws CheckstyleException {
	ModuleFactory factory = new PackageObjectFactory(
			Checker.class.getPackage().getName(), getClass().getClassLoader());
	RootModule rootModule = (RootModule) factory
			.createModule(configuration.getName());
	rootModule.setModuleClassLoader(getClass().getClassLoader());
	rootModule.configure(configuration);
	return rootModule;
}
 
Example #20
Source File: CheckStyleExecutor.java    From repositoryminer with Apache License 2.0 4 votes vote down vote up
private RootModule getRootModule(String name, ClassLoader moduleClassLoader) throws CheckstyleException {
	ModuleFactory factory = new PackageObjectFactory(Checker.class.getPackage().getName() + ".", moduleClassLoader);
	return (RootModule) factory.createModule(name);
}
 
Example #21
Source File: Main.java    From diff-check with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
 * Executes required Checkstyle actions based on passed parameters.
 * @param cliOptions
 *        pojo object that contains all options
 * @return number of violations of ERROR level
 * @throws IOException
 *         when output file could not be found
 * @throws CheckstyleException
 *         when properties file could not be loaded
 */
private static int runCheckstyle(CliOptions cliOptions)
        throws CheckstyleException, IOException {
    // setup the properties
    final Properties props;

    if (cliOptions.propertiesLocation == null) {
        props = System.getProperties();
    }
    else {
        props = loadProperties(new File(cliOptions.propertiesLocation));
    }

    // create a configuration
    final ThreadModeSettings multiThreadModeSettings =
            new ThreadModeSettings(
                    cliOptions.checkerThreadsNumber, cliOptions.treeWalkerThreadsNumber);

    final ConfigurationLoader.IgnoredModulesOptions ignoredModulesOptions;
    if (cliOptions.executeIgnoredModules) {
        ignoredModulesOptions = ConfigurationLoader.IgnoredModulesOptions.EXECUTE;
    }
    else {
        ignoredModulesOptions = ConfigurationLoader.IgnoredModulesOptions.OMIT;
    }

    final Configuration config = ConfigurationLoader.loadConfiguration(
            cliOptions.configLocation, new PropertiesExpander(props),
            ignoredModulesOptions, multiThreadModeSettings);

    // create RootModule object and run it
    final int errorCounter;
    final ClassLoader moduleClassLoader = Checker.class.getClassLoader();
    final RootModule rootModule = getRootModule(config.getName(), moduleClassLoader);

    try {
        final AuditListener listener;
        if (cliOptions.generateXpathSuppressionsFile) {
            // create filter to print generated xpath suppressions file
            final Configuration treeWalkerConfig = getTreeWalkerConfig(config);
            if (treeWalkerConfig != null) {
                final DefaultConfiguration moduleConfig =
                        new DefaultConfiguration(
                                XpathFileGeneratorAstFilter.class.getName());
                moduleConfig.addAttribute(OPTION_TAB_WIDTH_NAME,
                        Integer.toString(cliOptions.tabWidth));
                ((DefaultConfiguration) treeWalkerConfig).addChild(moduleConfig);
            }

            listener = new XpathFileGeneratorAuditListener(System.out,
                    AutomaticBean.OutputStreamOptions.NONE);
        }
        else {
            listener = createListener(cliOptions.format,
                    cliOptions.outputLocation);
        }

        rootModule.setModuleClassLoader(moduleClassLoader);
        rootModule.configure(config);
        rootModule.addListener(listener);

        if (CollectionUtils.isNotEmpty(DIFF_ENTRY_LIST) && rootModule instanceof Checker) {
            Checker checker = (Checker) rootModule;
            checker.addFilter(new DiffLineFilter(DIFF_ENTRY_LIST));
        }

        // run RootModule
        errorCounter = rootModule.process(cliOptions.files);
    }
    finally {
        rootModule.destroy();
    }

    return errorCounter;
}
 
Example #22
Source File: Main.java    From diff-check with GNU Lesser General Public License v2.1 3 votes vote down vote up
/**
 * Creates a new instance of the root module that will control and run
 * Checkstyle.
 * @param name The name of the module. This will either be a short name that
 *        will have to be found or the complete package name.
 * @param moduleClassLoader Class loader used to load the root module.
 * @return The new instance of the root module.
 * @throws CheckstyleException if no module can be instantiated from name
 */
private static RootModule getRootModule(String name, ClassLoader moduleClassLoader)
        throws CheckstyleException {
    final ModuleFactory factory = new PackageObjectFactory(
            Checker.class.getPackage().getName(), moduleClassLoader);

    return (RootModule) factory.createModule(name);
}