Skip to content

Commit

Permalink
Issue #45: LineLenght violations are resolved in main code
Browse files Browse the repository at this point in the history
  • Loading branch information
romani committed Dec 28, 2016
1 parent 6039316 commit b3d788e
Show file tree
Hide file tree
Showing 9 changed files with 71 additions and 34 deletions.
1 change: 0 additions & 1 deletion checkstyle-sonar-plugin/config/suppressions.xml
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@
<suppress checks="ImportControl" files=".*[\\/]src[\\/]main[\\/]"/>
<suppress checks="DesignForExtension" files=".*[\\/]src[\\/]main[\\/]"/>
<suppress checks="WriteTag" files=".*[\\/]src[\\/]main[\\/]"/>
<suppress checks="LineLength" files=".*[\\/]src[\\/]main[\\/]"/>
<suppress checks="DeclarationOrder" files=".*[\\/]src[\\/]main[\\/]"/>
<suppress checks="RightCurly" files=".*[\\/]src[\\/]main[\\/]"/>
<suppress checks="IllegalCatch" files=".*[\\/]src[\\/]main[\\/]"/>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,8 @@ public class CheckstyleAuditListener implements AuditListener, BatchExtension {
private final ResourcePerspectives perspectives;
private InputFile currentResource;

public CheckstyleAuditListener(RuleFinder ruleFinder, FileSystem fs, ResourcePerspectives perspectives) {
public CheckstyleAuditListener(RuleFinder ruleFinder, FileSystem fs,
ResourcePerspectives perspectives) {
this.ruleFinder = ruleFinder;
this.fs = fs;
this.perspectives = perspectives;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,8 @@ public class CheckstyleConfiguration implements BatchExtension {
private final Settings conf;
private final FileSystem fileSystem;

public CheckstyleConfiguration(Settings conf, CheckstyleProfileExporter confExporter, RulesProfile profile, FileSystem fileSystem) {
public CheckstyleConfiguration(Settings conf, CheckstyleProfileExporter confExporter,
RulesProfile profile, FileSystem fileSystem) {
this.conf = conf;
this.confExporter = confExporter;
this.profile = profile;
Expand All @@ -68,13 +69,15 @@ public File getXmlDefinitionFile() {
Writer writer = null;
File xmlFile = new File(fileSystem.workDir(), "checkstyle.xml");
try {
writer = new OutputStreamWriter(new FileOutputStream(xmlFile, false), StandardCharsets.UTF_8);
writer = new OutputStreamWriter(new FileOutputStream(xmlFile, false),
StandardCharsets.UTF_8);
confExporter.exportProfile(profile, writer);
writer.flush();
return xmlFile;

} catch (IOException e) {
throw new IllegalStateException("Fail to save the Checkstyle configuration to " + xmlFile.getPath(), e);
throw new IllegalStateException("Fail to save the Checkstyle configuration to "
+ xmlFile.getPath(), e);

} finally {
IOUtils.closeQuietly(writer);
Expand Down Expand Up @@ -107,7 +110,8 @@ public Configuration getCheckstyleConfiguration() throws CheckstyleException {

@VisibleForTesting
static Configuration toCheckstyleConfiguration(File xmlConfig) throws CheckstyleException {
return ConfigurationLoader.loadConfiguration(xmlConfig.getAbsolutePath(), new PropertiesExpander(new Properties()));
return ConfigurationLoader.loadConfiguration(xmlConfig.getAbsolutePath(),
new PropertiesExpander(new Properties()));
}

private void defineCharset(Configuration configuration) {
Expand All @@ -118,7 +122,9 @@ private void defineCharset(Configuration configuration) {
}

private void defineModuleCharset(Configuration module) {
if (("Checker".equals(module.getName()) || "com.puppycrawl.tools.checkstyle.Checker".equals(module.getName())) && module instanceof DefaultConfiguration) {
if (("Checker".equals(module.getName())
|| "com.puppycrawl.tools.checkstyle.Checker".equals(module.getName()))
&& module instanceof DefaultConfiguration) {
Charset charset = getCharset();
LOG.info("Checkstyle charset: " + charset.name());
((DefaultConfiguration) module).addAttribute("charset", charset.name());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,8 @@ public class CheckstyleExecutor implements BatchExtension {
private final CheckstyleAuditListener listener;
private final JavaResourceLocator javaResourceLocator;

public CheckstyleExecutor(CheckstyleConfiguration configuration, CheckstyleAuditListener listener, JavaResourceLocator javaResourceLocator) {
public CheckstyleExecutor(CheckstyleConfiguration configuration, CheckstyleAuditListener listener,
JavaResourceLocator javaResourceLocator) {
this.configuration = configuration;
this.listener = listener;
this.javaResourceLocator = javaResourceLocator;
Expand All @@ -60,7 +61,8 @@ public CheckstyleExecutor(CheckstyleConfiguration configuration, CheckstyleAudit
* Execute Checkstyle and return the generated XML report.
*/
public void execute() {
TimeProfiler profiler = new TimeProfiler().start("Execute Checkstyle " + CheckstyleVersion.getVersion());
TimeProfiler profiler =
new TimeProfiler().start("Execute Checkstyle " + CheckstyleVersion.getVersion());
ClassLoader initialClassLoader = Thread.currentThread().getContextClassLoader();
Thread.currentThread().setContextClassLoader(PackageNamesLoader.class.getClassLoader());
URLClassLoader projectClassloader = createClassloader();
Expand Down Expand Up @@ -103,7 +105,8 @@ URL getUrl(URI uri) {
try {
return uri.toURL();
} catch (MalformedURLException e) {
throw new IllegalStateException("Fail to create the project classloader. Classpath element is invalid: " + uri, e);
throw new IllegalStateException("Fail to create the project classloader. "
+ "Classpath element is invalid: " + uri, e);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,9 +43,14 @@ public List getExtensions() {
.subCategory(CHECKSTYLE_SUB_CATEGORY_NAME)
.name("Filters")
.description(
"Checkstyle supports four error filtering mechanisms: <code>SuppressionCommentFilter</code>, <code>SuppressWithNearbyCommentFilter</code>, "
+ "<code>SuppressionFilter</code>, and <code>SuppressWarningsFilter</code>.This property allows the configuration of those filters with a "
+ "native XML format. See the <a href='http://checkstyle.sourceforge.net/config.html'>Checkstyle</a> configuration for more information.")
"Checkstyle supports four error filtering mechanisms: "
+ "<code>SuppressionCommentFilter</code>, "
+ "<code>SuppressWithNearbyCommentFilter</code>, "
+ "<code>SuppressionFilter</code>, and <code>SuppressWarningsFilter</code>."
+ "This property allows the configuration of those filters with a "
+ "native XML format. See the "
+ "<a href='http://checkstyle.sourceforge.net/config.html'>Checkstyle</a> "
+ "configuration for more information.")
.type(PropertyType.TEXT)
.onQualifiers(Qualifiers.PROJECT, Qualifiers.MODULE)
.build(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,9 @@

public class CheckstyleProfileExporter extends ProfileExporter {

public static final String DOCTYPE_DECLARATION = "<!DOCTYPE module PUBLIC \"-//Puppy Crawl//DTD Check Configuration 1.2//EN\" \"http://www.puppycrawl.com/dtds/configuration_1_2.dtd\">";
public static final String DOCTYPE_DECLARATION =
"<!DOCTYPE module PUBLIC \"-//Puppy Crawl//DTD Check Configuration 1.2//EN\" "
+ "\"http://www.puppycrawl.com/dtds/configuration_1_2.dtd\">";
private final Settings settings;
private static final String CLOSE_MODULE = "</module>";

Expand All @@ -53,7 +55,9 @@ public CheckstyleProfileExporter(Settings settings) {
@Override
public void exportProfile(RulesProfile profile, Writer writer) {
try {
ListMultimap<String, ActiveRule> activeRulesByConfigKey = arrangeByConfigKey(profile.getActiveRulesByRepository(CheckstyleConstants.REPOSITORY_KEY));
ListMultimap<String, ActiveRule> activeRulesByConfigKey =
arrangeByConfigKey(
profile.getActiveRulesByRepository(CheckstyleConstants.REPOSITORY_KEY));
generateXml(writer, activeRulesByConfigKey);

} catch (IOException e) {
Expand All @@ -62,7 +66,8 @@ public void exportProfile(RulesProfile profile, Writer writer) {

}

private void generateXml(Writer writer, ListMultimap<String, ActiveRule> activeRulesByConfigKey) throws IOException {
private void generateXml(Writer writer, ListMultimap<String, ActiveRule> activeRulesByConfigKey)
throws IOException {
appendXmlHeader(writer);
appendCustomFilters(writer);
appendCheckerModules(writer, activeRulesByConfigKey);
Expand All @@ -84,7 +89,8 @@ private void appendCustomFilters(Writer writer) throws IOException {
}
}

private static void appendCheckerModules(Writer writer, ListMultimap<String, ActiveRule> activeRulesByConfigKey) throws IOException {
private static void appendCheckerModules(Writer writer, ListMultimap<String,
ActiveRule> activeRulesByConfigKey) throws IOException {
for (String configKey : activeRulesByConfigKey.keySet()) {
if (!isInTreeWalker(configKey)) {
List<ActiveRule> activeRules = activeRulesByConfigKey.get(configKey);
Expand All @@ -95,7 +101,8 @@ private static void appendCheckerModules(Writer writer, ListMultimap<String, Act
}
}

private void appendTreeWalker(Writer writer, ListMultimap<String, ActiveRule> activeRulesByConfigKey) throws IOException {
private void appendTreeWalker(Writer writer, ListMultimap<String,
ActiveRule> activeRulesByConfigKey) throws IOException {
writer.append("<module name=\"TreeWalker\">");
writer.append("<module name=\"FileContentsHolder\"/> ");
if (isSuppressWarningsEnabled()) {
Expand Down Expand Up @@ -150,12 +157,14 @@ private static void appendModule(Writer writer, ActiveRule activeRule) throws IO
if (activeRule.getRule().getTemplate() != null) {
appendModuleProperty(writer, "id", activeRule.getRuleKey());
}
appendModuleProperty(writer, "severity", CheckstyleSeverityUtils.toSeverity(activeRule.getSeverity()));
appendModuleProperty(writer, "severity",
CheckstyleSeverityUtils.toSeverity(activeRule.getSeverity()));
appendRuleParameters(writer, activeRule);
writer.append(CLOSE_MODULE);
}

private static void appendRuleParameters(Writer writer, ActiveRule activeRule) throws IOException {
private static void appendRuleParameters(Writer writer, ActiveRule activeRule)
throws IOException {
for (RuleParam ruleParam : activeRule.getRule().getParams()) {
String value = activeRule.getParameter(ruleParam.getKey());
if (StringUtils.isNotBlank(value)) {
Expand All @@ -164,7 +173,8 @@ private static void appendRuleParameters(Writer writer, ActiveRule activeRule) t
}
}

private static void appendModuleProperty(Writer writer, String propertyKey, String propertyValue) throws IOException {
private static void appendModuleProperty(Writer writer, String propertyKey, String propertyValue)
throws IOException {
if (StringUtils.isNotBlank(propertyValue)) {
writer.append("<property name=\"");
StringEscapeUtils.escapeXml(writer, propertyKey);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -104,10 +104,12 @@ public RulesProfile importProfile(Reader reader, ValidationMessages messages) {
Map<String, String> treewalkerModuleProperties = Maps.newHashMap(rootModuleProperties);
treewalkerModuleProperties.putAll(treewalkerModule.properties);

processModule(profile, CHECKER_MODULE + "/" + TREEWALKER_MODULE + "/", treewalkerModule.name, treewalkerModuleProperties, messages);
processModule(profile, CHECKER_MODULE + "/" + TREEWALKER_MODULE + "/",
treewalkerModule.name, treewalkerModuleProperties, messages);
}
} else {
processModule(profile, CHECKER_MODULE + "/", rootModule.name, rootModuleProperties, messages);
processModule(profile, CHECKER_MODULE + "/", rootModule.name,
rootModuleProperties, messages);
}
}

Expand All @@ -128,7 +130,8 @@ private static SMInputFactory initStax() {
return new SMInputFactory(xmlFactory);
}

private void processModule(RulesProfile profile, String path, String moduleName, Map<String, String> properties, ValidationMessages messages) {
private void processModule(RulesProfile profile, String path, String moduleName,
Map<String, String> properties, ValidationMessages messages) {
if (isFilter(moduleName)) {
messages.addWarningText("Checkstyle filters are not imported: " + moduleName);

Expand All @@ -139,7 +142,8 @@ private void processModule(RulesProfile profile, String path, String moduleName,

@VisibleForTesting
static boolean isIgnored(String configKey) {
return StringUtils.equals(configKey, "FileContentsHolder") || StringUtils.equals(configKey, "SuppressWarningsHolder");
return StringUtils.equals(configKey, "FileContentsHolder")
|| StringUtils.equals(configKey, "SuppressWarningsHolder");
}

@VisibleForTesting
Expand All @@ -152,17 +156,20 @@ static boolean isFilter(String configKey) {
return false;
}

private void processRule(RulesProfile profile, String path, String moduleName, Map<String, String> properties, ValidationMessages messages) {
private void processRule(RulesProfile profile, String path, String moduleName,
Map<String, String> properties, ValidationMessages messages) {
Rule rule;
String id = properties.get("id");
String warning;
if (StringUtils.isNotBlank(id)) {
rule = ruleFinder.find(RuleQuery.create().withRepositoryKey(CheckstyleConstants.REPOSITORY_KEY).withKey(id));
rule = ruleFinder.find(RuleQuery.create()
.withRepositoryKey(CheckstyleConstants.REPOSITORY_KEY).withKey(id));
warning = "Checkstyle rule with key '" + id + "' not found";

} else {
String configKey = path + moduleName;
rule = ruleFinder.find(RuleQuery.create().withRepositoryKey(CheckstyleConstants.REPOSITORY_KEY).withConfigKey(configKey));
rule = ruleFinder.find(RuleQuery.create()
.withRepositoryKey(CheckstyleConstants.REPOSITORY_KEY).withConfigKey(configKey));
warning = "Checkstyle rule with config key '" + configKey + "' not found";
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,8 @@ public void define(Context context) {
.setName(CheckstyleConstants.REPOSITORY_NAME);

try {
extractRulesData(repository, "/org/sonar/plugins/checkstyle/rules.xml", "/org/sonar/l10n/checkstyle/rules/checkstyle");
extractRulesData(repository, "/org/sonar/plugins/checkstyle/rules.xml",
"/org/sonar/l10n/checkstyle/rules/checkstyle");
} catch (IOException e) {
throw new IllegalStateException("Exception during extractRulesData", e);
}
Expand All @@ -48,13 +49,16 @@ public void define(Context context) {
}

@VisibleForTesting
static void extractRulesData(NewRepository repository, String xmlRulesFilePath, String htmlDescriptionFolder) throws IOException {
static void extractRulesData(NewRepository repository, String xmlRulesFilePath,
String htmlDescriptionFolder) throws IOException {
RulesDefinitionXmlLoader ruleLoader = new RulesDefinitionXmlLoader();
try (InputStream resource = CheckstyleRulesDefinition.class.getResourceAsStream(xmlRulesFilePath)) {
try (InputStream resource =
CheckstyleRulesDefinition.class.getResourceAsStream(xmlRulesFilePath)) {
ruleLoader.load(repository, resource, "UTF-8");
}
ExternalDescriptionLoader.loadHtmlDescriptions(repository, htmlDescriptionFolder);
try (InputStream resource = CheckstyleRulesDefinition.class.getResourceAsStream("/org/sonar/l10n/checkstyle.properties")) {
try (InputStream resource = CheckstyleRulesDefinition.class
.getResourceAsStream("/org/sonar/l10n/checkstyle.properties")) {
PropertyFileLoader.loadNames(repository, resource);
}
SqaleXmlLoader.load(repository, "/com/sonar/sqale/checkstyle-model.xml");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,8 @@
public enum CheckstyleVersion {
INSTANCE;

private static final String PROPERTIES_PATH = "/org/sonar/plugins/checkstyle/checkstyle-plugin.properties";
private static final String PROPERTIES_PATH =
"/org/sonar/plugins/checkstyle/checkstyle-plugin.properties";
private String version;

CheckstyleVersion() {
Expand All @@ -40,7 +41,8 @@ public enum CheckstyleVersion {
this.version = properties.getProperty("checkstyle.version");

} catch (IOException e) {
LoggerFactory.getLogger(getClass()).warn("Can not load the Checkstyle version from the file " + PROPERTIES_PATH, e);
LoggerFactory.getLogger(getClass()).warn("Can not load the Checkstyle version from the file "
+ PROPERTIES_PATH, e);
this.version = "";
} finally {
IOUtils.closeQuietly(input);
Expand Down

0 comments on commit b3d788e

Please sign in to comment.