com.puppycrawl.tools.checkstyle.api.CheckstyleException Java Examples
The following examples show how to use
com.puppycrawl.tools.checkstyle.api.CheckstyleException.
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: Main.java From diff-check with GNU Lesser General Public License v2.1 | 6 votes |
/** * Loads properties from a File. * @param file * the properties file * @return the properties in file * @throws CheckstyleException * when could not load properties file */ private static Properties loadProperties(File file) throws CheckstyleException { final Properties properties = new Properties(); try (InputStream stream = Files.newInputStream(file.toPath())) { properties.load(stream); } catch (final IOException ex) { final LocalizedMessage loadPropertiesExceptionMessage = new LocalizedMessage(1, Definitions.CHECKSTYLE_BUNDLE, LOAD_PROPERTIES_EXCEPTION, new String[] {file.getAbsolutePath()}, null, Main.class, null); throw new CheckstyleException(loadPropertiesExceptionMessage.getMessage(), ex); } return properties; }
Example #2
Source File: ClassFileSetCheck.java From contribution with GNU Lesser General Public License v2.1 | 6 votes |
/** * Instantiates, configures and registers a Check that is specified * in the provided configuration. * @see com.puppycrawl.tools.checkstyle.api.AutomaticBean */ public void setupChild(Configuration aChildConf) throws CheckstyleException { // TODO: improve the error handing final String name = aChildConf.getName(); final Object module = mModuleFactory.createModule(name); if (!(module instanceof AbstractCheckVisitor)) { throw new CheckstyleException( "ClassFileSet is not allowed as a parent of " + name); } final AbstractCheckVisitor c = (AbstractCheckVisitor) module; c.contextualize(mChildContext); c.configure(aChildConf); c.init(); registerCheck(c); }
Example #3
Source File: MailLogger.java From contribution with GNU Lesser General Public License v2.1 | 6 votes |
/** * Gets the value of a property. * * @param aProperties Properties to obtain value from. * @param aName suffix of property name. "MailLogger." will be * prepended internally. * @param aDefaultValue value returned if not present in the properties. * Set to null to make required. * @return The value of the property, or default value. * @throws CheckstyleException if no default value is specified and the * property is not present in properties. */ private String getValue(Properties aProperties, String aName, String aDefaultValue) throws CheckstyleException { final String propertyName = "MailLogger." + aName; String value = (String) aProperties.get(propertyName); if (value == null) { value = aDefaultValue; } if (value == null) { throw new CheckstyleException( "Missing required parameter: " + propertyName); } return value; }
Example #4
Source File: MetadataFactory.java From eclipse-cs with GNU Lesser General Public License v2.1 | 6 votes |
/** * Helper method to get all potential metadata files using the checkstyle_packages.xml as base * where to look. It is not guaranteed that the files returned acutally exist. * * @return the collection of potential metadata files. * @throws CheckstylePluginException * an unexpected exception ocurred */ private static Collection<String> getAllPotentialMetadataFiles(ClassLoader classLoader) throws CheckstylePluginException { Collection<String> potentialMetadataFiles = new ArrayList<>(); Set<String> packages = null; try { packages = PackageNamesLoader.getPackageNames(classLoader); } catch (CheckstyleException e) { CheckstylePluginException.rethrow(e); } for (String packageName : packages) { String metaFileLocation = packageName.replace('.', '/'); if (!metaFileLocation.endsWith("/")) { metaFileLocation = metaFileLocation + "/"; } metaFileLocation = metaFileLocation + METADATA_FILENAME; potentialMetadataFiles.add(metaFileLocation); } return potentialMetadataFiles; }
Example #5
Source File: ClassFileSetCheck.java From cacheonix-core with GNU Lesser General Public License v2.1 | 6 votes |
/** * Instantiates, configures and registers a Check that is specified * in the provided configuration. * @see com.puppycrawl.tools.checkstyle.api.AutomaticBean */ public void setupChild(Configuration aChildConf) throws CheckstyleException { // TODO: improve the error handing final String name = aChildConf.getName(); final Object module = mModuleFactory.createModule(name); if (!(module instanceof AbstractCheckVisitor)) { throw new CheckstyleException( "ClassFileSet is not allowed as a parent of " + name); } final AbstractCheckVisitor c = (AbstractCheckVisitor) module; c.contextualize(mChildContext); c.configure(aChildConf); c.init(); registerCheck(c); }
Example #6
Source File: MailLogger.java From cacheonix-core with GNU Lesser General Public License v2.1 | 6 votes |
/** * Gets the value of a property. * * @param aProperties Properties to obtain value from. * @param aName suffix of property name. "MailLogger." will be * prepended internally. * @param aDefaultValue value returned if not present in the properties. * Set to null to make required. * @return The value of the property, or default value. * @throws CheckstyleException if no default value is specified and the * property is not present in properties. */ private String getValue(Properties aProperties, String aName, String aDefaultValue) throws CheckstyleException { final String propertyName = "MailLogger." + aName; String value = (String) aProperties.get(propertyName); if (value == null) { value = aDefaultValue; } if (value == null) { throw new CheckstyleException( "Missing required parameter: " + propertyName); } return value; }
Example #7
Source File: CheckstyleExecutorTest.java From sonar-checkstyle with GNU Lesser General Public License v3.0 | 6 votes |
private static CheckstyleConfiguration mockConf() throws CheckstyleException { final CheckstyleConfiguration conf = mock(CheckstyleConfiguration.class); when(conf.getCharset()).thenReturn(Charset.defaultCharset()); when(conf.getCheckstyleConfiguration()).thenReturn( CheckstyleConfiguration.toCheckstyleConfiguration( new File("test-resources/checkstyle-conf.xml"))); final File file = new File("test-resources/Hello.java"); final File file2 = new File("test-resources/World.java"); when(conf.getSourceFiles()).thenReturn(Arrays.asList( new DefaultInputFile( new DefaultIndexedFile("", file.getParentFile().toPath(), file.getName(), "java"), DefaultInputFile::checkMetadata), new DefaultInputFile( new DefaultIndexedFile("", file2.getParentFile().toPath(), file2.getName(), "java"), DefaultInputFile::checkMetadata) )); return conf; }
Example #8
Source File: CheckstyleSourceCodeFileAnalyzerPlugin.java From coderadar with MIT License | 6 votes |
@Override public FileMetrics analyzeFile(String filepath, byte[] fileContent) throws AnalyzerException { File fileToAnalyze = null; try { fileToAnalyze = createTempFile(fileContent, filepath); auditListener.reset(); checker.process(Collections.singletonList(fileToAnalyze)); return auditListener.getMetrics(); } catch (CheckstyleException | IOException e) { throw new AnalyzerException(e); } finally { if (fileToAnalyze != null && !fileToAnalyze.delete()) { logger.warn("Could not delete temporary file {}", fileToAnalyze); } } }
Example #9
Source File: CheckstyleExecutorTest.java From sonar-checkstyle with GNU Lesser General Public License v3.0 | 6 votes |
@Test public void execute() throws CheckstyleException { final CheckstyleConfiguration conf = mockConf(); final CheckstyleAuditListener listener = mockListener(); final CheckstyleExecutor executor = new CheckstyleExecutor(conf, listener); executor.execute(context); verify(listener, times(1)).auditStarted(any(AuditEvent.class)); verify(listener, times(1)).auditFinished(any(AuditEvent.class)); final InOrder inOrder = Mockito.inOrder(listener); final ArgumentCaptor<AuditEvent> captor = ArgumentCaptor.forClass(AuditEvent.class); inOrder.verify(listener).fileStarted(captor.capture()); assertThat(captor.getValue().getFileName()).matches(".*Hello.java"); inOrder.verify(listener).fileFinished(captor.capture()); assertThat(captor.getValue().getFileName()).matches(".*Hello.java"); inOrder.verify(listener).fileStarted(captor.capture()); assertThat(captor.getValue().getFileName()).matches(".*World.java"); inOrder.verify(listener).fileFinished(captor.capture()); assertThat(captor.getValue().getFileName()).matches(".*World.java"); verify(listener, atLeast(1)).addError(captor.capture()); final AuditEvent event = captor.getValue(); assertThat(event.getFileName()).matches(".*Hello.java"); assertThat(event.getSourceName()).matches( "com.puppycrawl.tools.checkstyle.checks.coding.EmptyStatementCheck"); }
Example #10
Source File: Auditor.java From eclipse-cs with GNU Lesser General Public License v2.1 | 6 votes |
private void handleCheckstyleFailure(IProject project, CheckstyleException e) throws CheckstylePluginException { try { CheckstyleLog.log(e); // remove pre-existing project level marker project.deleteMarkers(CheckstyleMarker.MARKER_ID, false, IResource.DEPTH_ZERO); Map<String, Object> attrs = new HashMap<>(); attrs.put(IMarker.PRIORITY, Integer.valueOf(IMarker.PRIORITY_NORMAL)); attrs.put(IMarker.SEVERITY, Integer.valueOf(IMarker.SEVERITY_ERROR)); attrs.put(IMarker.MESSAGE, NLS.bind(Messages.Auditor_msgMsgCheckstyleInternalError, null)); IMarker projectMarker = project.createMarker(CheckstyleMarker.MARKER_ID); projectMarker.setAttributes(attrs); } catch (CoreException ce) { CheckstylePluginException.rethrow(e); } }
Example #11
Source File: CheckstyleExecutorTest.java From sonar-checkstyle with GNU Lesser General Public License v3.0 | 5 votes |
@Test public void executeException() throws CheckstyleException { thrown.expect(IllegalStateException.class); thrown.expectMessage("Can not execute Checkstyle"); final CheckstyleConfiguration conf = mockConf(); final CheckstyleExecutor executor = new CheckstyleExecutor(conf, null); executor.execute(context); }
Example #12
Source File: ExternalFileConfigurationType.java From eclipse-cs with GNU Lesser General Public License v2.1 | 5 votes |
/** * Tries to resolve a dynamic location into the real file path. * * @param location * the probably unresolved location string * @return the resolved location * @throws CheckstylePluginException * unexpected error while resolving the dynamic properties */ public static String resolveDynamicLocation(String location) throws CheckstylePluginException { String newLocation = location; try { // support dynamic locations for external configurations while (PropertyUtil.hasUnresolvedProperties(newLocation)) { newLocation = PropertyUtil.replaceProperties(newLocation, DYNAMIC_LOC_RESOLVER); } } catch (CheckstyleException e) { CheckstylePluginException.rethrow(e); } return newLocation; }
Example #13
Source File: PropertyUtil.java From eclipse-cs with GNU Lesser General Public License v2.1 | 5 votes |
/** * Checks if the current value has unresolved properties. * * @param value * the value * @return the resolved property * @throws CheckstyleException * Syntax exception in a property declaration */ public static boolean hasUnresolvedProperties(String value) throws CheckstyleException { if (value != null) { List<String> props = new ArrayList<>(); parsePropertyString(value, new ArrayList<String>(), props); return !props.isEmpty(); } else { return false; } }
Example #14
Source File: PropertyUtil.java From eclipse-cs with GNU Lesser General Public License v2.1 | 5 votes |
/** * Replaces <code>${xxx}</code> style constructions in the given value with the string value of * the corresponding data types. The method is package visible to facilitate testing. * * @param aValue * The string to be scanned for property references. May be <code>null</code>, in which * case this method returns immediately with no effect. * @param aProps * Mapping (String to String) of property names to their values. Must not be * <code>null</code>. * @return the original string with the properties replaced, or <code>null</code> if the original * string is <code>null</code>. Code copied from ant - * http://cvs.apache.org/viewcvs/jakarta-ant/src/main/org/apache/tools/ant/ProjectHelper.java * @throws CheckstyleException * if the string contains an opening <code>${</code> without a closing <code>}</code> */ public static String replaceProperties(String aValue, PropertyResolver aProps) throws CheckstyleException { if (aValue == null) { return null; } final List<String> fragments = new ArrayList<>(); final List<String> propertyRefs = new ArrayList<>(); parsePropertyString(aValue, fragments, propertyRefs); final StringBuffer sb = new StringBuffer(); final Iterator<String> i = fragments.iterator(); final Iterator<String> j = propertyRefs.iterator(); while (i.hasNext()) { String fragment = i.next(); if (fragment == null) { final String propertyName = j.next(); fragment = aProps.resolve(propertyName); if (fragment == null) { throw new CheckstyleException("Property ${" + propertyName //$NON-NLS-1$ + "} has not been set"); //$NON-NLS-1$ } } sb.append(fragment); } return sb.toString(); }
Example #15
Source File: CheckerFactory.java From eclipse-cs with GNU Lesser General Public License v2.1 | 5 votes |
/** * 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 #16
Source File: CTransformationClass.java From eclipse-cs with GNU Lesser General Public License v2.1 | 5 votes |
/** * Method for setting the field attributes. * * @param rule * The checkstyle-rule associated to this class. */ protected final void setRule(final Configuration rule) { final String[] attrs = rule.getAttributeNames(); for (final String att : attrs) { try { mAttributes.put(att, rule.getAttribute(att)); } catch (CheckstyleException e) { // shouldn't happen since we only use existing attribute names throw new RuntimeException(e); } } }
Example #17
Source File: CheckerService.java From vscode-checkstyle with GNU Lesser General Public License v3.0 | 5 votes |
@SuppressWarnings("unchecked") public void setConfiguration(Map<String, Object> config) throws IOException, CheckstyleException { final String configurationFsPath = (String) config.get("path"); final Map<String, String> properties = (Map<String, String>) config.get("properties"); final Properties checkstyleProperties = new Properties(); checkstyleProperties.putAll(properties); checker.configure(ConfigurationLoader.loadConfiguration( configurationFsPath, new PropertiesExpander(checkstyleProperties) )); }
Example #18
Source File: CheckstyleConfiguration.java From sonar-checkstyle with GNU Lesser General Public License v3.0 | 5 votes |
public Configuration getCheckstyleConfiguration() throws CheckstyleException { final File xmlConfig = getXmlDefinitionFile(); LOG.info("Checkstyle configuration: {}", xmlConfig.getAbsolutePath()); final Configuration configuration = toCheckstyleConfiguration(xmlConfig); defineCharset(configuration); return configuration; }
Example #19
Source File: MultiPropertyResolver.java From eclipse-cs with GNU Lesser General Public License v2.1 | 5 votes |
@Override public String resolve(String property) { String value = null; for (int i = 0, size = mChildResolver.size(); i < size; i++) { PropertyResolver aChildResolver = mChildResolver.get(i); value = aChildResolver.resolve(property); if (value != null) { break; } } try { // property chaining - might recurse internally while (PropertyUtil.hasUnresolvedProperties(value)) { value = PropertyUtil.replaceProperties(value, this); } } catch (CheckstyleException e) { throw new RuntimeException(e); } return value; }
Example #20
Source File: CheckstyleExecutorTest.java From sonar-checkstyle with GNU Lesser General Public License v3.0 | 5 votes |
@Test public void generateXmlReportNull() throws CheckstyleException { final CheckstyleConfiguration conf = mockConf(); final File report = new File("target/test-tmp/checkstyle-report.xml"); // delete if exists from a previous run report.delete(); when(conf.getTargetXmlReport()).thenReturn(null); final CheckstyleAuditListener listener = mockListener(); final CheckstyleExecutor executor = new CheckstyleExecutor(conf, listener); executor.execute(context); Assert.assertFalse("Report should NOT exists", report.exists()); }
Example #21
Source File: CommonsLoggingListener.java From cacheonix-core with GNU Lesser General Public License v2.1 | 5 votes |
/** * Creates a <code>CommonsLoggingListener. Initializes its log factory. * @throws CheckstyleException if if the implementation class is not * available or cannot be instantiated. */ public CommonsLoggingListener() throws CheckstyleException { try { mLogFactory = LogFactory.getFactory(); } catch (LogConfigurationException e) { throw new CheckstyleException("log configuration exception", e); } mInitialized = true; }
Example #22
Source File: CommonsLoggingListener.java From contribution with GNU Lesser General Public License v2.1 | 5 votes |
/** * Creates a <code>CommonsLoggingListener. Initializes its log factory. * @throws CheckstyleException if if the implementation class is not * available or cannot be instantiated. */ public CommonsLoggingListener() throws CheckstyleException { try { mLogFactory = LogFactory.getFactory(); } catch (LogConfigurationException e) { throw new CheckstyleException("log configuration exception", e); } mInitialized = true; }
Example #23
Source File: CheckstyleSourceCodeFileAnalyzerPlugin.java From coderadar with MIT License | 5 votes |
public CheckstyleSourceCodeFileAnalyzerPlugin() { try { init(createDefaultConfiguration()); } catch (CheckstyleException e) { throw new AnalyzerException(e); } }
Example #24
Source File: CheckstyleSourceCodeFileAnalyzerPlugin.java From coderadar with MIT License | 5 votes |
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 #25
Source File: CheckConfigurationTester.java From eclipse-cs with GNU Lesser General Public License v2.1 | 5 votes |
/** * Tests a configuration if there are unresolved properties. * * @return the list of unresolved properties as ResolvableProperty values. * @throws CheckstylePluginException * most likely the configuration file could not be found */ public List<ResolvableProperty> getUnresolvedProperties() throws CheckstylePluginException { CheckstyleConfigurationFile configFile = mCheckConfiguration.getCheckstyleConfiguration(); PropertyResolver resolver = configFile.getPropertyResolver(); // set the project context if the property resolver needs the // context if (mContextProject != null && resolver instanceof IContextAware) { ((IContextAware) resolver).setProjectContext(mContextProject); } MissingPropertyCollector collector = new MissingPropertyCollector(); if (resolver instanceof MultiPropertyResolver) { ((MultiPropertyResolver) resolver).addPropertyResolver(collector); } else { MultiPropertyResolver multiResolver = new MultiPropertyResolver(); multiResolver.addPropertyResolver(resolver); multiResolver.addPropertyResolver(collector); resolver = multiResolver; } InputSource in = null; try { in = configFile.getCheckConfigFileInputSource(); ConfigurationLoader.loadConfiguration(in, resolver, IgnoredModulesOptions.EXECUTE); } catch (CheckstyleException e) { CheckstylePluginException.rethrow(e); } finally { Closeables.closeQuietly(in.getByteStream()); } return collector.getUnresolvedProperties(); }
Example #26
Source File: CheckStyleExecutor.java From repositoryminer with Apache License 2.0 | 5 votes |
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 #27
Source File: NoHttpCheck.java From nohttp with Apache License 2.0 | 5 votes |
@Override protected void processFiltered(File file, FileText fileText) throws CheckstyleException { int lineNum = 0; for (int index = 0; index < fileText.size(); index++) { final String line = fileText.get(index); lineNum++; List<HttpMatchResult> results = this.matcher.findHttp(line); for(HttpMatchResult result : results) { log(lineNum, result.getStart() + 1, "nohttp", result.getHttp()); } } }
Example #28
Source File: NoHttpCheckITest.java From nohttp with Apache License 2.0 | 5 votes |
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 #29
Source File: CheckstyleProcessor.java From sputnik with Apache License 2.0 | 5 votes |
@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 #30
Source File: SpringHeaderCheck.java From spring-javaformat with Apache License 2.0 | 5 votes |
@Override protected void finishLocalSetup() throws CheckstyleException { try { this.check = createCheck(this.headerType, this.headerFile); String packageInfoHeaderType = this.packageInfoHeaderType != null ? this.packageInfoHeaderType : this.headerType; URI packageInfoHeaderFile = this.packageInfoHeaderFile != null ? this.packageInfoHeaderFile : this.headerFile; this.packageInfoCheck = createCheck(packageInfoHeaderType, packageInfoHeaderFile); } catch (IOException ex) { throw new IllegalStateException(ex); } }