下面列出了org.apache.commons.logging.LogConfigurationException#com.puppycrawl.tools.checkstyle.api.CheckstyleException 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* 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;
}
/**
* 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;
}
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);
}
}
@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");
}
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;
}
/**
* 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;
}
/**
* 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);
}
/**
* 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;
}
/**
* 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);
}
@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);
}
}
}
@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());
}
}
}
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;
}
@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);
}
}
@Override
public Object createModule(String name) throws CheckstyleException {
Object module = this.moduleFactory.createModule(name);
if (module instanceof AbstractCheck) {
module = filter((AbstractCheck) module);
}
return module;
}
private Configuration loadConfiguration(InputStream inputStream, PropertyResolver propertyResolver) {
try {
InputSource inputSource = new InputSource(inputStream);
return ConfigurationLoader.loadConfiguration(inputSource, propertyResolver, IgnoredModulesOptions.EXECUTE);
}
catch (CheckstyleException ex) {
throw new IllegalStateException(ex);
}
}
private Object createModule(Configuration configuration) {
String name = configuration.getName();
try {
Object module = this.moduleFactory.createModule(name);
if (module instanceof AutomaticBean) {
initialize(configuration, (AutomaticBean) module);
}
return module;
}
catch (CheckstyleException ex) {
throw new IllegalStateException("cannot initialize module " + name + " - " + ex.getMessage(), ex);
}
}
@Override
protected void processFiltered(File file, FileText fileText) throws CheckstyleException {
SortedSet<LocalizedMessage> messages = new TreeSet<>();
for (FileSetCheck check : this.checks) {
messages.addAll(check.process(file, fileText));
}
addMessages(messages);
}
private ModuleFactory createModuleFactory() {
try {
ClassLoader classLoader = AbstractCheck.class.getClassLoader();
Set<String> packageNames = PackageNamesLoader.getPackageNames(classLoader);
return new PackageObjectFactory(packageNames, classLoader);
}
catch (CheckstyleException ex) {
throw new IllegalStateException(ex);
}
}
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;
}
private void processAndCheckResults(RootModule rootModule) throws CheckstyleException {
rootModule.addListener(this.parameter.getAssertionsListener());
if (!RUNNING_ON_WINDOWS) {
printDebugInfo(this.parameter.getSourceFile());
}
rootModule.process(Arrays.asList(this.parameter.getSourceFile()));
}
private void printDebugInfo(File file) throws CheckstyleException {
try {
System.out.println(AstTreeStringPrinter.printFileAst(file, JavaParser.Options.WITHOUT_COMMENTS));
}
catch (IOException ex) {
}
}
/**
* 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();
}
@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;
}
/**
* 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;
}
/**
* 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;
}
}
/**
* 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();
}
/**
* 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;
}
/**
* 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);
}
}
}
@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)
));
}
public Configuration getCheckstyleConfiguration() throws CheckstyleException {
final File xmlConfig = getXmlDefinitionFile();
LOG.info("Checkstyle configuration: {}", xmlConfig.getAbsolutePath());
final Configuration configuration = toCheckstyleConfiguration(xmlConfig);
defineCharset(configuration);
return configuration;
}