From aeadc1f9129274949daaa57738c7c4550bdfbc7b Mon Sep 17 00:00:00 2001 From: simonbrandhof Date: Mon, 6 Sep 2010 14:08:06 +0000 Subject: SONAR-236 remove deprecated code from checkstyle plugin + display default value of rule parameters in Q profile console --- plugins/sonar-findbugs-plugin/pom.xml | 77 + .../java/org/sonar/plugins/findbugs/Category.java | 44 + .../plugins/findbugs/FindbugsAntConverter.java | 72 + .../findbugs/FindbugsMavenPluginHandler.java | 150 + .../org/sonar/plugins/findbugs/FindbugsPlugin.java | 73 + .../findbugs/FindbugsRulePriorityMapper.java | 53 + .../plugins/findbugs/FindbugsRulesRepository.java | 111 + .../org/sonar/plugins/findbugs/FindbugsSensor.java | 95 + .../plugins/findbugs/FindbugsXmlReportParser.java | 139 + .../java/org/sonar/plugins/findbugs/xml/Bug.java | 67 + .../sonar/plugins/findbugs/xml/ClassFilter.java | 45 + .../sonar/plugins/findbugs/xml/FieldFilter.java | 57 + .../sonar/plugins/findbugs/xml/FindBugsFilter.java | 206 + .../sonar/plugins/findbugs/xml/LocalFilter.java | 45 + .../java/org/sonar/plugins/findbugs/xml/Match.java | 137 + .../sonar/plugins/findbugs/xml/MethodFilter.java | 68 + .../org/sonar/plugins/findbugs/xml/OrFilter.java | 107 + .../sonar/plugins/findbugs/xml/PackageFilter.java | 45 + .../org/sonar/plugins/findbugs/xml/Priority.java | 46 + .../resources/org/sonar/plugins/findbugs/rules.xml | 4316 ++++++++++++++++++++ .../plugins/findbugs/FindbugsAntConverterTest.java | 39 + .../findbugs/FindbugsMavenPluginHandlerTest.java | 189 + .../findbugs/FindbugsRulesRepositoryTest.java | 186 + .../sonar/plugins/findbugs/FindbugsSensorTest.java | 137 + .../org/sonar/plugins/findbugs/FindbugsTests.java | 115 + .../findbugs/FindbugsXmlReportParserTest.java | 82 + .../plugins/findbugs/tools/RulesGenerator.java | 190 + .../plugins/findbugs/xml/FindBugsFilterTest.java | 124 + .../plugins/findbugs/xml/FindBugsXmlTests.java | 33 + .../shouldImportCategories.xml | 6 + .../shouldImportCodes.xml | 6 + .../shouldImportPatterns.xml | 9 + .../findbugs/findbugs-class-without-package.xml | 7 + .../sonar/plugins/findbugs/findbugs-include.xml | 36 + .../org/sonar/plugins/findbugs/findbugsXml.xml | 48 + .../org/sonar/plugins/findbugs/test_header.xml | 3 + .../sonar/plugins/findbugs/test_module_tree.xml | 9 + .../sonar/plugins/findbugs/test_xml_complete.xml | 11 + 38 files changed, 7183 insertions(+) create mode 100644 plugins/sonar-findbugs-plugin/pom.xml create mode 100644 plugins/sonar-findbugs-plugin/src/main/java/org/sonar/plugins/findbugs/Category.java create mode 100644 plugins/sonar-findbugs-plugin/src/main/java/org/sonar/plugins/findbugs/FindbugsAntConverter.java create mode 100644 plugins/sonar-findbugs-plugin/src/main/java/org/sonar/plugins/findbugs/FindbugsMavenPluginHandler.java create mode 100644 plugins/sonar-findbugs-plugin/src/main/java/org/sonar/plugins/findbugs/FindbugsPlugin.java create mode 100644 plugins/sonar-findbugs-plugin/src/main/java/org/sonar/plugins/findbugs/FindbugsRulePriorityMapper.java create mode 100644 plugins/sonar-findbugs-plugin/src/main/java/org/sonar/plugins/findbugs/FindbugsRulesRepository.java create mode 100644 plugins/sonar-findbugs-plugin/src/main/java/org/sonar/plugins/findbugs/FindbugsSensor.java create mode 100644 plugins/sonar-findbugs-plugin/src/main/java/org/sonar/plugins/findbugs/FindbugsXmlReportParser.java create mode 100644 plugins/sonar-findbugs-plugin/src/main/java/org/sonar/plugins/findbugs/xml/Bug.java create mode 100644 plugins/sonar-findbugs-plugin/src/main/java/org/sonar/plugins/findbugs/xml/ClassFilter.java create mode 100644 plugins/sonar-findbugs-plugin/src/main/java/org/sonar/plugins/findbugs/xml/FieldFilter.java create mode 100644 plugins/sonar-findbugs-plugin/src/main/java/org/sonar/plugins/findbugs/xml/FindBugsFilter.java create mode 100644 plugins/sonar-findbugs-plugin/src/main/java/org/sonar/plugins/findbugs/xml/LocalFilter.java create mode 100644 plugins/sonar-findbugs-plugin/src/main/java/org/sonar/plugins/findbugs/xml/Match.java create mode 100644 plugins/sonar-findbugs-plugin/src/main/java/org/sonar/plugins/findbugs/xml/MethodFilter.java create mode 100644 plugins/sonar-findbugs-plugin/src/main/java/org/sonar/plugins/findbugs/xml/OrFilter.java create mode 100644 plugins/sonar-findbugs-plugin/src/main/java/org/sonar/plugins/findbugs/xml/PackageFilter.java create mode 100644 plugins/sonar-findbugs-plugin/src/main/java/org/sonar/plugins/findbugs/xml/Priority.java create mode 100644 plugins/sonar-findbugs-plugin/src/main/resources/org/sonar/plugins/findbugs/rules.xml create mode 100644 plugins/sonar-findbugs-plugin/src/test/java/org/sonar/plugins/findbugs/FindbugsAntConverterTest.java create mode 100644 plugins/sonar-findbugs-plugin/src/test/java/org/sonar/plugins/findbugs/FindbugsMavenPluginHandlerTest.java create mode 100644 plugins/sonar-findbugs-plugin/src/test/java/org/sonar/plugins/findbugs/FindbugsRulesRepositoryTest.java create mode 100644 plugins/sonar-findbugs-plugin/src/test/java/org/sonar/plugins/findbugs/FindbugsSensorTest.java create mode 100644 plugins/sonar-findbugs-plugin/src/test/java/org/sonar/plugins/findbugs/FindbugsTests.java create mode 100644 plugins/sonar-findbugs-plugin/src/test/java/org/sonar/plugins/findbugs/FindbugsXmlReportParserTest.java create mode 100644 plugins/sonar-findbugs-plugin/src/test/java/org/sonar/plugins/findbugs/tools/RulesGenerator.java create mode 100644 plugins/sonar-findbugs-plugin/src/test/java/org/sonar/plugins/findbugs/xml/FindBugsFilterTest.java create mode 100644 plugins/sonar-findbugs-plugin/src/test/java/org/sonar/plugins/findbugs/xml/FindBugsXmlTests.java create mode 100644 plugins/sonar-findbugs-plugin/src/test/resources/org/sonar/plugins/findbugs/FindbugsRulesRepositoryTest/shouldImportCategories.xml create mode 100644 plugins/sonar-findbugs-plugin/src/test/resources/org/sonar/plugins/findbugs/FindbugsRulesRepositoryTest/shouldImportCodes.xml create mode 100644 plugins/sonar-findbugs-plugin/src/test/resources/org/sonar/plugins/findbugs/FindbugsRulesRepositoryTest/shouldImportPatterns.xml create mode 100644 plugins/sonar-findbugs-plugin/src/test/resources/org/sonar/plugins/findbugs/findbugs-class-without-package.xml create mode 100644 plugins/sonar-findbugs-plugin/src/test/resources/org/sonar/plugins/findbugs/findbugs-include.xml create mode 100644 plugins/sonar-findbugs-plugin/src/test/resources/org/sonar/plugins/findbugs/findbugsXml.xml create mode 100644 plugins/sonar-findbugs-plugin/src/test/resources/org/sonar/plugins/findbugs/test_header.xml create mode 100644 plugins/sonar-findbugs-plugin/src/test/resources/org/sonar/plugins/findbugs/test_module_tree.xml create mode 100644 plugins/sonar-findbugs-plugin/src/test/resources/org/sonar/plugins/findbugs/test_xml_complete.xml (limited to 'plugins/sonar-findbugs-plugin') diff --git a/plugins/sonar-findbugs-plugin/pom.xml b/plugins/sonar-findbugs-plugin/pom.xml new file mode 100644 index 00000000000..fa7c322c306 --- /dev/null +++ b/plugins/sonar-findbugs-plugin/pom.xml @@ -0,0 +1,77 @@ + + + 4.0.0 + + org.codehaus.sonar + sonar + 2.3-SNAPSHOT + ../.. + + org.codehaus.sonar.plugins + sonar-findbugs-plugin + sonar-plugin + Sonar :: Plugins :: Findbugs + FindBugs is a program that uses static analysis to look for bugs in Java code. It can detect a variety of common coding mistakes, including thread synchronization problems, misuse of API methods. + + + 1.3.9 + + + + + org.codehaus.sonar + sonar-plugin-api + ${project.version} + + + org.apache.maven + maven-project + provided + + + org.apache.maven + maven-plugin-api + provided + + + org.apache.maven + maven-core + provided + + + org.codehaus.sonar + sonar-testing-harness + test + + + + + + + ${basedir}/src/main/resources + + + ${basedir}/src/test/resources + + + + + org.codehaus.sonar + sonar-packaging-maven-plugin + true + + findbugs + Findbugs + Findbugs ${findbugs.version}.]]> + org.sonar.plugins.findbugs.FindbugsPlugin + + + + maven-deploy-plugin + + true + + + + + \ No newline at end of file diff --git a/plugins/sonar-findbugs-plugin/src/main/java/org/sonar/plugins/findbugs/Category.java b/plugins/sonar-findbugs-plugin/src/main/java/org/sonar/plugins/findbugs/Category.java new file mode 100644 index 00000000000..f9d5c641ff0 --- /dev/null +++ b/plugins/sonar-findbugs-plugin/src/main/java/org/sonar/plugins/findbugs/Category.java @@ -0,0 +1,44 @@ +/* + * Sonar, open source software quality management tool. + * Copyright (C) 2009 SonarSource SA + * mailto:contact AT sonarsource DOT com + * + * Sonar is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * Sonar is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with Sonar; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 + */ +package org.sonar.plugins.findbugs; + +import java.util.HashMap; +import java.util.Map; + +public final class Category { + private final static Map findbugsToSonar = new HashMap(); + + static { + findbugsToSonar.put("BAD_PRACTICE", "Bad practice"); + findbugsToSonar.put("CORRECTNESS", "Correctness"); + findbugsToSonar.put("MT_CORRECTNESS", "Multithreaded correctness"); + findbugsToSonar.put("I18N", "Internationalization"); + findbugsToSonar.put("EXPERIMENTAL", "Experimental"); + findbugsToSonar.put("MALICIOUS_CODE", "Malicious code"); + findbugsToSonar.put("PERFORMANCE", "Performance"); + findbugsToSonar.put("SECURITY", "Security"); + findbugsToSonar.put("STYLE", "Style"); + } + + + public static String findbugsToSonar(String findbugsCategKey) { + return findbugsToSonar.get(findbugsCategKey); + } +} \ No newline at end of file diff --git a/plugins/sonar-findbugs-plugin/src/main/java/org/sonar/plugins/findbugs/FindbugsAntConverter.java b/plugins/sonar-findbugs-plugin/src/main/java/org/sonar/plugins/findbugs/FindbugsAntConverter.java new file mode 100644 index 00000000000..161938c42a8 --- /dev/null +++ b/plugins/sonar-findbugs-plugin/src/main/java/org/sonar/plugins/findbugs/FindbugsAntConverter.java @@ -0,0 +1,72 @@ +/* + * Sonar, open source software quality management tool. + * Copyright (C) 2009 SonarSource SA + * mailto:contact AT sonarsource DOT com + * + * Sonar is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * Sonar is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with Sonar; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 + */ +package org.sonar.plugins.findbugs; + +import org.apache.commons.lang.StringUtils; +import org.sonar.api.resources.Java; + +public final class FindbugsAntConverter { + + private FindbugsAntConverter() { + } + + /** + * Convert the exclusion ant pattern to a java regexp accepted by findbugs + * exclusion file + * + * @param exclusion ant pattern to convert + * @return Exclusion pattern for findbugs + */ + public static String antToJavaRegexpConvertor(String exclusion) { + StringBuilder builder = new StringBuilder("~"); + int offset = 0; + // First **/ or */ is optional + if (exclusion.startsWith("**/")) { + builder.append("(.*\\.)?"); + offset += 3; + } else if (exclusion.startsWith("*/")) { + builder.append("([^\\\\^\\s]*\\.)?"); + offset += 2; + } + for (String suffix : Java.SUFFIXES) { + exclusion = StringUtils.removeEndIgnoreCase(exclusion, "." + suffix); + } + + char[] array = exclusion.toCharArray(); + for (int i = offset; i < array.length; i++) { + char c = array[i]; + if (c == '?') { + builder.append('.'); + } else if (c == '*') { + if (i + 1 < array.length && array[i + 1] == '*') { + builder.append(".*"); + i++; + } else { + builder.append("[^\\\\^\\s]*"); + } + } else if (c == '/') { + builder.append("\\."); + } else { + builder.append(c); + } + } + return builder.toString(); + } +} diff --git a/plugins/sonar-findbugs-plugin/src/main/java/org/sonar/plugins/findbugs/FindbugsMavenPluginHandler.java b/plugins/sonar-findbugs-plugin/src/main/java/org/sonar/plugins/findbugs/FindbugsMavenPluginHandler.java new file mode 100644 index 00000000000..0e6e9164762 --- /dev/null +++ b/plugins/sonar-findbugs-plugin/src/main/java/org/sonar/plugins/findbugs/FindbugsMavenPluginHandler.java @@ -0,0 +1,150 @@ +/* + * Sonar, open source software quality management tool. + * Copyright (C) 2009 SonarSource SA + * mailto:contact AT sonarsource DOT com + * + * Sonar is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * Sonar is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with Sonar; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 + */ +package org.sonar.plugins.findbugs; + +import java.io.File; +import java.io.IOException; + +import org.apache.commons.lang.StringUtils; +import org.sonar.api.CoreProperties; +import org.sonar.api.batch.maven.MavenPlugin; +import org.sonar.api.batch.maven.MavenPluginHandler; +import org.sonar.api.batch.maven.MavenUtils; +import org.sonar.api.profiles.RulesProfile; +import org.sonar.api.resources.Project; +import org.sonar.api.utils.SonarException; +import org.sonar.plugins.findbugs.xml.ClassFilter; +import org.sonar.plugins.findbugs.xml.FindBugsFilter; +import org.sonar.plugins.findbugs.xml.Match; + +public class FindbugsMavenPluginHandler implements MavenPluginHandler { + + private RulesProfile profile; + private FindbugsRulesRepository findbugsRulesRepository; + + public FindbugsMavenPluginHandler(RulesProfile profile, FindbugsRulesRepository findbugsRulesRepository) { + this.profile = profile; + this.findbugsRulesRepository = findbugsRulesRepository; + } + + public String getGroupId() { + return MavenUtils.GROUP_ID_CODEHAUS_MOJO; + } + + public String getArtifactId() { + return "findbugs-maven-plugin"; + } + + public String getVersion() { + // IMPORTANT : the version of the Findbugs lib must be also updated in the pom.xml (property findbugs.version). + return "2.3.1"; + } + + public boolean isFixedVersion() { + return true; + } + + public String[] getGoals() { + return new String[] { "findbugs" }; + } + + public void configure(Project project, MavenPlugin plugin) { + configureClassesDir(project, plugin); + configureBasicParameters(project, plugin); + configureFilters(project, plugin); + } + + private void configureBasicParameters(Project project, MavenPlugin plugin) { + plugin.setParameter("xmlOutput", "true"); + plugin.setParameter("threshold", "Low"); + plugin.setParameter("skip", "false"); + plugin.setParameter("effort", getEffort(project), false); + plugin.setParameter("maxHeap", "" + getMaxHeap(project), false); + String timeout = getTimeout(project); + if (StringUtils.isNotBlank(timeout)) { + plugin.setParameter("timeout", timeout, false); + } + } + + protected void configureFilters(Project project, MavenPlugin plugin) { + try { + String existingIncludeFilterConfig = plugin.getParameter("includeFilterFile"); + String existingExcludeFilterConfig = plugin.getParameter("excludeFilterFile"); + boolean existingConfig = !StringUtils.isBlank(existingIncludeFilterConfig) || !StringUtils.isBlank(existingExcludeFilterConfig); + if ( !project.getReuseExistingRulesConfig() || (project.getReuseExistingRulesConfig() && !existingConfig)) { + File includeXmlFile = saveIncludeConfigXml(project); + plugin.setParameter("includeFilterFile", getPath(includeXmlFile)); + + File excludeXmlFile = saveExcludeConfigXml(project); + plugin.setParameter("excludeFilterFile", getPath(excludeXmlFile)); + } + + } catch (IOException e) { + throw new SonarException("Failed to save the findbugs XML configuration.", e); + } + } + + private String getPath(File file) throws IOException { + // the findbugs maven plugin fails on windows if the path contains backslashes + String path = file.getCanonicalPath(); + return path.replace('\\', '/'); + } + + private void configureClassesDir(Project project, MavenPlugin plugin) { + File classesDir = project.getFileSystem().getBuildOutputDir(); + if (classesDir == null || !classesDir.exists()) { + throw new SonarException("Findbugs needs sources to be compiled. " + + "Please build project or edit pom.xml to set the property before executing sonar."); + } + try { + plugin.setParameter("classFilesDirectory", classesDir.getCanonicalPath()); + } catch (Exception e) { + throw new SonarException("Invalid classes directory", e); + } + } + + private File saveIncludeConfigXml(Project project) throws IOException { + String configuration = findbugsRulesRepository.exportConfiguration(profile); + return project.getFileSystem().writeToWorkingDirectory(configuration, "findbugs-include.xml"); + } + + private File saveExcludeConfigXml(Project project) throws IOException { + FindBugsFilter findBugsFilter = new FindBugsFilter(); + if (project.getExclusionPatterns() != null) { + for (String exclusion : project.getExclusionPatterns()) { + ClassFilter classFilter = new ClassFilter(FindbugsAntConverter.antToJavaRegexpConvertor(exclusion)); + findBugsFilter.addMatch(new Match(classFilter)); + } + } + return project.getFileSystem().writeToWorkingDirectory(findBugsFilter.toXml(), "findbugs-exclude.xml"); + } + + private String getEffort(Project project) { + return project.getConfiguration().getString(CoreProperties.FINDBUGS_EFFORT_PROPERTY, CoreProperties.FINDBUGS_EFFORT_DEFAULT_VALUE); + } + + private int getMaxHeap(Project project) { + return project.getConfiguration().getInt(CoreProperties.FINDBUGS_MAXHEAP_PROPERTY, CoreProperties.FINDBUGS_MAXHEAP_DEFAULT_VALUE); + } + + private String getTimeout(Project project) { + return project.getConfiguration().getString(CoreProperties.FINDBUGS_TIMEOUT_PROPERTY); + } +} diff --git a/plugins/sonar-findbugs-plugin/src/main/java/org/sonar/plugins/findbugs/FindbugsPlugin.java b/plugins/sonar-findbugs-plugin/src/main/java/org/sonar/plugins/findbugs/FindbugsPlugin.java new file mode 100644 index 00000000000..86cf5ea1441 --- /dev/null +++ b/plugins/sonar-findbugs-plugin/src/main/java/org/sonar/plugins/findbugs/FindbugsPlugin.java @@ -0,0 +1,73 @@ +/* + * Sonar, open source software quality management tool. + * Copyright (C) 2009 SonarSource SA + * mailto:contact AT sonarsource DOT com + * + * Sonar is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * Sonar is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with Sonar; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 + */ +package org.sonar.plugins.findbugs; + +import org.sonar.api.*; + +import java.util.ArrayList; +import java.util.List; + +@Properties({ + @Property( + key = CoreProperties.FINDBUGS_EFFORT_PROPERTY, + defaultValue = CoreProperties.FINDBUGS_EFFORT_DEFAULT_VALUE, + name = "Effort", + description = "Effort of the bug finders. Valid values are Min, Default and Max. Setting 'Max' increases precision but also increases memory consumption.", + project = true, + module = true, + global = true), + @Property( + key = CoreProperties.FINDBUGS_MAXHEAP_PROPERTY, + defaultValue = CoreProperties.FINDBUGS_MAXHEAP_DEFAULT_VALUE+"", + name = "Max Heap", + description = "Maximum Java heap size in megabytes (default=512).", + project = true, + module = true, + global = true), + @Property( + key = CoreProperties.FINDBUGS_TIMEOUT_PROPERTY, + name = "Timeout", + description = "Specifies the amount of time, in milliseconds, that FindBugs may run before it is assumed to be hung and is terminated. The default is 600,000 milliseconds, which is ten minutes.", + project = true, + module = true, + global = true) +}) +public class FindbugsPlugin implements Plugin { + + public String getKey() { + return CoreProperties.FINDBUGS_PLUGIN; + } + + public String getName() { + return "Findbugs"; + } + + public String getDescription() { + return "FindBugs is a program that uses static analysis to look for bugs in Java code. It can detect a variety of common coding mistakes, including thread synchronization problems, misuse of API methods... You can find more by going to the Findbugs web site."; + } + + public List> getExtensions() { + List> list = new ArrayList>(); + list.add(FindbugsSensor.class); + list.add(FindbugsMavenPluginHandler.class); + list.add(FindbugsRulesRepository.class); + return list; + } +} diff --git a/plugins/sonar-findbugs-plugin/src/main/java/org/sonar/plugins/findbugs/FindbugsRulePriorityMapper.java b/plugins/sonar-findbugs-plugin/src/main/java/org/sonar/plugins/findbugs/FindbugsRulePriorityMapper.java new file mode 100644 index 00000000000..47a8fb54120 --- /dev/null +++ b/plugins/sonar-findbugs-plugin/src/main/java/org/sonar/plugins/findbugs/FindbugsRulePriorityMapper.java @@ -0,0 +1,53 @@ +/* + * Sonar, open source software quality management tool. + * Copyright (C) 2009 SonarSource SA + * mailto:contact AT sonarsource DOT com + * + * Sonar is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * Sonar is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with Sonar; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 + */ +package org.sonar.plugins.findbugs; + +import org.sonar.api.rules.RulePriority; +import org.sonar.api.rules.RulePriorityMapper; + +public class FindbugsRulePriorityMapper implements RulePriorityMapper { + + public RulePriority from(String priority) { + if (priority.equals("1")) { + return RulePriority.BLOCKER; + } + if (priority.equals("2")) { + return RulePriority.MAJOR; + } + if (priority.equals("3")) { + return RulePriority.INFO; + } + throw new IllegalArgumentException("Priority not supported: " + priority); + } + + public String to(RulePriority priority) { + if (priority.equals(RulePriority.BLOCKER) || priority.equals(RulePriority.CRITICAL)) { + return "1"; + } + if (priority.equals(RulePriority.MAJOR)) { + return "2"; + } + if (priority.equals(RulePriority.INFO) || priority.equals(RulePriority.MINOR)) { + return "3"; + } + throw new IllegalArgumentException("Priority not supported: " + priority); + } + +} diff --git a/plugins/sonar-findbugs-plugin/src/main/java/org/sonar/plugins/findbugs/FindbugsRulesRepository.java b/plugins/sonar-findbugs-plugin/src/main/java/org/sonar/plugins/findbugs/FindbugsRulesRepository.java new file mode 100644 index 00000000000..4113c709536 --- /dev/null +++ b/plugins/sonar-findbugs-plugin/src/main/java/org/sonar/plugins/findbugs/FindbugsRulesRepository.java @@ -0,0 +1,111 @@ +/* + * Sonar, open source software quality management tool. + * Copyright (C) 2009 SonarSource SA + * mailto:contact AT sonarsource DOT com + * + * Sonar is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * Sonar is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with Sonar; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 + */ +package org.sonar.plugins.findbugs; + +import org.apache.commons.lang.StringUtils; +import org.sonar.api.CoreProperties; +import org.sonar.api.profiles.RulesProfile; +import org.sonar.api.resources.Java; +import org.sonar.api.rules.*; +import org.sonar.plugins.findbugs.xml.FindBugsFilter; + +import java.util.*; + +public class FindbugsRulesRepository extends AbstractRulesRepository implements ConfigurationImportable, ConfigurationExportable { + + public FindbugsRulesRepository(Java language) { + super(language, new FindbugsRulePriorityMapper()); + } + + @Override + public String getRepositoryResourcesBase() { + return "org/sonar/plugins/findbugs"; + } + + @Override + public List parseReferential(String fileContent) { + return new StandardRulesXmlParser().parse(fileContent); + } + + public List getProvidedProfiles() { + RulesProfile profile = new RulesProfile(RulesProfile.SONAR_WAY_FINDBUGS_NAME, Java.KEY); + List rules = getInitialReferential(); + ArrayList activeRules = new ArrayList(); + for (Rule rule : rules) { + activeRules.add(new ActiveRule(profile, rule, null)); + } + profile.setActiveRules(activeRules); + return Arrays.asList(profile); + } + + public String exportConfiguration(RulesProfile activeProfile) { + FindBugsFilter filter = FindBugsFilter.fromActiveRules(activeProfile.getActiveRulesByPlugin(CoreProperties.FINDBUGS_PLUGIN)); + return addHeaderToXml(filter.toXml()); + } + + private static String addHeaderToXml(String xmlModules) { + return "\n\n".concat(xmlModules); + } + + public List importConfiguration(String xml, List rules) { + FindBugsFilter filter = FindBugsFilter.fromXml(xml); + + Set result = new HashSet(); + + for (Map.Entry categoryLevel : filter.getCategoryLevels(getRulePriorityMapper()).entrySet()) { + completeActiveRulesByCategory(result, rules, categoryLevel.getKey(), categoryLevel.getValue()); + } + + for (Map.Entry codeLevel : filter.getCodeLevels(getRulePriorityMapper()).entrySet()) { + completeActiveRulesByCode(result, rules, codeLevel.getKey(), codeLevel.getValue()); + } + + for (Map.Entry patternLevel : filter.getPatternLevels(getRulePriorityMapper()).entrySet()) { + completeActiveRulesByPattern(result, rules, patternLevel.getKey(), patternLevel.getValue()); + } + + return new ArrayList(result); + } + + private void completeActiveRulesByCategory(Set result, List rules, String findbugsCategory, RulePriority priority) { + for (Rule rule : rules) { + String sonarCateg = Category.findbugsToSonar(findbugsCategory); + if (sonarCateg != null && rule.getName().startsWith(sonarCateg)) { + result.add(new ActiveRule(null, rule, priority)); + } + } + } + + private void completeActiveRulesByCode(Set result, List rules, String findbugsCode, RulePriority priority) { + for (Rule rule : rules) { + if (rule.getKey().equals(findbugsCode) || StringUtils.startsWith(rule.getKey(), findbugsCode + "_")) { + result.add(new ActiveRule(null, rule, priority)); + } + } + } + + private void completeActiveRulesByPattern(Set result, List rules, String findbugsPattern, RulePriority priority) { + for (Rule rule : rules) { + if (rule.getKey().equals(findbugsPattern)) { + result.add(new ActiveRule(null, rule, priority)); + } + } + } +} diff --git a/plugins/sonar-findbugs-plugin/src/main/java/org/sonar/plugins/findbugs/FindbugsSensor.java b/plugins/sonar-findbugs-plugin/src/main/java/org/sonar/plugins/findbugs/FindbugsSensor.java new file mode 100644 index 00000000000..cf31f5a3e55 --- /dev/null +++ b/plugins/sonar-findbugs-plugin/src/main/java/org/sonar/plugins/findbugs/FindbugsSensor.java @@ -0,0 +1,95 @@ +/* + * Sonar, open source software quality management tool. + * Copyright (C) 2009 SonarSource SA + * mailto:contact AT sonarsource DOT com + * + * Sonar is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * Sonar is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with Sonar; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 + */ +package org.sonar.plugins.findbugs; + +import java.io.File; +import java.util.List; + +import org.apache.commons.lang.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.sonar.api.CoreProperties; +import org.sonar.api.batch.GeneratesViolations; +import org.sonar.api.batch.Sensor; +import org.sonar.api.batch.SensorContext; +import org.sonar.api.batch.maven.DependsUponMavenPlugin; +import org.sonar.api.batch.maven.MavenPluginHandler; +import org.sonar.api.profiles.RulesProfile; +import org.sonar.api.resources.JavaFile; +import org.sonar.api.resources.Project; +import org.sonar.api.rules.Rule; +import org.sonar.api.rules.RulesManager; +import org.sonar.api.rules.Violation; + +public class FindbugsSensor implements Sensor, DependsUponMavenPlugin, GeneratesViolations { + + private RulesProfile profile; + private RulesManager rulesManager; + private FindbugsMavenPluginHandler pluginHandler; + private static Logger LOG = LoggerFactory.getLogger(FindbugsSensor.class); + + public FindbugsSensor(RulesProfile profile, RulesManager rulesManager, FindbugsMavenPluginHandler pluginHandler) { + this.profile = profile; + this.rulesManager = rulesManager; + this.pluginHandler = pluginHandler; + } + + public void analyse(Project project, SensorContext context) { + File report = getFindbugsReportFile(project); + LOG.info("Findbugs output report: " + report.getAbsolutePath()); + FindbugsXmlReportParser reportParser = new FindbugsXmlReportParser(report); + List fbViolations = reportParser.getViolations(); + for (FindbugsXmlReportParser.Violation fbViolation : fbViolations) { + Rule rule = rulesManager.getPluginRule(CoreProperties.FINDBUGS_PLUGIN, fbViolation.getType()); + JavaFile resource = new JavaFile(fbViolation.getSonarJavaFileKey()); + if (context.getResource(resource) != null) { + Violation violation = new Violation(rule, resource) + .setLineId(fbViolation.getStart()) + .setMessage(fbViolation.getLongMessage()); + context.saveViolation(violation); + } + } + } + + protected final File getFindbugsReportFile(Project project) { + if (project.getConfiguration().getString(CoreProperties.FINDBUGS_REPORT_PATH) != null) { + return new File(project.getConfiguration().getString(CoreProperties.FINDBUGS_REPORT_PATH)); + } + return new File(project.getFileSystem().getBuildDir(), "findbugsXml.xml"); + } + + public boolean shouldExecuteOnProject(Project project) { + return project.getFileSystem().hasJavaSourceFiles() && + ( !profile.getActiveRulesByPlugin(CoreProperties.FINDBUGS_PLUGIN).isEmpty() || project.getReuseExistingRulesConfig()) && + project.getPom() != null && !StringUtils.equalsIgnoreCase(project.getPom().getPackaging(), "ear"); + } + + public MavenPluginHandler getMavenPluginHandler(Project project) { + if (project.getConfiguration().getString(CoreProperties.FINDBUGS_REPORT_PATH) != null) { + return null; + } + return pluginHandler; + } + + @Override + public String toString() { + return getClass().getSimpleName(); + } +} \ No newline at end of file diff --git a/plugins/sonar-findbugs-plugin/src/main/java/org/sonar/plugins/findbugs/FindbugsXmlReportParser.java b/plugins/sonar-findbugs-plugin/src/main/java/org/sonar/plugins/findbugs/FindbugsXmlReportParser.java new file mode 100644 index 00000000000..de979170cd3 --- /dev/null +++ b/plugins/sonar-findbugs-plugin/src/main/java/org/sonar/plugins/findbugs/FindbugsXmlReportParser.java @@ -0,0 +1,139 @@ +/* + * Sonar, open source software quality management tool. + * Copyright (C) 2009 SonarSource SA + * mailto:contact AT sonarsource DOT com + * + * Sonar is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * Sonar is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with Sonar; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 + */ +package org.sonar.plugins.findbugs; + +import java.io.File; +import java.util.ArrayList; +import java.util.List; + +import javax.xml.stream.XMLInputFactory; +import javax.xml.stream.XMLStreamException; + +import org.codehaus.staxmate.SMInputFactory; +import org.codehaus.staxmate.in.SMInputCursor; +import org.sonar.api.utils.SonarException; +import org.sonar.api.utils.XmlParserException; + +class FindbugsXmlReportParser { + + private final File findbugsXmlReport; + private final String findbugsXmlReportPath; + + public FindbugsXmlReportParser(File findbugsXmlReport) { + this.findbugsXmlReport = findbugsXmlReport; + findbugsXmlReportPath = findbugsXmlReport.getAbsolutePath(); + if ( !findbugsXmlReport.exists()) { + throw new SonarException("The findbugs XML report can't be found at '" + findbugsXmlReportPath + "'"); + } + } + + public List getViolations() { + List violations = new ArrayList(); + try { + SMInputFactory inf = new SMInputFactory(XMLInputFactory.newInstance()); + SMInputCursor cursor = inf.rootElementCursor(findbugsXmlReport).advance(); + SMInputCursor bugInstanceCursor = cursor.childElementCursor("BugInstance").advance(); + while (bugInstanceCursor.asEvent() != null) { + String type = bugInstanceCursor.getAttrValue("type"); + String longMessage = ""; + SMInputCursor bugInstanceChildCursor = bugInstanceCursor.childElementCursor().advance(); + while (bugInstanceChildCursor.asEvent() != null) { + String nodeName = bugInstanceChildCursor.getLocalName(); + if ("LongMessage".equals(nodeName)) { + longMessage = bugInstanceChildCursor.collectDescendantText(); + } else if ("SourceLine".equals(nodeName)) { + Violation fbViolation = new Violation(); + fbViolation.type = type; + fbViolation.longMessage = longMessage; + fbViolation.parseStart(bugInstanceChildCursor.getAttrValue("start")); + fbViolation.parseEnd(bugInstanceChildCursor.getAttrValue("end")); + fbViolation.className = bugInstanceChildCursor.getAttrValue("classname"); + fbViolation.sourcePath = bugInstanceChildCursor.getAttrValue("sourcepath"); + violations.add(fbViolation); + } + bugInstanceChildCursor.advance(); + } + bugInstanceCursor.advance(); + } + cursor.getStreamReader().closeCompletely(); + } catch (XMLStreamException e) { + throw new XmlParserException("Unable to parse the Findbugs XML Report '" + findbugsXmlReportPath + "'", e); + } + return violations; + } + + public static class Violation { + + private String type; + private String longMessage; + private Integer start; + private Integer end; + protected String className; + protected String sourcePath; + + public String getType() { + return type; + } + + public void parseStart(String attrValue) { + try { + start = Integer.parseInt(attrValue); + } catch (NumberFormatException e) { + start = null; + } + } + + public void parseEnd(String attrValue) { + try { + end = Integer.parseInt(attrValue); + } catch (NumberFormatException e) { + end = null; + } + } + + public String getLongMessage() { + return longMessage; + } + + public Integer getStart() { + return start; + } + + public Integer getEnd() { + return end; + } + + public String getClassName() { + return className; + } + + public String getSourcePath() { + return sourcePath; + } + + public String getSonarJavaFileKey() { + if (className.indexOf('$') > -1) { + return className.substring(0, className.indexOf('$')); + } + return className; + } + } + +} diff --git a/plugins/sonar-findbugs-plugin/src/main/java/org/sonar/plugins/findbugs/xml/Bug.java b/plugins/sonar-findbugs-plugin/src/main/java/org/sonar/plugins/findbugs/xml/Bug.java new file mode 100644 index 00000000000..ebc836d8b1f --- /dev/null +++ b/plugins/sonar-findbugs-plugin/src/main/java/org/sonar/plugins/findbugs/xml/Bug.java @@ -0,0 +1,67 @@ +/* + * Sonar, open source software quality management tool. + * Copyright (C) 2009 SonarSource SA + * mailto:contact AT sonarsource DOT com + * + * Sonar is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * Sonar is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with Sonar; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 + */ +package org.sonar.plugins.findbugs.xml; + +import com.thoughtworks.xstream.annotations.XStreamAlias; +import com.thoughtworks.xstream.annotations.XStreamAsAttribute; + +@XStreamAlias("Bug") +public class Bug { + + @XStreamAsAttribute + private String code; + + @XStreamAsAttribute + private String category; + + @XStreamAsAttribute + private String pattern; + + public Bug() { + } + + public Bug(String pattern) { + this.pattern = pattern; + } + + public String getPattern() { + return pattern; + } + + public void setPattern(String pattern) { + this.pattern = pattern; + } + + public String getCode() { + return code; + } + + public void setCode(String code) { + this.code = code; + } + + public String getCategory() { + return category; + } + + public void setCategory(String category) { + this.category = category; + } +} diff --git a/plugins/sonar-findbugs-plugin/src/main/java/org/sonar/plugins/findbugs/xml/ClassFilter.java b/plugins/sonar-findbugs-plugin/src/main/java/org/sonar/plugins/findbugs/xml/ClassFilter.java new file mode 100644 index 00000000000..e8b307692c2 --- /dev/null +++ b/plugins/sonar-findbugs-plugin/src/main/java/org/sonar/plugins/findbugs/xml/ClassFilter.java @@ -0,0 +1,45 @@ +/* + * Sonar, open source software quality management tool. + * Copyright (C) 2009 SonarSource SA + * mailto:contact AT sonarsource DOT com + * + * Sonar is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * Sonar is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with Sonar; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 + */ +package org.sonar.plugins.findbugs.xml; + +import com.thoughtworks.xstream.annotations.XStreamAlias; +import com.thoughtworks.xstream.annotations.XStreamAsAttribute; + +@XStreamAlias("Class") +public class ClassFilter { + + @XStreamAsAttribute + private String name; + + public ClassFilter() { + } + + public ClassFilter(String name) { + this.name = name; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } +} \ No newline at end of file diff --git a/plugins/sonar-findbugs-plugin/src/main/java/org/sonar/plugins/findbugs/xml/FieldFilter.java b/plugins/sonar-findbugs-plugin/src/main/java/org/sonar/plugins/findbugs/xml/FieldFilter.java new file mode 100644 index 00000000000..384c90c9a39 --- /dev/null +++ b/plugins/sonar-findbugs-plugin/src/main/java/org/sonar/plugins/findbugs/xml/FieldFilter.java @@ -0,0 +1,57 @@ +/* + * Sonar, open source software quality management tool. + * Copyright (C) 2009 SonarSource SA + * mailto:contact AT sonarsource DOT com + * + * Sonar is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * Sonar is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with Sonar; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 + */ +package org.sonar.plugins.findbugs.xml; + +import com.thoughtworks.xstream.annotations.XStreamAlias; +import com.thoughtworks.xstream.annotations.XStreamAsAttribute; + +@XStreamAlias("Field") +public class FieldFilter { + + @XStreamAsAttribute + private String name; + + @XStreamAsAttribute + private String type; + + + public FieldFilter() { + } + + public FieldFilter(String name) { + this.name = name; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } +} \ No newline at end of file diff --git a/plugins/sonar-findbugs-plugin/src/main/java/org/sonar/plugins/findbugs/xml/FindBugsFilter.java b/plugins/sonar-findbugs-plugin/src/main/java/org/sonar/plugins/findbugs/xml/FindBugsFilter.java new file mode 100644 index 00000000000..bd2f6284aed --- /dev/null +++ b/plugins/sonar-findbugs-plugin/src/main/java/org/sonar/plugins/findbugs/xml/FindBugsFilter.java @@ -0,0 +1,206 @@ +/* + * Sonar, open source software quality management tool. + * Copyright (C) 2009 SonarSource SA + * mailto:contact AT sonarsource DOT com + * + * Sonar is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * Sonar is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with Sonar; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 + */ +package org.sonar.plugins.findbugs.xml; + +import com.thoughtworks.xstream.XStream; +import com.thoughtworks.xstream.annotations.XStreamAlias; +import com.thoughtworks.xstream.annotations.XStreamImplicit; +import org.apache.commons.io.IOUtils; +import org.apache.commons.lang.CharEncoding; +import org.apache.commons.lang.StringUtils; +import org.sonar.api.CoreProperties; +import org.sonar.api.rules.ActiveRule; +import org.sonar.api.rules.RulePriority; +import org.sonar.api.rules.RulePriorityMapper; + +import java.io.IOException; +import java.io.InputStream; +import java.util.*; + +@XStreamAlias("FindBugsFilter") +public class FindBugsFilter { + + private static final String PATTERN_SEPARATOR = ","; + private static final String CODE_SEPARATOR = ","; + private static final String CATEGORY_SEPARATOR = ","; + + @XStreamImplicit + private List matchs; + + public FindBugsFilter() { + matchs = new ArrayList(); + } + + public String toXml() { + XStream xstream = createXStream(); + return xstream.toXML(this); + } + + public List getMatchs() { + return matchs; + } + + public List getChildren() { + return matchs; + } + + public void setMatchs(List matchs) { + this.matchs = matchs; + } + + public void addMatch(Match child) { + matchs.add(child); + } + + public Map getPatternLevels(RulePriorityMapper priorityMapper) { + BugInfoSplitter splitter = new BugInfoSplitter() { + public String getSeparator() { + return PATTERN_SEPARATOR; + } + + public String getVar(Bug bug) { + return bug.getPattern(); + } + }; + return processMatches(priorityMapper, splitter); + } + + public Map getCodeLevels(RulePriorityMapper priorityMapper) { + BugInfoSplitter splitter = new BugInfoSplitter() { + public String getSeparator() { + return CODE_SEPARATOR; + } + + public String getVar(Bug bug) { + return bug.getCode(); + } + }; + return processMatches(priorityMapper, splitter); + } + + public Map getCategoryLevels(RulePriorityMapper priorityMapper) { + BugInfoSplitter splitter = new BugInfoSplitter() { + public String getSeparator() { + return CATEGORY_SEPARATOR; + } + + public String getVar(Bug bug) { + return bug.getCategory(); + } + }; + return processMatches(priorityMapper, splitter); + } + + private RulePriority getRulePriority(Priority priority, RulePriorityMapper priorityMapper) { + return priority != null ? priorityMapper.from(priority.getValue()) : null; + } + + private Map processMatches(RulePriorityMapper priorityMapper, BugInfoSplitter splitter) { + Map result = new HashMap(); + for (Match child : getChildren()) { + if (child.getOrs() != null) { + for (OrFilter orFilter : child.getOrs()) { + completeLevels(result, orFilter.getBugs(), child.getPriority(), priorityMapper, splitter); + } + } + if (child.getBug() != null) { + completeLevels(result, Arrays.asList(child.getBug()), child.getPriority(), priorityMapper, splitter); + } + } + return result; + } + + private void completeLevels(Map result, List bugs, Priority priority, RulePriorityMapper priorityMapper, BugInfoSplitter splitter) { + if (bugs == null) { + return; + } + RulePriority rulePriority = getRulePriority(priority, priorityMapper); + for (Bug bug : bugs) { + String varToSplit = splitter.getVar(bug); + if (!StringUtils.isBlank(varToSplit)) { + String[] splitted = StringUtils.split(varToSplit, splitter.getSeparator()); + for (String code : splitted) { + mapRulePriority(result, rulePriority, code); + } + } + } + } + + private interface BugInfoSplitter { + String getVar(Bug bug); + + String getSeparator(); + } + + private void mapRulePriority(Map prioritiesByRule, RulePriority priority, String key) { + if (prioritiesByRule.containsKey(key)) { + if (prioritiesByRule.get(key).compareTo(priority) < 0) { + prioritiesByRule.put(key, priority); + } + } else { + prioritiesByRule.put(key, priority); + } + } + + public static XStream createXStream() { + XStream xstream = new XStream(); + xstream.setClassLoader(FindBugsFilter.class.getClassLoader()); + xstream.processAnnotations(FindBugsFilter.class); + xstream.processAnnotations(Match.class); + xstream.processAnnotations(Bug.class); + xstream.processAnnotations(Priority.class); + xstream.processAnnotations(ClassFilter.class); + xstream.processAnnotations(PackageFilter.class); + xstream.processAnnotations(MethodFilter.class); + xstream.processAnnotations(FieldFilter.class); + xstream.processAnnotations(LocalFilter.class); + xstream.processAnnotations(OrFilter.class); + return xstream; + } + + public static FindBugsFilter fromXml(String xml) { + try { + XStream xStream = createXStream(); + InputStream inputStream = IOUtils.toInputStream(xml, CharEncoding.UTF_8); + return (FindBugsFilter) xStream.fromXML(inputStream); + + } catch (IOException e) { + throw new RuntimeException("can't read configuration file", e); + } + } + + public static FindBugsFilter fromActiveRules(List activeRules) { + FindBugsFilter root = new FindBugsFilter(); + for (ActiveRule activeRule : activeRules) { + if (CoreProperties.FINDBUGS_PLUGIN.equals(activeRule.getPluginName())) { + Match child = createChild(activeRule); + root.addMatch(child); + } + } + return root; + } + + private static Match createChild(ActiveRule activeRule) { + Match child = new Match(); + child.setBug(new Bug(activeRule.getConfigKey())); + return child; + } + +} diff --git a/plugins/sonar-findbugs-plugin/src/main/java/org/sonar/plugins/findbugs/xml/LocalFilter.java b/plugins/sonar-findbugs-plugin/src/main/java/org/sonar/plugins/findbugs/xml/LocalFilter.java new file mode 100644 index 00000000000..af26485cbd7 --- /dev/null +++ b/plugins/sonar-findbugs-plugin/src/main/java/org/sonar/plugins/findbugs/xml/LocalFilter.java @@ -0,0 +1,45 @@ +/* + * Sonar, open source software quality management tool. + * Copyright (C) 2009 SonarSource SA + * mailto:contact AT sonarsource DOT com + * + * Sonar is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * Sonar is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with Sonar; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 + */ +package org.sonar.plugins.findbugs.xml; + +import com.thoughtworks.xstream.annotations.XStreamAlias; +import com.thoughtworks.xstream.annotations.XStreamAsAttribute; + +@XStreamAlias("Local") +public class LocalFilter { + + @XStreamAsAttribute + private String name; + + public LocalFilter() { + } + + public LocalFilter(String name) { + this.name = name; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } +} \ No newline at end of file diff --git a/plugins/sonar-findbugs-plugin/src/main/java/org/sonar/plugins/findbugs/xml/Match.java b/plugins/sonar-findbugs-plugin/src/main/java/org/sonar/plugins/findbugs/xml/Match.java new file mode 100644 index 00000000000..e8fb48778ee --- /dev/null +++ b/plugins/sonar-findbugs-plugin/src/main/java/org/sonar/plugins/findbugs/xml/Match.java @@ -0,0 +1,137 @@ +/* + * Sonar, open source software quality management tool. + * Copyright (C) 2009 SonarSource SA + * mailto:contact AT sonarsource DOT com + * + * Sonar is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * Sonar is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with Sonar; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 + */ +package org.sonar.plugins.findbugs.xml; + +import java.util.List; + +import com.thoughtworks.xstream.annotations.XStreamAlias; +import com.thoughtworks.xstream.annotations.XStreamImplicit; + +@XStreamAlias("Match") +public class Match { + + @XStreamAlias("Bug") + private Bug bug; + + @XStreamAlias("Priority") + private Priority priority; + + @XStreamAlias("Package") + private PackageFilter particularPackage; + + @XStreamAlias("Class") + private ClassFilter particularClass; + + @XStreamAlias("Method") + private MethodFilter particularMethod; + + @XStreamAlias("Field") + private FieldFilter particularField; + + @XStreamAlias("Local") + private LocalFilter particularLocal; + + @XStreamImplicit(itemFieldName = "Or") + private List ors; + + public Match() { + } + + public Match(Bug bug, Priority priority) { + this.bug = bug; + this.priority = priority; + } + + public Match(Bug bug) { + this.bug = bug; + } + + public Match(ClassFilter particularClass) { + this.particularClass = particularClass; + } + + public Bug getBug() { + return bug; + } + + public void setBug(Bug bug) { + this.bug = bug; + } + + public Priority getPriority() { + return priority; + } + + public void setPriority(Priority priority) { + this.priority = priority; + } + + public PackageFilter getParticularPackage() { + return particularPackage; + } + + public void setParticularPackage(PackageFilter particularPackage) { + this.particularPackage = particularPackage; + } + + public ClassFilter getParticularClass() { + return particularClass; + } + + public void setParticularClass(ClassFilter particularClass) { + this.particularClass = particularClass; + } + + public MethodFilter getParticularMethod() { + return particularMethod; + } + + public void setParticularMethod(MethodFilter particularMethod) { + this.particularMethod = particularMethod; + } + + public FieldFilter getParticularField() { + return particularField; + } + + public void setParticularField(FieldFilter particularField) { + this.particularField = particularField; + } + + public LocalFilter getParticularLocal() { + return particularLocal; + } + + public void setParticularLocal(LocalFilter particularLocal) { + this.particularLocal = particularLocal; + } + + public List getOrs() { + return ors; + } + + public void setOrs(List ors) { + this.ors = ors; + } + + public void addDisjunctCombine(OrFilter child) { + ors.add(child); + } +} diff --git a/plugins/sonar-findbugs-plugin/src/main/java/org/sonar/plugins/findbugs/xml/MethodFilter.java b/plugins/sonar-findbugs-plugin/src/main/java/org/sonar/plugins/findbugs/xml/MethodFilter.java new file mode 100644 index 00000000000..78d353b6653 --- /dev/null +++ b/plugins/sonar-findbugs-plugin/src/main/java/org/sonar/plugins/findbugs/xml/MethodFilter.java @@ -0,0 +1,68 @@ +/* + * Sonar, open source software quality management tool. + * Copyright (C) 2009 SonarSource SA + * mailto:contact AT sonarsource DOT com + * + * Sonar is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * Sonar is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with Sonar; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 + */ +package org.sonar.plugins.findbugs.xml; + +import com.thoughtworks.xstream.annotations.XStreamAlias; +import com.thoughtworks.xstream.annotations.XStreamAsAttribute; + +@XStreamAlias("Method") +public class MethodFilter { + + @XStreamAsAttribute + private String name; + + @XStreamAsAttribute + private String params; + + @XStreamAsAttribute + private String returns; + + + public MethodFilter() { + } + + public MethodFilter(String name) { + this.name = name; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getParams() { + return params; + } + + public void setParams(String params) { + this.params = params; + } + + public String getReturns() { + return returns; + } + + public void setReturns(String returns) { + this.returns = returns; + } +} \ No newline at end of file diff --git a/plugins/sonar-findbugs-plugin/src/main/java/org/sonar/plugins/findbugs/xml/OrFilter.java b/plugins/sonar-findbugs-plugin/src/main/java/org/sonar/plugins/findbugs/xml/OrFilter.java new file mode 100644 index 00000000000..1fcdc24cbdf --- /dev/null +++ b/plugins/sonar-findbugs-plugin/src/main/java/org/sonar/plugins/findbugs/xml/OrFilter.java @@ -0,0 +1,107 @@ +/* + * Sonar, open source software quality management tool. + * Copyright (C) 2009 SonarSource SA + * mailto:contact AT sonarsource DOT com + * + * Sonar is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * Sonar is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with Sonar; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 + */ +package org.sonar.plugins.findbugs.xml; + +import com.thoughtworks.xstream.annotations.XStreamAlias; +import com.thoughtworks.xstream.annotations.XStreamImplicit; + +import java.util.ArrayList; +import java.util.List; + + +@XStreamAlias("Or") +public class OrFilter { + + @XStreamImplicit(itemFieldName = "Bug") + private List bugs; + + @XStreamImplicit(itemFieldName = "Package") + private List packages; + + @XStreamImplicit(itemFieldName = "Class") + private List classes; + + @XStreamImplicit(itemFieldName = "Method") + private List methods; + + @XStreamImplicit(itemFieldName = "Field") + private List fields; + + @XStreamImplicit(itemFieldName = "Local") + private List locals; + + + public OrFilter() { + bugs = new ArrayList(); + packages = new ArrayList(); + classes = new ArrayList(); + methods = new ArrayList(); + fields = new ArrayList(); + locals = new ArrayList(); + } + + public List getBugs() { + return bugs; + } + + public void setBugs(List bugs) { + this.bugs = bugs; + } + + public List getPackages() { + return packages; + } + + public void setPackages(List packages) { + this.packages = packages; + } + + public List getClasses() { + return classes; + } + + public void setClasses(List classes) { + this.classes = classes; + } + + public List getMethods() { + return methods; + } + + public void setMethods(List methods) { + this.methods = methods; + } + + public List getFields() { + return fields; + } + + public void setFields(List fields) { + this.fields = fields; + } + + public List getLocals() { + return locals; + } + + public void setLocals(List locals) { + this.locals = locals; + } +} \ No newline at end of file diff --git a/plugins/sonar-findbugs-plugin/src/main/java/org/sonar/plugins/findbugs/xml/PackageFilter.java b/plugins/sonar-findbugs-plugin/src/main/java/org/sonar/plugins/findbugs/xml/PackageFilter.java new file mode 100644 index 00000000000..858528fadd7 --- /dev/null +++ b/plugins/sonar-findbugs-plugin/src/main/java/org/sonar/plugins/findbugs/xml/PackageFilter.java @@ -0,0 +1,45 @@ +/* + * Sonar, open source software quality management tool. + * Copyright (C) 2009 SonarSource SA + * mailto:contact AT sonarsource DOT com + * + * Sonar is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * Sonar is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with Sonar; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 + */ +package org.sonar.plugins.findbugs.xml; + +import com.thoughtworks.xstream.annotations.XStreamAlias; +import com.thoughtworks.xstream.annotations.XStreamAsAttribute; + +@XStreamAlias("Package") +public class PackageFilter { + + @XStreamAsAttribute + private String name; + + public PackageFilter() { + } + + public PackageFilter(String name) { + this.name = name; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } +} \ No newline at end of file diff --git a/plugins/sonar-findbugs-plugin/src/main/java/org/sonar/plugins/findbugs/xml/Priority.java b/plugins/sonar-findbugs-plugin/src/main/java/org/sonar/plugins/findbugs/xml/Priority.java new file mode 100644 index 00000000000..6541bf3207c --- /dev/null +++ b/plugins/sonar-findbugs-plugin/src/main/java/org/sonar/plugins/findbugs/xml/Priority.java @@ -0,0 +1,46 @@ +/* + * Sonar, open source software quality management tool. + * Copyright (C) 2009 SonarSource SA + * mailto:contact AT sonarsource DOT com + * + * Sonar is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * Sonar is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with Sonar; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 + */ +package org.sonar.plugins.findbugs.xml; + +import com.thoughtworks.xstream.annotations.XStreamAlias; +import com.thoughtworks.xstream.annotations.XStreamAsAttribute; + +@XStreamAlias("Priority") +public class Priority { + + @XStreamAsAttribute + private String value; + + public Priority() { + } + + public Priority(String value) { + this.value = value; + } + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + +} \ No newline at end of file diff --git a/plugins/sonar-findbugs-plugin/src/main/resources/org/sonar/plugins/findbugs/rules.xml b/plugins/sonar-findbugs-plugin/src/main/resources/org/sonar/plugins/findbugs/rules.xml new file mode 100644 index 00000000000..ba318a14b34 --- /dev/null +++ b/plugins/sonar-findbugs-plugin/src/main/resources/org/sonar/plugins/findbugs/rules.xml @@ -0,0 +1,4316 @@ + + + + + + + + + + + + + + This code is casting the result of calling toArray() on a collection to a type more specific than Object[], as in:

+
+  String[] getAsArray(Collection c) {
+    return (String[]) c.toArray();
+  }
+
+

This will usually fail by throwing a ClassCastException. The toArray() of almost all collections return an Object[]. They can't really do anything else, since the Collection object has no reference to the declared generic type of the collection.

+

The correct way to do get an array of a specific type from a collection is to use c.toArray(new String[]); or c.toArray(new String[c.size()]); (the latter is slightly more efficient).

+

There is one common/known exception exception to this. The toArray() method of lists returned by Arrays.asList(...) will return a covariantly typed array. For example, Arrays.asArray(new String[] { "a" }).toArray() will return a String []. FindBugs attempts to detect and suppress such cases, but may miss some.

]]>
+
+ + + + + + + + + + + + + + + + + + + OpenJDK introduces a potential incompatibility. In particular, the java.util.logging.Logger behavior has changed. Instead of using strong references, it now uses weak references internally. That's a reasonable change, but unfortunately some code relies on the old behavior - when changing logger configuration, it simply drops the logger reference. That means that the garbage collector is free to reclaim that memory, which means that the logger configuration is lost. For example, consider:

+ + public static void initLogging() throws Exception { + Logger logger = Logger.getLogger("edu.umd.cs"); + logger.addHandler(new FileHandler()); // call to change logger configuration + logger.setUseParentHandlers(false); // another call to change logger configuration + } + +

The logger reference is lost at the end of the method (it doesn't escape the method), so if you have a garbage collection cycle just after the call to initLogging, the logger configuration is lost (because Logger only keeps weak references).

+
+  public static void main(String[] args) throws Exception {
+    initLogging(); // adds a file handler to the logger
+    System.gc(); // logger configuration lost
+    Logger.getLogger("edu.umd.cs").info("Some message"); // this isn't logged to the file as expected
+  }
+
+]]>
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + This method is invoked in the constructor of of the superclass. At this point, the fields of the class have not yet initialized. To make this more concrete, consider the following classes:

+
+  abstract class A {
+    int hashCode;
+    abstract Object getValue();
+    A() {
+      hashCode = getValue().hashCode();
+    }
+  }
+  class B extends A {
+    Object value;
+    B(Object v) {
+      this.value = v;
+    }
+    Object getValue() {
+      return value;
+    }
+  }
+
+

When a B is constructed, the constructor for the A class is invoked before the constructor for B sets value. Thus, when the constructor for A invokes getValue, an uninitialized value is read for value.

]]>
+
+ + + + + + + + + + + + + + + + This field is never initialized within any constructor, and is therefore could be null after the object is constructed. This could be a either an error or a questionable design, since it means a null pointer exception will be generated if that field is dereferenced before being initialized.

]]>
+
+ + + + + The program is dereferencing a field that does not seem to ever have a non-null value written to it. Dereferencing this value will generate a null pointer exception.

]]>
+
+ + + + + This field is never written. All reads of it will return the default value. Check for errors (should it have been initialized?), or remove it if it is useless.

]]>
+
+ + + + + + + This class is bigger than can be effectively handled, and was not fully analyzed for errors. +

]]>
+
+ + + + + This call doesn't pass any objects to the EasyMock method, so the call doesn't do anything. +

]]>
+
+ + + + + (Javadoc) +A ScheduledThreadPoolExecutor with zero core threads will never execute anything; changes to the max pool size are ignored. +

]]>
+
+ + + + + (Javadoc) +While ScheduledThreadPoolExecutor inherits from ThreadPoolExecutor, a few of the inherited tuning methods are not useful for it. In particular, because it acts as a fixed-sized pool using corePoolSize threads and an unbounded queue, adjustments to maximumPoolSize have no useful effect. +

]]>
+
+ + + + + All targets of this method invocation throw an UnsupportedOperationException. +

]]>
+
+ + + + + This code creates a database connect using a blank or empty password. This indicates that the database is not protected by a password. +

]]>
+
+ + + + + This code creates a database connect using a hardcoded, constant password. Anyone with access to either the source code or the compiled code can + easily learn the password. +

]]>
+
+ + + + + This code constructs an HTTP Cookie using an untrusted HTTP parameter. If this cookie is added to an HTTP response, it will allow a HTTP response splitting +vulnerability. See http://en.wikipedia.org/wiki/HTTP_response_splitting +for more information.

+

FindBugs looks only for the most blatant, obvious cases of HTTP response splitting. +If FindBugs found any, you almost certainly have more +vulnerabilities that FindBugs doesn't report. If you are concerned about HTTP response splitting, you should seriously +consider using a commercial static analysis or pen-testing tool. +

]]>
+
+ + + + + This code directly writes an HTTP parameter to an HTTP header, which allows for a HTTP response splitting +vulnerability. See http://en.wikipedia.org/wiki/HTTP_response_splitting +for more information.

+

FindBugs looks only for the most blatant, obvious cases of HTTP response splitting. +If FindBugs found any, you almost certainly have more +vulnerabilities that FindBugs doesn't report. If you are concerned about HTTP response splitting, you should seriously +consider using a commercial static analysis or pen-testing tool. +

]]>
+
+ + + + + This code directly writes an HTTP parameter to Servlet output, which allows for a reflected cross site scripting +vulnerability. See http://en.wikipedia.org/wiki/Cross-site_scripting +for more information.

+

FindBugs looks only for the most blatant, obvious cases of cross site scripting. +If FindBugs found any, you almost certainly have more cross site scripting +vulnerabilities that FindBugs doesn't report. If you are concerned about cross site scripting, you should seriously +consider using a commercial static analysis or pen-testing tool. +

]]>
+
+ + + + + This code directly writes an HTTP parameter to a Server error page (using HttpServletResponse.sendError). Echoing this untrusted input allows +for a reflected cross site scripting +vulnerability. See http://en.wikipedia.org/wiki/Cross-site_scripting +for more information.

+

FindBugs looks only for the most blatant, obvious cases of cross site scripting. +If FindBugs found any, you almost certainly have more cross site scripting +vulnerabilities that FindBugs doesn't report. If you are concerned about cross site scripting, you should seriously +consider using a commercial static analysis or pen-testing tool. +

]]>
+
+ + + + + This code directly writes an HTTP parameter to JSP output, which allows for a cross site scripting +vulnerability. See http://en.wikipedia.org/wiki/Cross-site_scripting +for more information.

+

FindBugs looks only for the most blatant, obvious cases of cross site scripting. +If FindBugs found any, you almost certainly have more cross site scripting +vulnerabilities that FindBugs doesn't report. If you are concerned about cross site scripting, you should seriously +consider using a commercial static analysis or pen-testing tool. +

]]>
+
+ + + + + (From JDC Tech Tip): The Swing methods +show(), setVisible(), and pack() will create the associated peer for the frame. +With the creation of the peer, the system creates the event dispatch thread. +This makes things problematic because the event dispatch thread could be notifying +listeners while pack and validate are still processing. This situation could result in +two threads going through the Swing component-based GUI -- it's a serious flaw that +could result in deadlocks or other related threading issues. A pack call causes +components to be realized. As they are being realized (that is, not necessarily +visible), they could trigger listener notification on the event dispatch thread.

]]>
+
+ + + + + This loop doesn't seem to have a way to terminate (other than by perhaps +throwing an exception).

]]>
+
+ + + + + This method unconditionally invokes itself. This would seem to indicate +an infinite recursive loop that will result in a stack overflow.

]]>
+
+ + + + + A collection is added to itself. As a result, computing the hashCode of this +set will throw a StackOverflowException. +

]]>
+
+ + + + + + This declares a volatile reference to an array, which might not be what +you want. With a volatile reference to an array, reads and writes of +the reference to the array are treated as volatile, but the array elements +are non-volatile. To get volatile array elements, you will need to use +one of the atomic array classes in java.util.concurrent (provided +in Java 5.0).

]]>
+
+ + + + + Calling this.getClass().getResource(...) could give +results other than expected if this class is extended by a class in +another package.

]]>
+
+ + + + + + A method that returns either Boolean.TRUE, Boolean.FALSE or null is an accident waiting to happen. + This method can be invoked as though it returned a value of type boolean, and + the compiler will insert automatic unboxing of the Boolean value. If a null value is returned, + this will result in a NullPointerException. +

]]>
+
+ + + + + Since the field is synchronized on, it seems not likely to be null. +If it is null and then synchronized on a NullPointerException will be +thrown and the check would be pointless. Better to synchronize on +another field.

]]>
+
+ + + + + The code contains a conditional test is performed twice, one right after the other +(e.g., x == 0 || x == 0). Perhaps the second occurrence is intended to be something else +(e.g., x == 0 || y == 0). +

]]>
+
+ + + + + The code calls putNextEntry(), immediately +followed by a call to closeEntry(). This results +in an empty ZipFile entry. The contents of the entry +should be written to the ZipFile between the calls to +putNextEntry() and +closeEntry().

]]>
+
+ + + + + The code calls putNextEntry(), immediately +followed by a call to closeEntry(). This results +in an empty JarFile entry. The contents of the entry +should be written to the JarFile between the calls to +putNextEntry() and +closeEntry().

]]>
+
+ + + + + IllegalMonitorStateException is generally only + thrown in case of a design flaw in your code (calling wait or + notify on an object you do not hold a lock on).

]]>
+
+ + + + + + The method performs math operations using floating point precision. + Floating point precision is very imprecise. For example, + 16777216.0f + 1.0f = 16777216.0f. Consider using double math instead.

]]>
+
+ + + + + + Class implements Cloneable but does not define or + use the clone method.

]]>
+
+ + + + + This class defines a clone() method but the class doesn't implement Cloneable. +There are some situations in which this is OK (e.g., you want to control how subclasses +can clone themselves), but just make sure that this is what you intended. +

]]>
+
+ + + + + This non-final class defines a clone() method that does not call super.clone(). +If this class ("A") is extended by a subclass ("B"), +and the subclass B calls super.clone(), then it is likely that +B's clone() method will return an object of type A, +which violates the standard contract for clone().

+ +

If all clone() methods call super.clone(), then they are guaranteed +to use Object.clone(), which always returns an object of the correct type.

]]>
+
+ + + + + The identifier is a word that is reserved as a keyword in later versions of Java, and your code will need to be changed +in order to compile it in later versions of Java.

]]>
+
+ + + + + This identifier is used as a keyword in later versions of Java. This code, and +any code that references this API, +will need to be changed in order to compile it in later versions of Java.

]]>
+
+ + + + + This method might drop an exception.  In general, exceptions + should be handled or reported in some way, or they should be thrown + out of the method.

]]>
+
+ + + + + This method might ignore an exception.  In general, exceptions + should be handled or reported in some way, or they should be thrown + out of the method.

]]>
+
+ + + + + This code invokes a method that requires a security permission check. + If this code will be granted security permissions, but might be invoked by code that does not + have security permissions, then the invocation needs to occur inside a doPrivileged block.

]]>
+
+ + + + + This code creates a classloader, which requires a security manager. + If this code will be granted security permissions, but might be invoked by code that does not + have security permissions, then the classloader creation needs to occur inside a doPrivileged block.

]]>
+
+ + + + + The class is annotated with net.jcip.annotations.Immutable, and the rules for that annotation require +that all fields are final. + .

]]>
+
+ + + + + A Thread object is passed as a parameter to a method where +a Runnable is expected. This is rather unusual, and may indicate a logic error +or cause unexpected behavior. +

]]>
+
+ + + + + This method or field is or uses a Map or Set of URLs. Since both the equals and hashCode +method of URL perform domain name resolution, this can result in a big performance hit. +See http://michaelscharf.blogspot.com/2006/11/javaneturlequals-and-hashcode-make.html for more information. +Consider using java.net.URI instead. +

]]>
+
+ + + + + The equals and hashCode +method of URL perform domain name resolution, this can result in a big performance hit. +See http://michaelscharf.blogspot.com/2006/11/javaneturlequals-and-hashcode-make.html for more information. +Consider using java.net.URI instead. +

]]>
+
+ + + + + + Unless an annotation has itself been annotated with @Retention(RetentionPolicy.RUNTIME), the annotation can't be observed using reflection +(e.g., by using the isAnnotationPresent method). + .

]]>
+
+ + + + + Invoking System.exit shuts down the entire Java virtual machine. This + should only been done when it is appropriate. Such calls make it + hard or impossible for your code to be invoked by other code. + Consider throwing a RuntimeException instead.

]]>
+
+ + + + + Never call System.runFinalizersOnExit +or Runtime.runFinalizersOnExit for any reason: they are among the most +dangerous methods in the Java libraries. -- Joshua Bloch

]]>
+
+ + + + + Using the java.lang.String(String) constructor wastes memory + because the object so constructed will be functionally indistinguishable + from the String passed as a parameter.  Just use the + argument String directly.

]]>
+
+ + + + + Creating a new java.lang.String object using the + no-argument constructor wastes memory because the object so created will + be functionally indistinguishable from the empty string constant + "".  Java guarantees that identical string constants + will be represented by the same String object.  Therefore, + you should just use the empty string constant directly.

]]>
+
+ + + + + Calling String.toString() is just a redundant operation. + Just use the String.

]]>
+
+ + + + + Code explicitly invokes garbage collection. + Except for specific use in benchmarking, this is very dubious.

+

In the past, situations where people have explicitly invoked + the garbage collector in routines such as close or finalize methods + has led to huge performance black holes. Garbage collection + can be expensive. Any situation that forces hundreds or thousands + of garbage collections will bring the machine to a crawl.

]]>
+
+ + + + + + Creating new instances of java.lang.Boolean wastes + memory, since Boolean objects are immutable and there are + only two useful values of this type.  Use the Boolean.valueOf() + method (or Java 1.5 autoboxing) to create Boolean objects instead.

]]>
+
+ + + + + + Using new Integer(int) is guaranteed to always result in a new object whereas + Integer.valueOf(int) allows caching of values to be done by the compiler, class library, or JVM. + Using of cached values avoids object allocation and the code will be faster. +

+

+ Values between -128 and 127 are guaranteed to have corresponding cached instances + and using valueOf is approximately 3.5 times faster than using constructor. + For values outside the constant range the performance of both styles is the same. +

+

+ Unless the class must be compatible with JVMs predating Java 1.5, + use either autoboxing or the valueOf() method when creating instances of + Long, Integer, Short, Character, and Byte. +

]]>
+
+ + + + + + + Using new Double(double) is guaranteed to always result in a new object whereas + Double.valueOf(double) allows caching of values to be done by the compiler, class library, or JVM. + Using of cached values avoids object allocation and the code will be faster. +

+

+ Unless the class must be compatible with JVMs predating Java 1.5, + use either autoboxing or the valueOf() method when creating instances of Double and Float. +

]]>
+
+ + + + + A String is being converted to upper or lowercase, using the platform's default encoding. This may + result in improper conversions when used with international characters. Use the

+
String.toUpperCase( Locale l )
String.toLowerCase( Locale l )
+

versions instead.

]]>
+
+ + + + + A wrapped primitive value is unboxed and converted to another primitive type as part of the +evaluation of a conditional ternary operator (the b ? e1 : e2 operator). The +semantics of Java mandate that if e1 and e2 are wrapped +numeric values, the values are unboxed and converted/coerced to their common type (e.g, +if e1 is of type Integer +and e2 is of type Float, then e1 is unboxed, +converted to a floating point value, and boxed. See JLS Section 15.25. +

]]>
+
+ + + + + A primitive is boxed, and then immediately unboxed. This probably is due to a manual + boxing in a place where an unboxed value is required, thus forcing the compiler +to immediately undo the work of the boxing. +

]]>
+
+ + + + + A primitive boxed value constructed and then immediately converted into a different primitive type +(e.g., new Double(d).intValue()). Just perform direct primitive coercion (e.g., (int) d).

]]>
+
+ + + + + A boxed primitive is allocated just to call toString(). It is more effective to just use the static + form of toString which takes the primitive value. So,

+ + + + + + + + + +
Replace...With this...
new Integer(1).toString()Integer.toString(1)
new Long(1).toString()Long.toString(1)
new Float(1.0).toString()Float.toString(1.0)
new Double(1.0).toString()Double.toString(1.0)
new Byte(1).toString()Byte.toString(1)
new Short(1).toString()Short.toString(1)
new Boolean(true).toString()Boolean.toString(true)
]]>
+
+ + + + + This method allocates an object just to call getClass() on it, in order to + retrieve the Class object for it. It is simpler to just access the .class property of the class.

]]>
+
+ + + + + + This method calls wait() on a + java.util.concurrent.locks.Condition object.  + Waiting for a Condition should be done using one of the await() + methods defined by the Condition interface. +

]]>
+
+ + + + + A random value from 0 to 1 is being coerced to the integer value 0. You probably +want to multiple the random value by something else before coercing it to an integer, or use the Random.nextInt(n) method. +

]]>
+
+ + + + + + If r is a java.util.Random, you can generate a random number from 0 to n-1 +using r.nextInt(n), rather than using (int)(r.nextDouble() * n). +

]]>
+
+ + + + + The method invokes the execute method on an SQL statement with a String that seems +to be dynamically generated. Consider using +a prepared statement instead. It is more efficient and less vulnerable to +SQL injection attacks. +

]]>
+
+ + + + + The code creates an SQL prepared statement from a nonconstant String. +If unchecked, tainted data from a user is used in building this String, SQL injection could +be used to make the prepared statement do something unexpected and undesirable. +

]]>
+
+ + + + + This method creates a thread without specifying a run method either by deriving from the Thread class, or + by passing a Runnable object. This thread, then, does nothing but waste time. +

]]>
+
+ + + + + This method may contain an instance of double-checked locking.  + This idiom is not correct according to the semantics of the Java memory + model.  For more information, see the web page + http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html.

]]>
+
+ + + + + This finalizer nulls out fields. This is usually an error, as it does not aid garbage collection, + and the object is going to be garbage collected anyway.]]> + + + + + + This finalizer does nothing except null out fields. This is completely pointless, and requires that +the object be garbage collected, finalized, and then garbage collected again. You should just remove the finalize +method.]]> + + + + + + A class's finalize() method should have protected access, + not public.

]]>
+
+ + + + + Empty finalize() methods are useless, so they should + be deleted.

]]>
+
+ + + + + This empty finalize() method explicitly negates the + effect of any finalizer defined by its superclass.  Any finalizer + actions defined for the superclass will not be performed.  + Unless this is intended, delete this method.

]]>
+
+ + + + + The only thing this finalize() method does is call + the superclass's finalize() method, making it + redundant.  Delete it.

]]>
+
+ + + + + This finalize() method does not make a call to its + superclass's finalize() method.  So, any finalizer + actions defined for the superclass will not be performed.  + Add a call to super.finalize().

]]>
+
+ + + + + This method contains an explicit invocation of the finalize() + method on an object.  Because finalizer methods are supposed to be + executed once, and only by the VM, this is a bad idea.

+

If a connected set of objects beings finalizable, then the VM will invoke the +finalize method on all the finalizable object, possibly at the same time in different threads. +Thus, it is a particularly bad idea, in the finalize method for a class X, invoke finalize +on objects referenced by X, because they may already be getting finalized in a separate thread.]]> + + + + + + This equals method is checking to see if the argument is some incompatible type +(i.e., a class that is neither a supertype nor subtype of the class that defines +the equals method). For example, the Foo class might have an equals method +that looks like: + +

+public boolean equals(Object o) {
+  if (o instanceof Foo)
+    return name.equals(((Foo)o).name);
+  else if (o instanceof String)
+    return name.equals(o);
+  else return false;
+

+ +

This is considered bad practice, as it makes it very hard to implement an equals method that +is symmetric and transitive. Without those properties, very unexpected behavoirs are possible. +

]]>
+
+ + + + + This class defines an enumeration, and equality on enumerations are defined +using object identity. Defining a covariant equals method for an enumeration +value is exceptionally bad practice, since it would likely result +in having two different enumeration values that compare as equals using +the covariant enum method, and as not equal when compared normally. +Don't do it. +

]]>
+
+ + + + + This class defines a covariant version of the equals() + method, but inherits the normal equals(Object) method + defined in the base java.lang.Object class.  + The class should probably define a boolean equals(Object) method. +

]]>
+
+ + + + + This class defines an equals() + method, that doesn't override the normal equals(Object) method + defined in the base java.lang.Object class.  + The class should probably define a boolean equals(Object) method. +

]]>
+
+ + + + + This class defines an equals() + method, that doesn't override the normal equals(Object) method + defined in the base java.lang.Object class.  Instead, it + inherits an equals(Object) method from a superclass. + The class should probably define a boolean equals(Object) method. +

]]>
+
+ + + + + + + + This class defines a covariant version of equals().  + To correctly override the equals() method in + java.lang.Object, the parameter of equals() + must have type java.lang.Object.

]]>
+
+ + + + + This class defines an equals method that overrides an equals method in a superclass. Both equals methods +methods use instanceof in the determination of whether two objects are equal. This is fraught with peril, +since it is important that the equals method is symmetrical (in other words, a.equals(b) == b.equals(a)). +If B is a subtype of A, and A's equals method checks that the argument is an instanceof A, and B's equals method +checks that the argument is an instanceof B, it is quite likely that the equivalence relation defined by these +methods is not symmetric. +

]]>
+
+ + + + + This class has an equals method that will be broken if it is inherited by subclasses. +It compares a class literal with the class of the argument (e.g., in class Foo +it might check if Foo.class == o.getClass()). +It is better to check if this.getClass() == o.getClass(). +

]]>
+
+ + + + + This class doesn't do any of the patterns we recognize for checking that the type of the argument +is compatible with the type of the this object. There might not be anything wrong with +this code, but it is worth reviewing. +

]]>
+
+ + + + + This method checks to see if two objects are the same class by checking to see if the names +of their classes are equal. You can have different classes with the same name if they are loaded by +different class loaders. Just check to see if the class objects are the same. +

]]>
+
+ + + + + This class defines an equals method that always returns true. This is imaginative, but not very smart. +Plus, it means that the equals method is not symmetric. +

]]>
+
+ + + + + This class defines an equals method that always returns false. This means that an object is not equal to itself, and it is impossible to create useful Maps or Sets of this class. More fundamentally, it means +that equals is not reflexive, one of the requirements of the equals method.

+

The likely intended semantics are object identity: that an object is equal to itself. This is the behavior inherited from class Object. If you need to override an equals inherited from a different +superclass, you can use use: +

+public boolean equals(Object o) { return this == o; }
+
+

]]>
+
+ + + + + + A large String constant is duplicated across multiple class files. + This is likely because a final field is initialized to a String constant, and the Java language + mandates that all references to a final field from other classes be inlined into +that classfile. See JDK bug 6447475 + for a description of an occurrence of this bug in the JDK and how resolving it reduced + the size of the JDK by 1 megabyte. +

]]>
+
+ + + + + + A parameter to this method has been identified as a value that should + always be checked to see whether or not it is null, but it is being dereferenced + without a preceding null check. +

]]>
+
+ + + + + + This implementation of equals(Object) violates the contract defined + by java.lang.Object.equals() because it does not check for null + being passed as the argument. All equals() methods should return + false if passed a null value. +

]]>
+
+ + + + + This class defines a covariant version of compareTo().  + To correctly override the compareTo() method in the + Comparable interface, the parameter of compareTo() + must have type java.lang.Object.

]]>
+
+ + + + + A method, field or class declares a generic signature where a non-hashable class +is used in context where a hashable class is required. +A class that declares an equals method but inherits a hashCode() method +from Object is unhashable, since it doesn't fulfill the requirement that +equal objects have equal hashCodes. +

]]>
+
+ + + + + A class defines an equals(Object) method but not a hashCode() method, +and thus doesn't fulfill the requirement that equal objects have equal hashCodes. +An instance of this class is used in a hash data structure, making the need to +fix this problem of highest importance.]]> + + + + + + This class defines a hashCode() method but inherits its + equals() method from java.lang.Object + (which defines equality by comparing object references).  Although + this will probably satisfy the contract that equal objects must have + equal hashcodes, it is probably not what was intended by overriding + the hashCode() method.  (Overriding hashCode() + implies that the object's identity is based on criteria more complicated + than simple reference equality.)

+

If you don't think instances of this class will ever be inserted into a HashMap/HashTable, +the recommended hashCode implementation to use is:

+

public int hashCode() {
+  assert false : "hashCode not designed";
+  return 42; // any arbitrary constant will do 
+  }

]]>
+
+ + + + + This class defines a compareTo(...) method but inherits its + equals() method from java.lang.Object. + Generally, the value of compareTo should return zero if and only if + equals returns true. If this is violated, weird and unpredictable + failures will occur in classes such as PriorityQueue. + In Java 5 the PriorityQueue.remove method uses the compareTo method, + while in Java 6 it uses the equals method. + +

From the JavaDoc for the compareTo method in the Comparable interface: +

+It is strongly recommended, but not strictly required that (x.compareTo(y)==0) == (x.equals(y)). +Generally speaking, any class that implements the Comparable interface and violates this condition +should clearly indicate this fact. The recommended language +is "Note: this class has a natural ordering that is inconsistent with equals." +
]]>
+
+ + + + + This class defines a hashCode() method but not an + equals() method.  Therefore, the class may + violate the invariant that equal objects must have equal hashcodes.

]]>
+
+ + + + + This class overrides equals(Object), but does not + override hashCode(), and inherits the implementation of + hashCode() from java.lang.Object (which returns + the identity hash code, an arbitrary value assigned to the object + by the VM).  Therefore, the class is very likely to violate the + invariant that equal objects must have equal hashcodes.

+ +

If you don't think instances of this class will ever be inserted into a HashMap/HashTable, +the recommended hashCode implementation to use is:

+
public int hashCode() {
+  assert false : "hashCode not designed";
+  return 42; // any arbitrary constant will do 
+  }
]]>
+
+ + + + + This class inherits equals(Object) from an abstract + superclass, and hashCode() from +java.lang.Object (which returns + the identity hash code, an arbitrary value assigned to the object + by the VM).  Therefore, the class is very likely to violate the + invariant that equal objects must have equal hashcodes.

+ +

If you don't want to define a hashCode method, and/or don't + believe the object will ever be put into a HashMap/Hashtable, + define the hashCode() method + to throw UnsupportedOperationException.

]]>
+
+ + + + + This class overrides equals(Object), but does not + override hashCode().  Therefore, the class may violate the + invariant that equal objects must have equal hashcodes.

]]>
+
+ + + + + This class defines a covariant version of equals().  + To correctly override the equals() method in + java.lang.Object, the parameter of equals() + must have type java.lang.Object.

]]>
+
+ + + + + This code compares java.lang.String objects for reference +equality using the == or != operators. +Unless both strings are either constants in a source file, or have been +interned using the String.intern() method, the same string +value may be represented by two different String objects. Consider +using the equals(Object) method instead.

]]>
+
+ + + + + This code compares a java.lang.String parameter for reference +equality using the == or != operators. Requiring callers to +pass only String constants or interned strings to a method is unnecessarily +fragile, and rarely leads to measurable performance gains. Consider +using the equals(Object) method instead.

]]>
+
+ + + + + This class defines a covariant version of compareTo().  + To correctly override the compareTo() method in the + Comparable interface, the parameter of compareTo() + must have type java.lang.Object.

]]>
+
+ + + + + This field is annotated with net.jcip.annotations.GuardedBy, +but can be accessed in a way that seems to violate the annotation.

]]>
+
+ + + + + A web server generally only creates one instance of servlet or jsp class (i.e., treats +the class as a Singleton), +and will +have multiple threads invoke methods on that instance to service multiple +simultaneous requests. +Thus, having a mutable instance field generally creates race conditions.]]> + + + + + + The fields of this class appear to be accessed inconsistently with respect + to synchronization.  This bug report indicates that the bug pattern detector + judged that +

+
    +
  1. The class contains a mix of locked and unlocked accesses,
  2. +
  3. At least one locked access was performed by one of the class's own methods, and
  4. +
  5. The number of unsynchronized field accesses (reads and writes) was no more than + one third of all accesses, with writes being weighed twice as high as reads
  6. +
+ +

A typical bug matching this bug pattern is forgetting to synchronize + one of the methods in a class that is intended to be thread-safe.

+ +

You can select the nodes labeled "Unsynchronized access" to show the + code locations where the detector believed that a field was accessed + without synchronization.

+ +

Note that there are various sources of inaccuracy in this detector; + for example, the detector cannot statically detect all situations in which + a lock is held.  Also, even when the detector is accurate in + distinguishing locked vs. unlocked accesses, the code in question may still + be correct.

]]>
+
+ + + + + A call to notify() or notifyAll() + was made without any (apparent) accompanying + modification to mutable object state.  In general, calling a notify + method on a monitor is done because some condition another thread is + waiting for has become true.  However, for the condition to be meaningful, + it must involve a heap object that is visible to both threads.

+ +

This bug does not necessarily indicate an error, since the change to + mutable object state may have taken place in a method which then called + the method containing the notification.

]]>
+
+ + + + + + A public static method returns a reference to + an array that is part of the static state of the class. + Any code that calls this method can freely modify + the underlying array. + One fix is to return a copy of the array.

]]>
+
+ + + + + + Returning a reference to a mutable object value stored in one of the object's fields + exposes the internal representation of the object.  + If instances + are accessed by untrusted code, and unchecked changes to + the mutable object would compromise security or other + important properties, you will need to do something different. + Returning a new copy of the object is better approach in many situations.

]]>
+
+ + + + + + This code stores a reference to an externally mutable object into the + internal representation of the object.  + If instances + are accessed by untrusted code, and unchecked changes to + the mutable object would compromise security or other + important properties, you will need to do something different. + Storing a copy of the object is better approach in many situations.

]]>
+
+ + + + + + This code stores a reference to an externally mutable object into a static + field. + If unchecked changes to + the mutable object would compromise security or other + important properties, you will need to do something different. + Storing a copy of the object is better approach in many situations.

]]>
+
+ + + + + This method explicitly invokes run() on an object.  + In general, classes implement the Runnable interface because + they are going to have their run() method invoked in a new thread, + in which case Thread.start() is the right method to call.

]]>
+
+ + + + + This method spins in a loop which reads a field.  The compiler + may legally hoist the read out of the loop, turning the code into an + infinite loop.  The class should be changed so it uses proper + synchronization (including wait and notify calls).

]]>
+
+ + + + + This code seems to be using non-short-circuit logic (e.g., & +or |) +rather than short-circuit logic (&& or ||). In addition, +it seem possible that, depending on the value of the left hand side, you might not +want to evaluate the right hand side (because it would have side effects, could cause an exception +or could be expensive.

+

+Non-short-circuit logic causes both sides of the expression +to be evaluated even when the result can be inferred from +knowing the left-hand side. This can be less efficient and +can result in errors if the left-hand side guards cases +when evaluating the right-hand side can generate an error. +

+ +

See the Java +Language Specification for details + +

]]>
+
+ + + + + This code seems to be using non-short-circuit logic (e.g., & +or |) +rather than short-circuit logic (&& or ||). +Non-short-circuit logic causes both sides of the expression +to be evaluated even when the result can be inferred from +knowing the left-hand side. This can be less efficient and +can result in errors if the left-hand side guards cases +when evaluating the right-hand side can generate an error. + +

See the Java +Language Specification for details + +

]]>
+
+ + + + + Waiting on a monitor while two locks are held may cause + deadlock. +   + Performing a wait only releases the lock on the object + being waited on, not any other locks. +   +This not necessarily a bug, but is worth examining + closely.

]]>
+
+ + + + + This method contains a call to java.lang.Object.wait() which + is not guarded by conditional control flow.  The code should + verify that condition it intends to wait for is not already satisfied + before calling wait; any previous notifications will be ignored. +

]]>
+
+ + + + + This constructor reads a field which has not yet been assigned a value.  + This is often caused when the programmer mistakenly uses the field instead + of one of the constructor's parameters.

]]>
+
+ + + + + This class contains similarly-named get and set + methods where the set method is synchronized and the get method is not.  + This may result in incorrect behavior at runtime, as callers of the get + method will not necessarily see a consistent state for the object.  + The get method should be made synchronized.

]]>
+
+ + + + + A circularity was detected in the static initializers of the two + classes referenced by the bug instance.  Many kinds of unexpected + behavior may arise from such circularity.

]]>
+
+ + + + + During the initialization of a class, the class makes an active use of a subclass. +That subclass will not yet be initialized at the time of this use. +For example, in the following code, foo will be null.

+ +
+public class CircularClassInitialization {
+	static class InnerClassSingleton extends CircularClassInitialization {
+		static InnerClassSingleton singleton = new InnerClassSingleton();
+	}
+	
+	static CircularClassInitialization foo = InnerClassSingleton.singleton;
+}
+
]]>
+
+ + + + + This class implements the java.util.Iterator interface.  + However, its next() method is not capable of throwing + java.util.NoSuchElementException.  The next() + method should be changed so it throws NoSuchElementException + if is called when there are no more elements to return.

]]>
+
+ + + + + The code synchronizes on interned String. +
+private static String LOCK = "LOCK";
+...
+  synchronized(LOCK) { ...}
+...
+
+

+

Constant Strings are interned and shared across all other classes loaded by the JVM. Thus, this could +is locking on something that other code might also be locking. This could result in very strange and hard to diagnose +blocking and deadlock behavior. See http://www.javalobby.org/java/forums/t96352.html and http://jira.codehaus.org/browse/JETTY-352. +

]]>
+
+ + + + + The code synchronizes on a boxed primitive constant, such as an Boolean. +
+private static Boolean inited = Boolean.FALSE;
+...
+  synchronized(inited) { 
+    if (!inited) {
+       init();
+       inited = Boolean.TRUE;
+       }
+     }
+...
+
+

+

Since there normally exist only two Boolean objects, this code could be synchronizing on the same object as other, unrelated code, leading to unresponsiveness +and possible deadlock

]]>
+
+ + + + + The code synchronizes on an apparently unshared boxed primitive, +such as an Integer. +
+private static final Integer fileLock = new Integer(1);
+...
+  synchronized(fileLock) { 
+     .. do something ..
+     }
+...
+
+

+

It would be much better, in this code, to redeclare fileLock as +

+private static final Object fileLock = new Object();
+
+The existing code might be OK, but it is confusing and a +future refactoring, such as the "Remove Boxing" refactoring in IntelliJ, +might replace this with the use of an interned Integer object shared +throughout the JVM, leading to very confusing behavior and potential deadlock. +

]]>
+
+ + + + + The code synchronizes on a boxed primitive constant, such as an Integer. +
+private static Integer count = 0;
+...
+  synchronized(count) { 
+     count++;
+     }
+...
+
+

+

Since Integer objects can be cached and shared, +this code could be synchronizing on the same object as other, unrelated code, leading to unresponsiveness +and possible deadlock

]]>
+
+ + + + + The code contains an empty synchronized block:

+
+synchronized() {}
+
+

Empty synchronized blocks are far more subtle and hard to use correctly +than most people recognize, and empty synchronized blocks +are almost never a better solution +than less contrived solutions. +

]]>
+
+ + + + + The fields of this class appear to be accessed inconsistently with respect + to synchronization.  This bug report indicates that the bug pattern detector + judged that +

+
    +
  1. The class contains a mix of locked and unlocked accesses,
  2. +
  3. At least one locked access was performed by one of the class's own methods, and
  4. +
  5. The number of unsynchronized field accesses (reads and writes) was no more than + one third of all accesses, with writes being weighed twice as high as reads
  6. +
+ +

A typical bug matching this bug pattern is forgetting to synchronize + one of the methods in a class that is intended to be thread-safe.

+ +

Note that there are various sources of inaccuracy in this detector; + for example, the detector cannot statically detect all situations in which + a lock is held.  Also, even when the detector is accurate in + distinguishing locked vs. unlocked accesses, the code in question may still + be correct.

]]>
+
+ + + + + This method synchronizes on a field in what appears to be an attempt +to guard against simultaneous updates to that field. But guarding a field +gets a lock on the referenced object, not on the field. This may not +provide the mutual exclusion you need, and other threads might +be obtaining locks on the referenced objects (for other purposes). An example +of this pattern would be: + +

+private Long myNtfSeqNbrCounter = new Long(0);
+private Long getNotificationSequenceNumber() {
+     Long result = null;
+     synchronized(myNtfSeqNbrCounter) {
+         result = new Long(myNtfSeqNbrCounter.longValue() + 1);
+         myNtfSeqNbrCounter = new Long(result.longValue());
+     }
+     return result;
+ }
+
+ + +

]]>
+
+ + + + + This method synchronizes on an object + referenced from a mutable field. + This is unlikely to have useful semantics, since different +threads may be synchronizing on different objects.

]]>
+
+ + + + + + + A final static field that is +defined in an interface references a mutable + object such as an array or hashtable. + This mutable object could + be changed by malicious code or + by accident from another package. + To solve this, the field needs to be moved to a class + and made package protected + to avoid + this vulnerability.

]]>
+
+ + + + + + A mutable static field could be changed by malicious code or + by accident from another package. + The field could be made package protected and/or made final + to avoid + this vulnerability.

]]>
+
+ + + + + + A mutable static field could be changed by malicious code or + by accident from another package. + The field could be made final to avoid + this vulnerability.

]]>
+
+ + + + + A mutable static field could be changed by malicious code or + by accident. + The field could be made package protected to avoid + this vulnerability.

]]>
+
+ + + + + A final static field references a Hashtable + and can be accessed by malicious code or + by accident from another package. + This code can freely modify the contents of the Hashtable.

]]>
+
+ + + + + A final static field references an array + and can be accessed by malicious code or + by accident from another package. + This code can freely modify the contents of the array.

]]>
+
+ + + + + + A mutable static field could be changed by malicious code or + by accident from another package. + Unfortunately, the way the field is used doesn't allow + any easy fix to this problem.

]]>
+
+ + + + + An inner class is invoking a method that could be resolved to either a inherited method or a method defined in an outer class. By the Java semantics, +it will be resolved to invoke the inherited method, but this may not be want +you intend. If you really intend to invoke the inherited method, +invoke it by invoking the method on super (e.g., invoke super.foo(17)), and +thus it will be clear to other readers of your code and to FindBugs +that you want to invoke the inherited method, not the method in the outer class. +

]]>
+
+ + + + + This class has a simple name that is identical to that of its superclass, except +that its superclass is in a different package (e.g., alpha.Foo extends beta.Foo). +This can be exceptionally confusing, create lots of situations in which you have to look at import statements +to resolve references and creates many +opportunities to accidently define methods that do not override methods in their superclasses. +

]]>
+
+ + + + + This class/interface has a simple name that is identical to that of an implemented/extended interface, except +that the interface is in a different package (e.g., alpha.Foo extends beta.Foo). +This can be exceptionally confusing, create lots of situations in which you have to look at import statements +to resolve references and creates many +opportunities to accidently define methods that do not override methods in their superclasses. +

]]>
+
+ + + + + The referenced methods have names that differ only by capitalization. +This is very confusing because if the capitalization were +identical then one of the methods would override the other. +

]]>
+
+ + + + + The referenced methods have names that differ only by capitalization. +This is very confusing because if the capitalization were +identical then one of the methods would override the other. From the existence of other methods, it +seems that the existence of both of these methods is intentional, but is sure is confusing. +You should try hard to eliminate one of them, unless you are forced to have both due to frozen APIs. +

]]>
+
+ + + + + + The method in the subclass doesn't override a similar method in a superclass because the type of a parameter doesn't exactly match +the type of the corresponding parameter in the superclass. For example, if you have:

+ +
+
+import alpha.Foo;
+public class A {
+  public int f(Foo x) { return 17; }
+}
+----
+import beta.Foo;
+public class B extends A {
+  public int f(Foo x) { return 42; }
+}
+
+
+ +

The f(Foo) method defined in class B doesn't +override the +f(Foo) method defined in class A, because the argument +types are Foo's from different packages. +

]]>
+
+ + + + + + The method in the subclass doesn't override a similar method in a superclass because the type of a parameter doesn't exactly match +the type of the corresponding parameter in the superclass. For example, if you have:

+ +
+
+import alpha.Foo;
+public class A {
+  public int f(Foo x) { return 17; }
+}
+----
+import beta.Foo;
+public class B extends A {
+  public int f(Foo x) { return 42; }
+  public int f(alpha.Foo x) { return 27; }
+}
+
+
+ +

The f(Foo) method defined in class B doesn't +override the +f(Foo) method defined in class A, because the argument +types are Foo's from different packages. +

+ +

In this case, the subclass does define a method with a signature identical to the method in the superclass, +so this is presumably understood. However, such methods are exceptionally confusing. You should strongly consider +removing or deprecating the method with the similar but not identical signature. +

]]>
+
+ + + + + The referenced methods have names that differ only by capitalization.

]]>
+
+ + + + + This regular method has the same name as the class it is defined in. It is likely that this was intended to be a constructor. + If it was intended to be a constructor, remove the declaration of a void return value. + If you had accidently defined this method, realized the mistake, defined a proper constructor + but can't get rid of this method due to backwards compatibility, deprecate the method. +

]]>
+
+ + + + + This class is not derived from another exception, but ends with 'Exception'. This will +be confusing to users of this class.

]]>
+
+ + + + + This method ignores the return value of one of the variants of + java.io.InputStream.read() which can return multiple bytes.  + If the return value is not checked, the caller will not be able to correctly + handle the case where fewer bytes were read than the caller requested.  + This is a particularly insidious kind of bug, because in many programs, + reads from input streams usually do read the full amount of data requested, + causing the program to fail only sporadically.

]]>
+
+ + + + + This method ignores the return value of + java.io.InputStream.skip() which can skip multiple bytes.  + If the return value is not checked, the caller will not be able to correctly + handle the case where fewer bytes were skipped than the caller requested.  + This is a particularly insidious kind of bug, because in many programs, + skips from input streams usually do skip the full amount of data requested, + causing the program to fail only sporadically. With Buffered streams, however, + skip() will only skip data in the buffer, and will routinely fail to skip the + requested number of bytes.

]]>
+
+ + + + + In order for the readResolve method to be recognized by the serialization +mechanism, it must not be declared as a static method. +

]]>
+
+ + + + + This class defines a private readResolve method. Since it is private, it won't be inherited by subclasses. +This might be intentional and OK, but should be reviewed to ensure it is what is intended. +

]]>
+
+ + + + + In order for the readResolve method to be recognized by the serialization +mechanism, it must be declared to have a return type of Object. +

]]>
+
+ + + + + The field is marked as transient, but the class isn't Serializable, so marking it as transient +has absolutely no effect. +This may be leftover marking from a previous version of the code in which the class was transient, or +it may indicate a misunderstanding of how serialization works. +

]]>
+
+ + + + + This class contains a field that is updated at multiple places in the class, thus it seems to be part of the state of the class. However, since the field is marked as transient and not set in readObject or readResolve, it will contain the default value in any +deserialized instance of the class. +

]]>
+
+ + + + + This class implements the Serializable interface, and defines a method + for custom serialization/deserialization. But since that method isn't declared private, + it will be silently ignored by the serialization/deserialization API.

]]>
+
+ + + + + This class implements the Externalizable interface, but does + not define a void constructor. When Externalizable objects are deserialized, + they first need to be constructed by invoking the void + constructor. Since this class does not have one, + serialization and deserialization will fail at runtime.

]]>
+
+ + + + + This class implements the Serializable interface + and its superclass does not. When such an object is deserialized, + the fields of the superclass need to be initialized by + invoking the void constructor of the superclass. + Since the superclass does not have one, + serialization and deserialization will fail at runtime.

]]>
+
+ + + + + This class implements the Serializable interface, but does + not define a serialVersionUID field.  + A change as simple as adding a reference to a .class object + will add synthetic fields to the class, + which will unfortunately change the implicit + serialVersionUID (e.g., adding a reference to String.class + will generate a static field class$java$lang$String). + Also, different source code to bytecode compilers may use different + naming conventions for synthetic variables generated for + references to class objects or inner classes. + To ensure interoperability of Serializable across versions, + consider adding an explicit serialVersionUID.

]]>
+
+ + + + + This class implements the Comparator interface. You +should consider whether or not it should also implement the Serializable +interface. If a comparator is used to construct an ordered collection +such as a TreeMap, then the TreeMap +will be serializable only if the comparator is also serializable. +As most comparators have little or no state, making them serializable +is generally easy and good defensive programming. +

]]>
+
+ + + + + + This class has a writeObject() method which is synchronized; + however, no other method of the class is synchronized.

]]>
+
+ + + + + This serializable class defines a readObject() which is + synchronized.  By definition, an object created by deserialization + is only reachable by one thread, and thus there is no need for + readObject() to be synchronized.  If the readObject() + method itself is causing the object to become visible to another thread, + that is an example of very dubious coding style.

]]>
+
+ + + + + This class defines a serialVersionUID field that is not static.  + The field should be made static + if it is intended to specify + the version UID for purposes of serialization.

]]>
+
+ + + + + This class defines a serialVersionUID field that is not final.  + The field should be made final + if it is intended to specify + the version UID for purposes of serialization.

]]>
+
+ + + + + This class defines a serialVersionUID field that is not long.  + The field should be made long + if it is intended to specify + the version UID for purposes of serialization.

]]>
+
+ + + + + This Serializable class is an inner class of a non-serializable class. +Thus, attempts to serialize it will also attempt to associate instance of the outer +class with which it is associated, leading to a runtime error. +

+

If possible, making the inner class a static inner class should solve the +problem. Making the outer class serializable might also work, but that would +mean serializing an instance of the inner class would always also serialize the instance +of the outer class, which it often not what you really want.]]> + + + + + + This Serializable class is an inner class. Any attempt to serialize +it will also serialize the associated outer instance. The outer instance is serializable, +so this won't fail, but it might serialize a lot more data than intended. +If possible, making the inner class a static inner class (also known as a nested class) should solve the +problem.]]> + + + + + + A non-serializable value is stored into a non-transient field +of a serializable class.

]]>
+
+ + + + + The constructor starts a thread. This is likely to be wrong if + the class is ever extended/subclassed, since the thread will be started + before the subclass constructor is started.

]]>
+
+ + + + + This class contains an instance final field that + is initialized to a compile-time static value. + Consider making the field static.

]]>
+
+ + + + + This field is never used.  Consider removing it from the class.

]]>
+
+ + + + + This field is never read.  Consider removing it from the class.

]]>
+
+ + + + + Are you sure this for loop is incrementing the correct variable? + It appears that another variable is being initialized and checked + by the for loop. +

]]>
+
+ + + + + All writes to this field are of the constant value null, and thus +all reads of the field will return null. +Check for errors, or remove it if it is useless.

]]>
+
+ + + + + This instance method writes to a static field. This is tricky to get +correct if multiple instances are being manipulated, +and generally bad practice. +

]]>
+
+ + + + + The variable referenced at this point is known to be null due to an earlier + check against null. Although this is valid, it might be a mistake (perhaps you +intended to refer to a different variable, or perhaps the earlier check to see if the +variable is null should have been a check to see if it was nonnull). +

]]>
+
+ + + + + The result of invoking readLine() is dereferenced without checking to see if the result is null. If there are no more lines of text +to read, readLine() will return null and dereferencing that will generate a null pointer exception. +

]]>
+
+ + + + + The result of invoking readLine() is immediately dereferenced. If there are no more lines of text +to read, readLine() will return null and dereferencing that will generate a null pointer exception. +

]]>
+
+ + + + + This class is an inner class, but does not use its embedded reference + to the object which created it.  This reference makes the instances + of the class larger, and may keep the reference to the creator object + alive longer than necessary.  If possible, the class should be + made static. +

]]>
+
+ + + + + This class is an inner class, but does not use its embedded reference + to the object which created it.  This reference makes the instances + of the class larger, and may keep the reference to the creator object + alive longer than necessary.  If possible, the class should be + made into a static inner class. Since anonymous inner +classes cannot be marked as static, doing this will require refactoring +the inner class so that it is a named inner class.

]]>
+
+ + + + + This class is an inner class, but does not use its embedded reference + to the object which created it except during construction of the +inner object.  This reference makes the instances + of the class larger, and may keep the reference to the creator object + alive longer than necessary.  If possible, the class should be + made into a static inner class. Since the reference to the + outer object is required during construction of the inner instance, + the inner class will need to be refactored so as to + pass a reference to the outer instance to the constructor + for the inner class.

]]>
+
+ + + + + This method contains a call to java.lang.Object.wait() + which is not in a loop.  If the monitor is used for multiple conditions, + the condition the caller intended to wait for might not be the one + that actually occurred.

]]>
+
+ + + + + This method contains a call to java.util.concurrent.await() + (or variants) + which is not in a loop.  If the object is used for multiple conditions, + the condition the caller intended to wait for might not be the one + that actually occurred.

]]>
+
+ + + + + This method calls notify() rather than notifyAll().  + Java monitors are often used for multiple conditions.  Calling notify() + only wakes up one thread, meaning that the thread woken up might not be the + one waiting for the condition that the caller just satisfied.

]]>
+
+ + + + + The method invokes String.indexOf and checks to see if the result is positive or non-positive. + It is much more typical to check to see if the result is negative or non-negative. It is + positive only if the substring checked for occurs at some place other than at the beginning of + the String.

]]>
+
+ + + + + The value returned by readLine is discarded after checking to see if the return +value is non-null. In almost all situations, if the result is non-null, you will want +to use that non-null value. Calling readLine again will give you a different line.

]]>
+
+ + + + + The return value of this method should be checked. One common +cause of this warning is to invoke a method on an immutable object, +thinking that it updates the object. For example, in the following code +fragment,

+
+
+String dateString = getHeaderField(name);
+dateString.trim();
+
+
+

the programmer seems to be thinking that the trim() method will update +the String referenced by dateString. But since Strings are immutable, the trim() +function returns a new String value, which is being ignored here. The code +should be corrected to:

+
+
+String dateString = getHeaderField(name);
+dateString = dateString.trim();
+
+
]]>
+
+ + + + + This method returns a value that is not checked. The return value should be checked +since it can indicate an unusual or unexpected function execution. For +example, the File.delete() method returns false +if the file could not be successfully deleted (rather than +throwing an Exception). +If you don't check the result, you won't notice if the method invocation +signals unexpected behavior by returning an atypical return value. +

]]>
+
+ + + + + This code creates an exception (or error) object, but doesn't do anything with it. For example, +something like

+
+
+if (x < 0)
+  new IllegalArgumentException("x must be nonnegative");
+
+
+

It was probably the intent of the programmer to throw the created exception:

+
+
+if (x < 0)
+  throw new IllegalArgumentException("x must be nonnegative");
+
+
]]>
+
+ + + + + The return value of this method should be checked. One common +cause of this warning is to invoke a method on an immutable object, +thinking that it updates the object. For example, in the following code +fragment,

+
+
+String dateString = getHeaderField(name);
+dateString.trim();
+
+
+

the programmer seems to be thinking that the trim() method will update +the String referenced by dateString. But since Strings are immutable, the trim() +function returns a new String value, which is being ignored here. The code +should be corrected to:

+
+
+String dateString = getHeaderField(name);
+dateString = dateString.trim();
+
+
]]>
+
+ + + + + A null pointer is dereferenced here.  This will lead to a +NullPointerException when the code is executed.

]]>
+
+ + + + + + A value that could be null is stored into a field that has been annotated as NonNull.

]]>
+
+ + + + + A pointer which is null on an exception path is dereferenced here.  +This will lead to a NullPointerException when the code is executed.  +Note that because FindBugs currently does not prune infeasible exception paths, +this may be a false warning.

+ +

Also note that FindBugs considers the default case of a switch statement to +be an exception path, since the default case is often infeasible.

]]>
+
+ + + + + This parameter is always used in a way that requires it to be nonnull, +but the parameter is explicitly annotated as being Nullable. Either the use +of the parameter or the annotation is wrong. +

]]>
+
+ + + + + There is a branch of statement that, if executed, guarantees that +a null value will be dereferenced, which +would generate a NullPointerException when the code is executed. +Of course, the problem might be that the branch or statement is infeasible and that +the null pointer exception can't ever be executed; deciding that is beyond the ability of FindBugs. +

]]>
+
+ + + + + There is a branch of statement that, if executed, guarantees that +a null value will be dereferenced, which +would generate a NullPointerException when the code is executed. +Of course, the problem might be that the branch or statement is infeasible and that +the null pointer exception can't ever be executed; deciding that is beyond the ability of FindBugs. +Due to the fact that this value had been previously tested for nullness, this is a definite possibility. +

]]>
+
+ + + + + A reference value which is null on some exception control path is +dereferenced here.  This may lead to a NullPointerException +when the code is executed.  +Note that because FindBugs currently does not prune infeasible exception paths, +this may be a false warning.

+ +

Also note that FindBugs considers the default case of a switch statement to +be an exception path, since the default case is often infeasible.

]]>
+
+ + + + + The return value from a method is dereferenced without a null check, +and the return value of that method is one that should generally be checked +for null. This may lead to a NullPointerException when the code is executed. +

]]>
+
+ + + + + + A possibly-null value is passed to a nonnull method parameter. + Either the parameter is annotated as a parameter that should + always be nonnull, or analysis has shown that it will always be + dereferenced. +

]]>
+
+ + + + + + A possibly-null value is passed at a call site where all known + target methods require the parameter to be nonnull. + Either the parameter is annotated as a parameter that should + always be nonnull, or analysis has shown that it will always be + dereferenced. +

]]>
+
+ + + + + + This method call passes a null value for a nonnull method parameter. + Either the parameter is annotated as a parameter that should + always be nonnull, or analysis has shown that it will always be + dereferenced. +

]]>
+
+ + + + + + This method passes a null value as the parameter of a method which + must be nonnull. Either this parameter has been explicitly marked + as @Nonnull, or analysis has determined that this parameter is + always dereferenced. +

]]>
+
+ + + + + + This method may return a null value, but the method (or a superclass method + which it overrides) is declared to return @NonNull. +

]]>
+
+ + + + + + This clone method seems to return null in some circumstances, but clone is never + allowed to return a null value. If you are convinced this path is unreachable, throw an AssertionError + instead. +

]]>
+
+ + + + + + This toString method seems to return null in some circumstances. A liberal reading of the + spec could be interpreted as allowing this, but it is probably a bad idea and could cause + other code to break. Return the empty string or some other appropriate string rather than null. +

]]>
+
+ + + + + + There is a statement or branch that if executed guarantees that + a value is null at this point, and that + value that is guaranteed to be dereferenced + (except on forward paths involving runtime exceptions). +

]]>
+
+ + + + + + There is a statement or branch on an exception path + that if executed guarantees that + a value is null at this point, and that + value that is guaranteed to be dereferenced + (except on forward paths involving runtime exceptions). +

]]>
+
+ + + + + The class's static initializer creates an instance of the class +before all of the static final fields are assigned.

]]>
+
+ + + + + The method creates an IO stream object, does not assign it to any +fields, pass it to other methods that might close it, +or return it, and does not appear to close +the stream on all paths out of the method.  This may result in +a file descriptor leak.  It is generally a good +idea to use a finally block to ensure that streams are +closed.

]]>
+
+ + + + + The method creates an IO stream object, does not assign it to any +fields, pass it to other methods, or return it, and does not appear to close +it on all possible exception paths out of the method.  +This may result in a file descriptor leak.  It is generally a good +idea to use a finally block to ensure that streams are +closed.

]]>
+
+ + + + + It is often a better design to +return a length zero array rather than a null reference to indicate that there +are no results (i.e., an empty list of results). +This way, no explicit check for null is needed by clients of the method.

+ +

On the other hand, using null to indicate +"there is no answer to this question" is probably appropriate. +For example, File.listFiles() returns an empty list +if given a directory containing no files, and returns null if the file +is not a directory.

]]>
+
+ + + + + This method contains a useless control flow statement, where +control flow continues onto the same place regardless of whether or not +the branch is taken. For example, +this is caused by having an empty statement +block for an if statement:

+
+    if (argv.length == 0) {
+	// TODO: handle this case
+	}
+
]]>
+
+ + + + + This method contains a useless control flow statement in which control +flow follows to the same or following line regardless of whether or not +the branch is taken. +Often, this is caused by inadvertently using an empty statement as the +body of an if statement, e.g.:

+
+    if (argv.length == 1);
+        System.out.println("Hello, " + argv[0]);
+
]]>
+
+ + + + + A value is checked here to see whether it is null, but this value can't +be null because it was previously dereferenced and if it were null a null pointer +exception would have occurred at the earlier dereference. +Essentially, this code and the previous dereference +disagree as to whether this value is allowed to be null. Either the check is redundant +or the previous dereference is erroneous.

]]>
+
+ + + + + This method contains a redundant check of a known null value against +the constant null.

]]>
+
+ + + + + This method contains a redundant check of a known non-null value against +the constant null.

]]>
+
+ + + + + This method contains a redundant comparison of two references known to +both be definitely null.

]]>
+
+ + + + + This method contains a reference known to be non-null with another reference +known to be null.

]]>
+
+ + + + + This method acquires a JSR-166 (java.util.concurrent) lock, +but does not release it on all paths out of the method. In general, the correct idiom +for using a JSR-166 lock is: +

+
+    Lock l = ...;
+    l.lock();
+    try {
+        // do something
+    } finally {
+        l.unlock();
+    }
+
]]>
+
+ + + + + This method acquires a JSR-166 (java.util.concurrent) lock, +but does not release it on all exception paths out of the method. In general, the correct idiom +for using a JSR-166 lock is: +

+
+    Lock l = ...;
+    l.lock();
+    try {
+        // do something
+    } finally {
+        l.unlock();
+    }
+
]]>
+
+ + + + + This method compares two reference values using the == or != operator, +where the correct way to compare instances of this type is generally +with the equals() method. Examples of classes which should generally +not be compared by reference are java.lang.Integer, java.lang.Float, etc.

]]>
+
+ + + + + This method uses using pointer equality to compare two references that seem to be of +different types. The result of this comparison will always be false at runtime. +

]]>
+
+ + + + + This method calls equals(Object) on two references of different +class types with no common subclasses. +Therefore, the objects being compared +are unlikely to be members of the same class at runtime +(unless some application classes were not analyzed, or dynamic class +loading can occur at runtime). +According to the contract of equals(), +objects of different +classes should always compare as unequal; therefore, according to the +contract defined by java.lang.Object.equals(Object), +the result of this comparison will always be false at runtime. +

]]>
+
+ + + + + This method calls equals(Object) on two references of unrelated +interface types, where neither is a subtype of the other, +and there are no known non-abstract classes which implement both interfaces. +Therefore, the objects being compared +are unlikely to be members of the same class at runtime +(unless some application classes were not analyzed, or dynamic class +loading can occur at runtime). +According to the contract of equals(), +objects of different +classes should always compare as unequal; therefore, according to the +contract defined by java.lang.Object.equals(Object), +the result of this comparison will always be false at runtime. +

]]>
+
+ + + + + +This method calls equals(Object) on two references, one of which is a class +and the other an interface, where neither the class nor any of its +non-abstract subclasses implement the interface. +Therefore, the objects being compared +are unlikely to be members of the same class at runtime +(unless some application classes were not analyzed, or dynamic class +loading can occur at runtime). +According to the contract of equals(), +objects of different +classes should always compare as unequal; therefore, according to the +contract defined by java.lang.Object.equals(Object), +the result of this comparison will always be false at runtime. +

]]>
+
+ + + + + This method calls equals(Object), passing a null value as +the argument. According to the contract of the equals() method, +this call should always return false.

]]>
+
+ + + + + This method calls Object.wait() without obviously holding a lock +on the object.  Calling wait() without a lock held will result in +an IllegalMonitorStateException being thrown.

]]>
+
+ + + + + This method calls Object.notify() or Object.notifyAll() without obviously holding a lock +on the object.  Calling notify() or notifyAll() without a lock held will result in +an IllegalMonitorStateException being thrown.

]]>
+
+ + + + + This method contains a self assignment of a local variable; e.g.

+
+  public void foo() {
+    int x = 3;
+    x = x;
+  }
+
+

+Such assignments are useless, and may indicate a logic error or typo. +

]]>
+
+ + + + + This method contains a self assignment of a field; e.g. +

+
+  int x;
+  public void foo() {
+    x = x;
+  }
+
+

Such assignments are useless, and may indicate a logic error or typo.

]]>
+
+ + + + + This method contains a double assignment of a field; e.g. +

+
+  int x,y;
+  public void foo() {
+    x = x = 17;
+  }
+
+

Assigning to a field twice is useless, and may indicate a logic error or typo.

]]>
+
+ + + + + This method contains a double assignment of a local variable; e.g. +

+
+  public void foo() {
+    int x,y;
+    x = x = 17;
+  }
+
+

Assigning the same value to a variable twice is useless, and may indicate a logic error or typo.

]]>
+
+ + + + + This method performs a nonsensical computation of a field with another +reference to the same field (e.g., x&x or x-x). Because of the nature +of the computation, this operation doesn't seem to make sense, +and may indicate a typo or +a logic error. Double check the computation. +

]]>
+
+ + + + + This method performs a nonsensical computation of a local variable with another +reference to the same variable (e.g., x&x or x-x). Because of the nature +of the computation, this operation doesn't seem to make sense, +and may indicate a typo or +a logic error. Double check the computation. +

]]>
+
+ + + + + This method compares a field with itself, and may indicate a typo or +a logic error. Make sure that you are comparing the right things. +

]]>
+
+ + + + + This method compares a local variable with itself, and may indicate a typo or +a logic error. Make sure that you are comparing the right things. +

]]>
+
+ + + + + The Double.longBitsToDouble method is invoked, but a 32 bit int value is passed + as an argument. This almostly certainly is not intended and is unlikely + to give the intended result. +

]]>
+
+ + + + + This code creates a java.util.Random object, uses it to generate one random number, and then discards +the Random object. This produces mediocre quality random numbers and is inefficient. +If possible, rewrite the code so that the Random object is created once and saved, and each time a new random number +is required invoke a method on the existing Random object to obtain it. +

+ +

If it is important that the generated Random numbers not be guessable, you must not create a new Random for each random +number; the values are too easily guessable. You should strongly consider using a java.security.SecureRandom instead +(and avoid allocating a new SecureRandom for each random number needed). +

]]>
+
+ + + + + This code generates a random signed integer and then computes +the absolute value of that random integer. If the number returned by the random number +generator is Integer.MIN_VALUE, then the result will be negative as well (since +Math.abs(Integer.MIN_VALUE) == Integer.MIN_VALUE). +

]]>
+
+ + + + + This code generates a hashcode and then computes +the absolute value of that hashcode. If the hashcode +is Integer.MIN_VALUE, then the result will be negative as well (since +Math.abs(Integer.MIN_VALUE) == Integer.MIN_VALUE). +

]]>
+
+ + + + + This code generates a random signed integer and then computes +the remainder of that value modulo another value. Since the random +number can be negative, the result of the remainder operation +can also be negative. Be sure this is intended, and strongly +consider using the Random.nextInt(int) method instead. +

]]>
+
+ + + + + This code computes a hashCode, and then computes +the remainder of that value modulo another value. Since the hashCode +can be negative, the result of the remainder operation +can also be negative.

+

Assuming you want to ensure that the result of your computation is nonnegative, +you may need to change your code. +If you know the divisor is a power of 2, +you can use a bitwise and operator instead (i.e., instead of +using x.hashCode()%n, use x.hashCode()&(n-1). +This is probably faster than computing the remainder as well. +If you don't know that the divisor is a power of 2, take the absolute +value of the result of the remainder operation (i.e., use +Math.abs(x.hashCode()%n) +

]]>
+
+ + + + + This code compares a value that is guaranteed to be non-negative with a negative constant. +

]]>
+
+ + + + + Signed bytes can only have a value in the range -128 to 127. Comparing +a signed byte with a value outside that range is vacuous and likely to be incorrect. +To convert a signed byte b to an unsigned value in the range 0..255, +use 0xff & b +

]]>
+
+ + + + + This is an integer bit operation (and, or, or exclusive or) that doesn't do any useful work +(e.g., v & 0xffffffff). + +

]]>
+
+ + + + + There is an integer comparison that always returns +the same value (e.g., x <= Integer.MAX_VALUE). +

]]>
+
+ + + + + Any expression (exp % 1) is guaranteed to always return zero. +Did you mean (exp & 1) or (exp % 2) instead? +

]]>
+
+ + + + + Loads a value from a byte array and performs a bitwise OR with +that value. Values loaded from a byte array are sign extended to 32 bits +before any any bitwise operations are performed on the value. +Thus, if b[0] contains the value 0xff, and +x is initially 0, then the code +((x << 8) | b[0]) will sign extend 0xff +to get 0xffffffff, and thus give the value +0xffffffff as the result. +

+ +

In particular, the following code for packing a byte array into an int is badly wrong:

+
+int result = 0;
+for(int i = 0; i < 4; i++) 
+  result = ((result << 8) | b[i]);
+
+ +

The following idiom will work instead:

+
+int result = 0;
+for(int i = 0; i < 4; i++) 
+  result = ((result << 8) | (b[i] & 0xff));
+
]]>
+
+ + + + + Adds a byte value and a value which is known to the 8 lower bits clear. +Values loaded from a byte array are sign extended to 32 bits +before any any bitwise operations are performed on the value. +Thus, if b[0] contains the value 0xff, and +x is initially 0, then the code +((x << 8) + b[0]) will sign extend 0xff +to get 0xffffffff, and thus give the value +0xffffffff as the result. +

+ +

In particular, the following code for packing a byte array into an int is badly wrong:

+
+int result = 0;
+for(int i = 0; i < 4; i++) 
+  result = ((result << 8) + b[i]);
+
+ +

The following idiom will work instead:

+
+int result = 0;
+for(int i = 0; i < 4; i++) 
+  result = ((result << 8) + (b[i] & 0xff));
+
]]>
+
+ + + + + This method compares an expression of the form (e & C) to D, +which will always compare unequal +due to the specific values of constants C and D. +This may indicate a logic error or typo.

]]>
+
+ + + + + This method compares an expression such as +
((event.detail & SWT.SELECTED) > 0)
. +Using bit arithmetic and then comparing with the greater than operator can +lead to unexpected results (of course depending on the value of +SWT.SELECTED). If SWT.SELECTED is a negative number, this is a candidate +for a bug. Even when SWT.SELECTED is not negative, it seems good practice +to use '!= 0' instead of '> 0'. +

+

+Boris Bokowski +

]]>
+
+ + + + + This method compares an expression such as +
((event.detail & SWT.SELECTED) > 0)
. +Using bit arithmetic and then comparing with the greater than operator can +lead to unexpected results (of course depending on the value of +SWT.SELECTED). If SWT.SELECTED is a negative number, this is a candidate +for a bug. Even when SWT.SELECTED is not negative, it seems good practice +to use '!= 0' instead of '> 0'. +

+

+Boris Bokowski +

]]>
+
+ + + + + This method compares an expression of the form (e & 0) to 0, +which will always compare equal. +This may indicate a logic error or typo.

]]>
+
+ + + + + This method compares an expression of the form (e | C) to D. +which will always compare unequal +due to the specific values of constants C and D. +This may indicate a logic error or typo.

+ +

Typically, this bug occurs because the code wants to perform +a membership test in a bit set, but uses the bitwise OR +operator ("|") instead of bitwise AND ("&").

]]>
+
+ + + + + This method contains an unsynchronized lazy initialization of a non-volatile static field. +Because the compiler or processor may reorder instructions, +threads are not guaranteed to see a completely initialized object, +if the method can be called by multiple threads. +You can make the field volatile to correct the problem. +For more information, see the +Java Memory Model web site. +

]]>
+
+ + + + + This method contains an unsynchronized lazy initialization of a static field. +After the field is set, the object stored into that location is further accessed. +The setting of the field is visible to other threads as soon as it is set. If the +futher accesses in the method that set the field serve to initialize the object, then +you have a very serious multithreading bug, unless something else prevents +any other thread from accessing the stored object until it is fully initialized. +

]]>
+
+ + + + + This method performs synchronization on an implementation of +java.util.concurrent.locks.Lock. You should use +the lock() and unlock() methods instead. +

]]>
+
+ + + + + This private method is never called. Although it is +possible that the method will be invoked through reflection, +it is more likely that the method is never used, and should be +removed. +

]]>
+
+ + + + + This anonymous class defined a method that is not directly invoked and does not override +a method in a superclass. Since methods in other classes cannot directly invoke methods +declared in an anonymous class, it seems that this method is uncallable. The method +might simply be dead code, but it is also possible that the method is intended to +override a method declared in a superclass, and due to an typo or other error the method does not, +in fact, override the method it is intended to. +

]]>
+
+ + + + + The method creates a database resource (such as a database connection +or row set), does not assign it to any +fields, pass it to other methods, or return it, and does not appear to close +the object on all paths out of the method.  Failure to +close database resources on all paths out of a method may +result in poor performance, and could cause the application to +have problems communicating with the database. +

]]>
+
+ + + + + The method creates a database resource (such as a database connection +or row set), does not assign it to any +fields, pass it to other methods, or return it, and does not appear to close +the object on all exception paths out of the method.  Failure to +close database resources on all paths out of a method may +result in poor performance, and could cause the application to +have problems communicating with the database.

]]>
+
+ + + + + The method seems to be building a String using concatenation in a loop. +In each iteration, the String is converted to a StringBuffer/StringBuilder, + appended to, and converted back to a String. + This can lead to a cost quadratic in the number of iterations, + as the growing string is recopied in each iteration.

+ +

Better performance can be obtained by using +a StringBuffer (or StringBuilder in Java 1.5) explicitly.

+ +

For example:

+
+  // This is bad
+  String s = "";
+  for (int i = 0; i < field.length; ++i) {
+    s = s + field[i];
+  }
+
+  // This is better
+  StringBuffer buf = new StringBuffer();
+  for (int i = 0; i < field.length; ++i) {
+    buf.append(field[i]);
+  }
+  String s = buf.toString();
+
]]>
+
+ + + + + This method uses the toArray() method of a collection derived class, and passes +in a zero-length prototype array argument. It is more efficient to use +myCollection.toArray(new Foo[myCollection.size()]) +If the array passed in is big enough to store all of the +elements of the collection, then it is populated and returned +directly. This avoids the need to create a second array +(by reflection) to return as the result.

]]>
+
+ + + + + A JUnit assertion is performed in a run method. Failed JUnit assertions +just result in exceptions being thrown. +Thus, if this exception occurs in a thread other than the thread that invokes +the test method, the exception will terminate the thread but not result +in the test failing. +

]]>
+
+ + + + + Class is a JUnit TestCase and implements the setUp method. The setUp method should call +super.setUp(), but doesn't.

]]>
+
+ + + + + Class is a JUnit TestCase and implements the tearDown method. The tearDown method should call +super.tearDown(), but doesn't.

]]>
+
+ + + + + Class is a JUnit TestCase and implements the suite() method. + The suite method should be declared as being static, but isn't.

]]>
+
+ + + + + Class is a JUnit TestCase and defines a suite() method. +However, the suite method needs to be declared as either +
public static junit.framework.Test suite()
+or +
public static junit.framework.TestSuite suite()
+

]]>
+
+ + + + + Class is a JUnit TestCase but has not implemented any test methods

]]>
+
+ + + + + This method overrides a method found in a parent class, where that class is an Adapter that implements +a listener defined in the java.awt.event or javax.swing.event package. As a result, this method will not +get called when the event occurs.

]]>
+
+ + + + + A call to getXXX or updateXXX methods of a result set was made where the +field index is 0. As ResultSet fields start at index 1, this is always a mistake.

]]>
+
+ + + + + A call to a setXXX method of a prepared statement was made where the +parameter index is 0. As parameter indexes start at index 1, this is always a mistake.

]]>
+
+ + + + + Type check performed using the instanceof operator where it can be statically determined whether the object +is of the type requested.

]]>
+
+ + + + + +This method invokes the .equals(Object o) to compare an array and a reference that doesn't seem +to be an array. If things being compared are of different types, they are guaranteed to be unequal +and the comparison is almost certainly an error. Even if they are both arrays, the equals method +on arrays only determines of the two arrays are the same object. +To compare the +contents of the arrays, use java.util.Arrays.equals(Object[], Object[]). +

]]>
+
+ + + + + +This method invokes the .equals(Object o) method on an array. Since arrays do not override the equals +method of Object, calling equals on an array is the same as comparing their addresses. To compare the +contents of the arrays, use java.util.Arrays.equals(Object[], Object[]). +

]]>
+
+ + + + + +This method invokes the Thread.currentThread() call, just to call the interrupted() method. As interrupted() is a +static method, is more simple and clear to use Thread.interrupted(). +

]]>
+
+ + + + + +This method invokes the Thread.interrupted() method on a Thread object that appears to be a Thread object that is +not the current thread. As the interrupted() method is static, the interrupted method will be called on a different +object than the one the author intended. +

]]>
+
+ + + + + +The initial value of this parameter is ignored, and the parameter +is overwritten here. This often indicates a mistaken belief that +the write to the parameter will be conveyed back to +the caller. +

]]>
+
+ + + + + +This instruction assigns a value to a local variable, +but the value is not read or used in any subsequent instruction. +Often, this indicates an error, because the value computed is never +used. +

+

+Note that Sun's javac compiler often generates dead stores for +final local variables. Because FindBugs is a bytecode-based tool, +there is no easy way to eliminate these false positives. +

]]>
+
+ + + + + +This statement assigns to a local variable in a return statement. This assignment +has effect. Please verify that this statement does the right thing. +

]]>
+
+ + + + + +This instruction assigns a class literal to a variable and then never uses it. +The behavior of this differs in Java 1.4 and in Java 5. +In Java 1.4 and earlier, a reference to Foo.class would force the static initializer +for Foo to be executed, if it has not been executed already. +In Java 5 and later, it does not. +

+

See Sun's article on Java SE compatibility +for more details and examples, and suggestions on how to force class initialization in Java 5. +

]]>
+
+ + + + + The code stores null into a local variable, and the stored value is not +read. This store may have been introduced to assist the garbage collector, but +as of Java SE 6.0, this is no longer needed or useful. +

]]>
+
+ + + + + This method defines a local variable with the same name as a field +in this class or a superclass. This may cause the method to +read an uninitialized value from the field, leave the field uninitialized, +or both.

]]>
+
+ + + + + This class defines a field with the same name as a visible +instance field in a superclass. This is confusing, and +may indicate an error if methods update or access one of +the fields when they wanted the other.

]]>
+
+ + + + + This method accesses the value of a Map entry, using a key that was retrieved from +a keySet iterator. It is more efficient to use an iterator on the entrySet of the map, to avoid the +Map.get(key) lookup.

]]>
+
+ + + + + This class allocates an object that is based on a class that only supplies static methods. This object +does not need to be created, just access the static methods directly using the class name as a qualifier.

]]>
+
+ + + + + + This method uses a try-catch block that catches Exception objects, but Exception is not + thrown within the try block, and RuntimeException is not explicitly caught. It is a common bug pattern to + say try { ... } catch (Exception e) { something } as a shorthand for catching a number of types of exception + each of whose catch blocks is identical, but this construct also accidentally catches RuntimeException as well, + masking potential bugs. +

]]>
+
+ + + + + + This code checks to see if a floating point value is equal to the special + Not A Number value (e.g., if (x == Double.NaN)). However, + because of the special semantics of NaN, no value + is equal to Nan, including NaN. Thus, + x == Double.NaN always evaluates to false. + + To check to see if a value contained in x + is the special Not A Number value, use + Double.isNaN(x) (or Float.isNaN(x) if + x is floating point precision). +

]]>
+
+ + + + + + This operation compares two floating point values for equality. + Because floating point calculations may involve rounding, + calculated float and double values may not be accurate. + For values that must be precise, such as monetary values, + consider using a fixed-precision type such as BigDecimal. + For values that need not be precise, consider comparing for equality + within some range, for example: + if ( Math.abs(x - y) < .0000001 ). + See the Java Language Specification, section 4.2.4. +

]]>
+
+ + + + + This method uses a static method from java.lang.Math on a constant value. This method's +result in this case, can be determined statically, and is faster and sometimes more accurate to +just use the constant. Methods detected are: +

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Method Parameter
abs -any-
acos 0.0 or 1.0
asin 0.0 or 1.0
atan 0.0 or 1.0
atan2 0.0
cbrt 0.0 or 1.0
ceil -any-
cos 0.0
cosh 0.0
exp 0.0 or 1.0
expm1 0.0
floor -any-
log 0.0 or 1.0
log10 0.0 or 1.0
rint -any-
round -any-
sin 0.0
sinh 0.0
sqrt 0.0 or 1.0
tan 0.0
tanh 0.0
toDegrees 0.0 or 1.0
toRadians 0.0
]]>
+
+ + + + + + This class declares that it implements an interface that is also implemented by a superclass. + This is redundant because once a superclass implements an interface, all subclasses by default also + implement this interface. It may point out that the inheritance hierarchy has changed since + this class was created, and consideration should be given to the ownership of + the interface's implementation. +

]]>
+
+ + + + + + This class extends from a Struts Action class, and uses an instance member variable. Since only + one instance of a struts Action class is created by the Struts framework, and used in a + multithreaded way, this paradigm is highly discouraged and most likely problematic. Consider + only using method local variables. Only instance fields that are written outside of a monitor + are reported. +

]]>
+
+ + + + + + This class extends from a Servlet class, and uses an instance member variable. Since only + one instance of a Servlet class is created by the J2EE framework, and used in a + multithreaded way, this paradigm is highly discouraged and most likely problematic. Consider + only using method local variables. +

]]>
+
+ + + + + + This class uses synchronization along with wait(), notify() or notifyAll() on itself (the this + reference). Client classes that use this class, may, in addition, use an instance of this class + as a synchronizing object. Because two classes are using the same object for synchronization, + Multithread correctness is suspect. You should not synchronize nor call semaphore methods on + a public reference. Consider using a internal private member variable to control synchronization. +

]]>
+
+ + + + + +This code performs integer multiply and then converts the result to a long, +as in: + +
 
+	long convertDaysToMilliseconds(int days) { return 1000*3600*24*days; } 
+
+If the multiplication is done using long arithmetic, you can avoid +the possibility that the result will overflow. For example, you +could fix the above code to: + +
 
+	long convertDaysToMilliseconds(int days) { return 1000L*3600*24*days; } 
+
+or + +
 
+	static final long MILLISECONDS_PER_DAY = 24L*3600*1000;
+	long convertDaysToMilliseconds(int days) { return days * MILLISECONDS_PER_DAY; } 
+
+

]]>
+
+ + + + + +This code converts an int value to a float precision +floating point number and then +passing the result to the Math.round() function, which returns the int/long closest +to the argument. This operation should always be a no-op, +since the converting an integer to a float should give a number with no fractional part. +It is likely that the operation that generated the value to be passed +to Math.round was intended to be performed using +floating point arithmetic. +

]]>
+
+ + + + + +This code converts an int value to a double precision +floating point number and then +passing the result to the Math.ceil() function, which rounds a double to +the next higher integer value. This operation should always be a no-op, +since the converting an integer to a double should give a number with no fractional part. +It is likely that the operation that generated the value to be passed +to Math.ceil was intended to be performed using double precision +floating point arithmetic. +

]]>
+
+ + + + + +This code casts the result of an integer division operation to double or +float. +Doing division on integers truncates the result +to the integer value closest to zero. The fact that the result +was cast to double suggests that this precision should have been retained. +What was probably meant was to cast one or both of the operands to +double before performing the division. Here is an example: +

+
+
+int x = 2;
+int y = 5;
+// Wrong: yields result 0.0
+double value1 =  x / y;
+
+// Right: yields result 0.4
+double value2 =  x / (double) y;
+
+
]]>
+
+ + + + + +This code seems to be storing a non-serializable object into an HttpSession. +If this session is passivated or migrated, an error will result. +

]]>
+
+ + + + + +This code seems to be passing a non-serializable object to the ObjectOutput.writeObject method. +If the object is, indeed, non-serializable, an error will result. +

]]>
+
+ + + + + +The format string specifies a relative index to request that the argument for the previous format specifier +be reused. However, there is no previous argument. +For example, +

+

formatter.format("%<s %s", "a", "b") +

+

would throw a MissingFormatArgumentException when executed. +

]]>
+
+ + + + + +One of the arguments is uncompatible with the corresponding format string specifier. +As a result, this will generate a runtime exception when executed. +For example, String.format("%d", "1") will generate an exception, since +the String "1" is incompatible with the format specifier %d. +

]]>
+
+ + + + + +An argument not of type Boolean is being formatted with a %b format specifier. This won't throw an +exception; instead, it will print true for any nonnull value, and false for null. +This feature of format strings is strange, and may not be what you intended. +

]]>
+
+ + + + + +One of the arguments being formatted with a format string is an array. This will be formatted +using a fairly useless format, such as [I@304282, which doesn't actually show the contents +of the array. +Consider wrapping the array using Arrays.asList(...) before handling it off to a formatted. +

]]>
+
+ + + + + + +A format-string method with a variable number of arguments is called, +but the number of arguments passed does not match with the number of +% placeholders in the format string. This is probably not what the +author intended. +

]]>
+
+ + + + + +A format-string method with a variable number of arguments is called, +but more arguments are passed than are actually used by the format string. +This won't cause a runtime exception, but the code may be silently omitting +information that was intended to be included in the formatted string. +

]]>
+
+ + + + + +The format string is syntactically invalid, +and a runtime exception will occur when +this statement is executed. +

]]>
+
+ + + + + +Not enough arguments are passed to satisfy a placeholder in the format string. +A runtime exception will occur when +this statement is executed. +

]]>
+
+ + + + + +The format string placeholder is incompatible with the corresponding +argument. For example, + + System.out.println("%d\n", "hello"); + +

The %d placeholder requires a numeric argument, but a string value is +passed instead. +A runtime exception will occur when +this statement is executed. +

]]>
+
+ + + + + + +This code passes a primitive array to a function that takes a variable number of object arguments. +This creates an array of length one to hold the primitive array and passes it to the function. +

]]>
+
+ + + + + +The equals(Object o) method shouldn't make any assumptions +about the type of o. It should simply return +false if o is not the same type as this. +

]]>
+
+ + + + + +This code casts a Collection to an abstract collection +(such as List, Set, or Map). +Ensure that you are guaranteed that the object is of the type +you are casting to. If all you need is to be able +to iterate through a collection, you don't need to cast it to a Set or List. +

]]>
+
+ + + + + +This cast will always throw a ClassCastException. +

]]>
+
+ + + + + +This instanceof test will always return false, since the value being checked is guaranteed to be null. +Although this is safe, make sure it isn't +an indication of some misunderstanding or some other logic error. +

]]>
+
+ + + + + +This instanceof test will always return false. Although this is safe, make sure it isn't +an indication of some misunderstanding or some other logic error. +

]]>
+
+ + + + + +This instanceof test will always return true (unless the value being tested is null). +Although this is safe, make sure it isn't +an indication of some misunderstanding or some other logic error. +If you really want to test the value for being null, perhaps it would be clearer to do +better to do a null test rather than an instanceof test. +

]]>
+
+ + + + + +This cast is unchecked, and not all instances of the type casted from can be cast to +the type it is being cast to. Ensure that your program logic ensures that this +cast will not fail. +

]]>
+
+ + + + + +This code casts an abstract collection (such as a Collection, List, or Set) +to a specific concrete implementation (such as an ArrayList or HashSet). +This might not be correct, and it may make your code fragile, since +it makes it harder to switch to other concrete implementations at a future +point. Unless you have a particular reason to do so, just use the abstract +collection class. +

]]>
+
+ + + + + +A String function is being invoked and "." is being passed +to a parameter that takes a regular expression as an argument. Is this what you intended? +For example +s.replaceAll(".", "/") will return a String in which every +character has been replaced by a / character. +

]]>
+
+ + + + + +The code here uses a regular expression that is invalid according to the syntax +for regular expressions. This statement will throw a PatternSyntaxException when +executed. +

]]>
+
+ + + + + +The code here uses File.separator +where a regular expression is required. This will fail on Windows +platforms, where the File.separator is a backslash, which is interpreted in a +regular expression as an escape character. Amoung other options, you can just use +File.separatorChar=='\\' & "\\\\" : File.separator instead of +File.separator + +

]]>
+
+ + + + + +The code performs an increment operation (e.g., i++) and then +immediately overwrites it. For example, i = i++ immediately +overwrites the incremented value with the original value. +

]]>
+
+ + + + + +The code performs an unsigned right shift, whose result is then +cast to a short or byte, which discards the upper bits of the result. +Since the upper bits are discarded, there may be no difference between +a signed and unsigned right shift (depending upon the size of the shift). +

]]>
+
+ + + + + +The code performs an integer shift by a constant amount outside +the range 0..31. +The effect of this is to use the lower 5 bits of the integer +value to decide how much to shift by. This probably isn't want was expected, +and it at least confusing. +

]]>
+
+ + + + + +The code multiplies the result of an integer remaining by an integer constant. +Be sure you don't have your operator precedence confused. For example +i % 60 * 1000 is (i % 60) * 1000, not i % (60 * 1000). +

]]>
+
+ + + + + +The code invokes hashCode on an array. Calling hashCode on +an array returns the same value as System.identityHashCode, and ingores +the contents and length of the array. If you need a hashCode that +depends on the contents of an array a, +use java.util.Arrays.hashCode(a). + +

]]>
+
+ + + + + +The code invokes toString on an array, which will generate a fairly useless result +such as [C@16f0472. Consider using Arrays.toString to convert the array into a readable +String that gives the contents of the array. See Programming Puzzlers, chapter 3, puzzle 12. +

]]>
+
+ + + + + +The code invokes toString on an (anonymous) array. Calling toString on an array generates a fairly useless result +such as [C@16f0472. Consider using Arrays.toString to convert the array into a readable +String that gives the contents of the array. See Programming Puzzlers, chapter 3, puzzle 12. +

]]>
+
+ + + + + The code computes the average of two integers using either division or signed right shift, +and then uses the result as the index of an array. +If the values being averaged are very large, this can overflow (resulting in the computation +of a negative average). Assuming that the result is intended to be nonnegative, you +can use an unsigned right shift instead. In other words, rather that using (low+high)/2, +use (low+high) >>> 1 +

+

This bug exists in many earlier implementations of binary search and merge sort. +Martin Buchholz found and fixed it +in the JDK libraries, and Joshua Bloch +widely +publicized the bug pattern. +

]]>
+
+ + + + + +The code uses x % 2 == 1 to check to see if a value is odd, but this won't work +for negative numbers (e.g., (-5) % 2 == -1). If this code is intending to check +for oddness, consider using x & 1 == 1, or x % 2 != 0. +

]]>
+
+ + + + + This code constructs a File object using a hard coded to an absolute pathname +(e.g., new File("/home/dannyc/workspace/j2ee/src/share/com/sun/enterprise/deployment"); +

]]>
+
+ + + + + +This code passes a constant month +value outside the expected range of 0..11 to a method. +

]]>
+
+ + + + + +This code invokes substring(0) on a String, which returns the original value. +

]]>
+
+ + + + + +The hasNext() method invokes the next() method. This is almost certainly wrong, +since the hasNext() method is not supposed to change the state of the iterator, +and the next method is supposed to change the state of the iterator. +

]]>
+
+ + + + + + This method calls Thread.sleep() with a lock held. This may result + in very poor performance and scalability, or a deadlock, since other threads may + be waiting to acquire the lock. It is a much better idea to call + wait() on the lock, which releases the lock and allows other threads + to run. +

]]>
+
+ + + + + + This method uses the same code to implement two branches of a conditional branch. + Check to ensure that this isn't a coding mistake. +

]]>
+
+ + + + + + This method uses the same code to implement two clauses of a switch statement. + This could be a case of duplicate code, but it might also indicate + a coding mistake. +

]]>
+
+ + + + + + This method allocates a specific implementation of an xml interface. It is preferable to use + the supplied factory classes to create these objects so that the implementation can be + changed at runtime. See +

+
    +
  • javax.xml.parsers.DocumentBuilderFactory
  • +
  • javax.xml.parsers.SAXParserFactory
  • +
  • javax.xml.transform.TransformerFactory
  • +
  • org.w3c.dom.Document.createXXXX
  • +
+

for details.

]]>
+
+ + + + + + This class is declared to be final, but declares fields to be protected. Since the class + is final, it can not be derived from, and the use of protected is confusing. The access + modifier for the field should be changed to private or public to represent the true + use for the field. +

]]>
+
+ + + + + + This method assigns a literal boolean value (true or false) to a boolean variable inside + an if or while expression. Most probably this was supposed to be a boolean comparison using + ==, not an assignment using =. +

]]>
+
+ + + + + This call to a generic collection method passes an argument + while compile type Object where a specific type from + the generic type parameters is expected. + Thus, neither the standard Java type system nor static analysis + can provide useful information on whether the + object being passed as a parameter is of an appropriate type. +

]]>
+
+ + + + + This call to a generic collection method contains an argument + with an incompatible class from that of the collection's parameter + (i.e., the type of the argument is neither a supertype nor a subtype + of the corresponding generic type argument). + Therefore, it is unlikely that the collection contains any objects + that are equal to the method argument used here. + Most likely, the wrong value is being passed to the method.

+

In general, instances of two unrelated classes are not equal. + For example, if the Foo and Bar classes + are not related by subtyping, then an instance of Foo + should not be equal to an instance of Bar. + Among other issues, doing so will likely result in an equals method + that is not symmetrical. For example, if you define the Foo class + so that a Foo can be equal to a String, + your equals method isn't symmetrical since a String can only be equal + to a String. +

+

In rare cases, people do define nonsymmetrical equals methods and still manage to make + their code work. Although none of the APIs document or guarantee it, it is typically + the case that if you check if a Collection<String> contains + a Foo, the equals method of argument (e.g., the equals method of the + Foo class) used to perform the equality checks. +

]]>
+
+ + + + + This call to a generic collection's method would only make sense if a collection contained +itself (e.g., if s.contains(s) were true). This is unlikely to be true and would cause +problems if it were true (such as the computation of the hash code resulting in infinite recursion). +It is likely that the wrong value is being passed as a parameter. +

]]>
+
+ + + + + This call doesn't make sense. For any collection c, calling c.containsAll(c) should +always be true, and c.retainAll(c) should have no effect. +

]]>
+
+ + + + + If you want to remove all elements from a collection c, use c.clear, +not c.removeAll(c). +

]]>
+
+ + + + + Even though the JavaDoc does not contain a hint about it, Calendars are inherently unsafe for multihtreaded use. +Sharing a single instance across thread boundaries without proper synchronization will result in erratic behavior of the +application. Under 1.4 problems seem to surface less often than under Java 5 where you will probably see +random ArrayIndexOutOfBoundsExceptions or IndexOutOfBoundsExceptions in sun.util.calendar.BaseCalendar.getCalendarDateFromFixedDate().

+

You may also experience serialization problems.

+

Using an instance field is recommended.

+

For more information on this see Sun Bug #6231579 +and Sun Bug #6178997.

]]>
+
+ + + + + Even though the JavaDoc does not contain a hint about it, Calendars are inherently unsafe for multihtreaded use. +The detector has found a call to an instance of Calendar that has been obtained via a static +field. This looks suspicous.

+

For more information on this see Sun Bug #6231579 +and Sun Bug #6178997.

]]>
+
+ + + + + As the JavaDoc states, DateFormats are inherently unsafe for multithreaded use. +Sharing a single instance across thread boundaries without proper synchronization will result in erratic behavior of the +application.

+

You may also experience serialization problems.

+

Using an instance field is recommended.

+

For more information on this see Sun Bug #6231579 +and Sun Bug #6178997.

]]>
+
+ + + + + As the JavaDoc states, DateFormats are inherently unsafe for multithreaded use. +The detector has found a call to an instance of DateFormat that has been obtained via a static +field. This looks suspicous.

+

For more information on this see Sun Bug #6231579 +and Sun Bug #6178997.

]]>
+
+ + + + + + + A value specified as carrying a type qualifier annotation is + consumed in a location or locations requiring that the value not + carry that annotation. +

+ +

+ More precisely, a value annotated with a type qualifier specifying when=ALWAYS + is guaranteed to reach a use or uses where the same type qualifier specifies when=NEVER. +

+ +

+ For example, say that @NonNegative is a nickname for + the type qualifier annotation @Negative(when=When.NEVER). + The following code will generate this warning because + the return statement requires a @NonNegative value, + but receives one that is marked as @Negative. +

+
+
+public @NonNegative Integer example(@Negative Integer value) {
+    return value;
+}
+
+
]]>
+
+ + + + + + + A value specified as not carrying a type qualifier annotation is guaranteed + to be consumed in a location or locations requiring that the value does + carry that annotation. +

+ +

+ More precisely, a value annotated with a type qualifier specifying when=NEVER + is guaranteed to reach a use or uses where the same type qualifier specifies when=ALWAYS. +

+ +

+ TODO: example +

]]>
+
+ + + + + + + A value that is annotated as possibility not being an instance of + the values denoted by the type qualifier, and the value is guaranteed to be used + in a way that requires values denoted by that type qualifier. +

]]>
+
+ + + + + + + A value that is annotated as possibility being an instance of + the values denoted by the type qualifier, and the value is guaranteed to be used + in a way that prohibits values denoted by that type qualifier. +

]]>
+
+ + + + + + A value is used in a way that requires it to be never be a value denoted by a type qualifier, but + there is an explicit annotation stating that it is not known where the value is prohibited from having that type qualifier. + Either the usage or the annotation is incorrect. +

]]>
+
+ + + + + + A value is used in a way that requires it to be always be a value denoted by a type qualifier, but + there is an explicit annotation stating that it is not known where the value is required to have that type qualifier. + Either the usage or the annotation is incorrect. +

]]>
+
+ + + + + + This code opens a file in append mode and then wraps the result in an object output stream. + This won't allow you to append to an existing object output stream stored in a file. If you want to be + able to append to an object output stream, you need to keep the object output stream open. +

+

The only situation in which opening a file in append mode and the writing an object output stream + could work is if on reading the file you plan to open it in random access mode and seek to the byte offset + where the append started. +

+ +

+ TODO: example. +

]]>
+
+ + + + + + This instance method synchronizes on this.getClass(). If this class is subclassed, + subclasses will synchronize on the class object for the subclass, which isn't likely what was intended. + For example, consider this code from java.awt.Label: +
+     private static final String base = "label";
+     private static int nameCounter = 0;
+     String constructComponentName() {
+        synchronized (getClass()) {
+            return base + nameCounter++;
+        }
+     }
+     

+

Subclasses of Label won't synchronize on the same subclass, giving rise to a datarace. + Instead, this code should be synchronizing on Label.class +

+     private static final String base = "label";
+     private static int nameCounter = 0;
+     String constructComponentName() {
+        synchronized (Label.class) {
+            return base + nameCounter++;
+        }
+     }
+     

+

Bug pattern contributed by Jason Mehrens

]]>
+
+ + + + + + + This method contains a switch statement where one case branch will fall + through to the next case. Usually you need to end this case with a break or return. +

]]>
+
+ + + + + + + This method contains a switch statement where default case is missing. + Usually you need to provide a default case. +

]]>
+
+ + + + + + + A value stored in the previous switch case is overwritten here due + to a switch fall through. It is likely that you forgot to put a + break or return at the end of the previous case. +

]]>
+
+ + + + + + + A value stored in the previous switch case is ignored here due + to a switch fall through to a place where an exception is thrown. + It is likely that you forgot to put a break or return at the end of the previous case. +

]]>
+
+
\ No newline at end of file diff --git a/plugins/sonar-findbugs-plugin/src/test/java/org/sonar/plugins/findbugs/FindbugsAntConverterTest.java b/plugins/sonar-findbugs-plugin/src/test/java/org/sonar/plugins/findbugs/FindbugsAntConverterTest.java new file mode 100644 index 00000000000..e47a02c72a2 --- /dev/null +++ b/plugins/sonar-findbugs-plugin/src/test/java/org/sonar/plugins/findbugs/FindbugsAntConverterTest.java @@ -0,0 +1,39 @@ +/* + * Sonar, open source software quality management tool. + * Copyright (C) 2009 SonarSource SA + * mailto:contact AT sonarsource DOT com + * + * Sonar is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * Sonar is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with Sonar; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 + */ +package org.sonar.plugins.findbugs; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; +import org.junit.Test; + +public class FindbugsAntConverterTest { + + @Test + public void convertToJavaRegexFormat() { + assertRegex("foo", "~foo"); + assertRegex("**/*Test.java", "~(.*\\.)?[^\\\\^\\s]*Test"); + } + + private void assertRegex(String antRegex, String javaRegex) { + assertThat(FindbugsAntConverter.antToJavaRegexpConvertor(antRegex), is(javaRegex)); + } + + +} diff --git a/plugins/sonar-findbugs-plugin/src/test/java/org/sonar/plugins/findbugs/FindbugsMavenPluginHandlerTest.java b/plugins/sonar-findbugs-plugin/src/test/java/org/sonar/plugins/findbugs/FindbugsMavenPluginHandlerTest.java new file mode 100644 index 00000000000..9b443c0c2ec --- /dev/null +++ b/plugins/sonar-findbugs-plugin/src/test/java/org/sonar/plugins/findbugs/FindbugsMavenPluginHandlerTest.java @@ -0,0 +1,189 @@ +/* + * Sonar, open source software quality management tool. + * Copyright (C) 2009 SonarSource SA + * mailto:contact AT sonarsource DOT com + * + * Sonar is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * Sonar is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with Sonar; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 + */ +package org.sonar.plugins.findbugs; + +import org.apache.commons.configuration.Configuration; +import org.apache.maven.project.MavenProject; +import static org.hamcrest.CoreMatchers.is; +import org.hamcrest.core.Is; +import static org.hamcrest.text.StringEndsWith.endsWith; +import static org.junit.Assert.assertThat; +import org.junit.Before; +import org.junit.Test; +import static org.mockito.Matchers.anyObject; +import static org.mockito.Matchers.anyString; +import static org.mockito.Matchers.argThat; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.*; +import org.sonar.api.CoreProperties; +import org.sonar.api.batch.maven.MavenPlugin; +import org.sonar.api.profiles.RulesProfile; +import org.sonar.api.resources.Project; +import org.sonar.api.resources.ProjectFileSystem; +import org.sonar.api.test.SimpleProjectFileSystem; +import org.sonar.api.utils.SonarException; + +import java.io.File; +import java.io.IOException; +import java.net.URISyntaxException; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class FindbugsMavenPluginHandlerTest { + private static final String TARGET_TMP_TESTS = "target/tmp-tests"; + + private Project project; + private ProjectFileSystem fs; + private File fakeSonarConfig; + private FindbugsRulesRepository repo; + private MavenPlugin plugin; + private FindbugsMavenPluginHandler handler; + + @Before + public void setup() { + project = mock(Project.class); + fs = mock(ProjectFileSystem.class); + fakeSonarConfig = mock(File.class); + repo = mock(FindbugsRulesRepository.class); + plugin = mock(MavenPlugin.class); + handler = createMavenPluginHandler(); + } + + @Test + public void doOverrideConfig() throws Exception { + setupConfig(); + + handler.configureFilters(project, plugin); + verify(plugin).setParameter("includeFilterFile", "fakeSonarConfig.xml"); + } + + @Test + public void doReuseExistingRulesConfig() throws Exception { + setupConfig(); + // See sonar 583 + when(project.getReuseExistingRulesConfig()).thenReturn(true); + when(plugin.getParameter("excludeFilterFile")).thenReturn("existingConfig.xml"); + + handler.configureFilters(project, plugin); + verify(plugin, never()).setParameter(eq("includeFilterFile"), anyString()); + + setupConfig(); + when(project.getReuseExistingRulesConfig()).thenReturn(true); + when(plugin.getParameter("includeFilterFile")).thenReturn("existingConfig.xml"); + + handler.configureFilters(project, plugin); + verify(plugin, never()).setParameter(eq("includeFilterFile"), anyString()); + } + + private void setupConfig() throws IOException { + when(fakeSonarConfig.getCanonicalPath()).thenReturn("fakeSonarConfig.xml"); + when(project.getFileSystem()).thenReturn(fs); + when(fs.writeToWorkingDirectory(anyString(), anyString())).thenReturn(fakeSonarConfig); + } + + @Test + public void shoulConfigurePlugin() throws URISyntaxException, IOException { + + mockProject(CoreProperties.FINDBUGS_EFFORT_DEFAULT_VALUE); + + handler.configure(project, plugin); + + verify(plugin).setParameter("skip", "false"); + verify(plugin).setParameter("xmlOutput", "true"); + verify(plugin).setParameter("threshold", "Low"); + verify(plugin).setParameter("effort", CoreProperties.FINDBUGS_EFFORT_DEFAULT_VALUE, false); + verify(plugin).setParameter(eq("classFilesDirectory"), anyString()); + verify(plugin).setParameter(eq("includeFilterFile"), argThat(endsWith("findbugs-include.xml"))); + assertFindbugsIncludeFileIsSaved(); + } + + @Test(expected = SonarException.class) + public void shoulFailIfNoCompiledClasses() throws URISyntaxException, IOException { + when(project.getFileSystem()).thenReturn(fs); + + handler.configure(project, plugin); + } + + @Test + public void shouldConfigureEffort() throws URISyntaxException, IOException { + FindbugsMavenPluginHandler handler = createMavenPluginHandler(); + mockProject("EffortSetInPom"); + MavenPlugin plugin = mock(MavenPlugin.class); + + handler.configure(project, plugin); + + verify(plugin).setParameter("effort", "EffortSetInPom", false); + } + + @Test + public void shouldConvertAntToJavaRegexp() { + // see SONAR-853 + assertAntPatternEqualsToFindBugsRegExp("?", "~.", "g"); + assertAntPatternEqualsToFindBugsRegExp("*/myClass.JaVa", "~([^\\\\^\\s]*\\.)?myClass", "foo.bar.test.myClass"); + assertAntPatternEqualsToFindBugsRegExp("*/myClass.java", "~([^\\\\^\\s]*\\.)?myClass", "foo.bar.test.myClass"); + assertAntPatternEqualsToFindBugsRegExp("*/myClass2.jav", "~([^\\\\^\\s]*\\.)?myClass2", "foo.bar.test.myClass2"); + assertAntPatternEqualsToFindBugsRegExp("*/myOtherClass", "~([^\\\\^\\s]*\\.)?myOtherClass", "foo.bar.test.myOtherClass"); + assertAntPatternEqualsToFindBugsRegExp("*", "~[^\\\\^\\s]*", "ga.%#123_(*"); + assertAntPatternEqualsToFindBugsRegExp("**", "~.*", "gd.3reqg.3151];9#@!"); + assertAntPatternEqualsToFindBugsRegExp("**/generated/**", "~(.*\\.)?generated\\..*", "!@$Rq/32T$).generated.##TR.e#@!$"); + assertAntPatternEqualsToFindBugsRegExp("**/cl*nt/*", "~(.*\\.)?cl[^\\\\^\\s]*nt\\.[^\\\\^\\s]*", "!#$_.clr31r#!$(nt.!#$QRW)(."); + assertAntPatternEqualsToFindBugsRegExp("**/org/apache/commons/**", "~(.*\\.)?org\\.apache\\.commons\\..*", "org.apache.commons.httpclient.contrib.ssl"); + assertAntPatternEqualsToFindBugsRegExp("*/org/apache/commons/**", "~([^\\\\^\\s]*\\.)?org\\.apache\\.commons\\..*", "org.apache.commons.httpclient.contrib.ssl"); + assertAntPatternEqualsToFindBugsRegExp("org/apache/commons/**", "~org\\.apache\\.commons\\..*", "org.apache.commons.httpclient.contrib.ssl"); + } + + @Test + public void shouldntMatchThoseClassPattern() { + // see SONAR-853 + assertJavaRegexpResult("[^\\\\^\\s]", "fad f.ate 12#)", false); + } + + private void assertAntPatternEqualsToFindBugsRegExp(String antPattern, String regExp, String example) { + assertThat(FindbugsAntConverter.antToJavaRegexpConvertor(antPattern), Is.is(regExp)); + String javaRegexp = regExp.substring(1, regExp.length()); + assertJavaRegexpResult(javaRegexp, example, true); + } + + private void assertJavaRegexpResult(String javaRegexp, String example, boolean expectedResult) { + Pattern pattern = Pattern.compile(javaRegexp); + Matcher matcher = pattern.matcher(example); + assertThat(example + " tested with pattern " + javaRegexp, matcher.matches(), Is.is(expectedResult)); + } + + private void assertFindbugsIncludeFileIsSaved() { + File findbugsIncludeFile = new File(TARGET_TMP_TESTS + "/target/sonar/findbugs-include.xml"); + assertThat(findbugsIncludeFile.exists(), is(true)); + } + + private FindbugsMavenPluginHandler createMavenPluginHandler() { + when(repo.exportConfiguration((RulesProfile) anyObject())).thenReturn(""); + return new FindbugsMavenPluginHandler(new RulesProfile(), repo); + } + + private void mockProject(String effort) throws URISyntaxException, IOException { + when(project.getPom()).thenReturn(new MavenProject()); + when(project.getFileSystem()).thenReturn(new SimpleProjectFileSystem(new File(TARGET_TMP_TESTS))); + + Configuration conf = mock(Configuration.class); + when(project.getConfiguration()).thenReturn(conf); + when(conf.getString(eq(CoreProperties.FINDBUGS_EFFORT_PROPERTY), anyString())).thenReturn(effort); + + } +} diff --git a/plugins/sonar-findbugs-plugin/src/test/java/org/sonar/plugins/findbugs/FindbugsRulesRepositoryTest.java b/plugins/sonar-findbugs-plugin/src/test/java/org/sonar/plugins/findbugs/FindbugsRulesRepositoryTest.java new file mode 100644 index 00000000000..2033a209f43 --- /dev/null +++ b/plugins/sonar-findbugs-plugin/src/test/java/org/sonar/plugins/findbugs/FindbugsRulesRepositoryTest.java @@ -0,0 +1,186 @@ +/* + * Sonar, open source software quality management tool. + * Copyright (C) 2009 SonarSource SA + * mailto:contact AT sonarsource DOT com + * + * Sonar is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * Sonar is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with Sonar; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 + */ +package org.sonar.plugins.findbugs; + +import org.apache.commons.io.IOUtils; +import org.hamcrest.BaseMatcher; +import static org.hamcrest.CoreMatchers.is; +import org.hamcrest.Description; +import static org.junit.Assert.*; +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; +import org.sonar.api.CoreProperties; +import org.sonar.api.profiles.RulesProfile; +import org.sonar.api.resources.Java; +import org.sonar.api.rules.ActiveRule; +import org.sonar.api.rules.Rule; +import org.sonar.api.rules.RulePriority; +import org.xml.sax.SAXException; + +import java.io.IOException; +import java.io.InputStream; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +public class FindbugsRulesRepositoryTest extends FindbugsTests { + + private FindbugsRulesRepository repository; + + @Before + public void setup() { + repository = new FindbugsRulesRepository(new Java()); + } + + @Test + public void rulesAreDefinedWithTheDefaultSonarXmlFormat() { + List rules = repository.getInitialReferential(); + assertTrue(rules.size() > 0); + for (Rule rule : rules) { + assertNotNull(rule.getKey()); + assertNotNull(rule.getDescription()); + assertNotNull(rule.getConfigKey()); + assertNotNull(rule.getName()); + } + } + + @Test + @Ignore + public void shouldProvideProfiles() { + List profiles = repository.getProvidedProfiles(); + assertThat(profiles.size(), is(1)); + + RulesProfile profile1 = profiles.get(0); + assertThat(profile1.getName(), is(RulesProfile.SONAR_WAY_FINDBUGS_NAME)); + assertEquals(profile1.getActiveRules().size(), 344); + } + + @Test + public void shouldAddHeaderToExportedXml() throws IOException, SAXException { + RulesProfile rulesProfile = mock(RulesProfile.class); + when(rulesProfile.getActiveRulesByPlugin(CoreProperties.FINDBUGS_PLUGIN)).thenReturn(Collections.emptyList()); + + assertXmlAreSimilar(repository.exportConfiguration(rulesProfile), "test_header.xml"); + } + + @Test + public void shouldExportConfiguration() throws IOException, SAXException { + List rules = buildRulesFixture(); + List activeRulesExpected = buildActiveRulesFixture(rules); + RulesProfile activeProfile = new RulesProfile(); + activeProfile.setActiveRules(activeRulesExpected); + + assertXmlAreSimilar(repository.exportConfiguration(activeProfile), "test_xml_complete.xml"); + } + + @Test + public void shouldImportPatterns() throws IOException { + InputStream input = getClass().getResourceAsStream("/org/sonar/plugins/findbugs/FindbugsRulesRepositoryTest/shouldImportPatterns.xml"); + List results = repository.importConfiguration(IOUtils.toString(input), buildRulesFixtureImport()); + + assertThat(results.size(), is(2)); + assertThat(results, new ContainsActiveRule("FB1_IMPORT_TEST_1", RulePriority.MAJOR)); + assertThat(results, new ContainsActiveRule("FB2_IMPORT_TEST_4", RulePriority.MAJOR)); + } + + @Test + public void shouldImportCodes() throws IOException { + InputStream input = getClass().getResourceAsStream("/org/sonar/plugins/findbugs/FindbugsRulesRepositoryTest/shouldImportCodes.xml"); + List results = repository.importConfiguration(IOUtils.toString(input), buildRulesFixtureImport()); + + assertThat(results.size(), is(4)); + assertThat(results, new ContainsActiveRule("FB1_IMPORT_TEST_1", RulePriority.MAJOR)); + assertThat(results, new ContainsActiveRule("FB1_IMPORT_TEST_2", RulePriority.MAJOR)); + assertThat(results, new ContainsActiveRule("FB1_IMPORT_TEST_3", RulePriority.MAJOR)); + assertThat(results, new ContainsActiveRule("FB3_IMPORT_TEST_5", RulePriority.MAJOR)); + } + + @Test + public void shouldImportCategories() throws IOException { + InputStream input = getClass().getResourceAsStream("/org/sonar/plugins/findbugs/FindbugsRulesRepositoryTest/shouldImportCategories.xml"); + List results = repository.importConfiguration(IOUtils.toString(input), buildRulesFixtureImport()); + + assertThat(results.size(), is(4)); + assertThat(results, new ContainsActiveRule("FB1_IMPORT_TEST_1", RulePriority.INFO)); + assertThat(results, new ContainsActiveRule("FB1_IMPORT_TEST_2", RulePriority.INFO)); + assertThat(results, new ContainsActiveRule("FB1_IMPORT_TEST_3", RulePriority.INFO)); + assertThat(results, new ContainsActiveRule("FB2_IMPORT_TEST_4", RulePriority.INFO)); + } + + @Test + public void shouldImportConfigurationBugInclude() throws IOException { + InputStream input = getClass().getResourceAsStream("/org/sonar/plugins/findbugs/findbugs-include.xml"); + List results = repository.importConfiguration(IOUtils.toString(input), buildRulesFixtureImport()); + + assertThat(results.size(), is(4)); + assertThat(results, new ContainsActiveRule("FB1_IMPORT_TEST_1", null)); + assertThat(results, new ContainsActiveRule("FB1_IMPORT_TEST_2", null)); + assertThat(results, new ContainsActiveRule("FB1_IMPORT_TEST_3", null)); + assertThat(results, new ContainsActiveRule("FB2_IMPORT_TEST_4", null)); + } + + private static List buildRulesFixtureImport() { + Rule rule1 = new Rule("Correctness - Import test 1 group 1", "FB1_IMPORT_TEST_1", + "FB1_IMPORT_TEST_1", null, CoreProperties.FINDBUGS_PLUGIN, null); + + Rule rule2 = new Rule("Multithreaded correctness - Import test 2 group 1", "FB1_IMPORT_TEST_2", + "FB1_IMPORT_TEST_2", null, CoreProperties.FINDBUGS_PLUGIN, null); + + Rule rule3 = new Rule("Multithreaded correctness - Import test 3 group 1", "FB1_IMPORT_TEST_3", + "FB1_IMPORT_TEST_3", null, CoreProperties.FINDBUGS_PLUGIN, null); + + Rule rule4 = new Rule("Multithreaded correctness - Import test 4 group 2", "FB2_IMPORT_TEST_4", + "FB2_IMPORT_TEST_4", null, CoreProperties.FINDBUGS_PLUGIN, null); + + Rule rule5 = new Rule("Style - Import test 5 group 3", "FB3_IMPORT_TEST_5", + "FB3_IMPORT_TEST_5", null, CoreProperties.FINDBUGS_PLUGIN, null); + + return Arrays.asList(rule1, rule2, rule3, rule4, rule5); + } +} + +class ContainsActiveRule extends BaseMatcher> { + private String key; + private RulePriority priority; + + ContainsActiveRule(String key, RulePriority priority) { + this.key = key; + this.priority = priority; + } + + public boolean matches(Object o) { + List rules = (List) o; + for (ActiveRule rule : rules) { + if (rule.getRule().getKey().equals(key)) { + if (priority == null) { + return true; + } + return rule.getPriority().equals(priority); + } + } + return false; + } + + public void describeTo(Description description) { + } +} diff --git a/plugins/sonar-findbugs-plugin/src/test/java/org/sonar/plugins/findbugs/FindbugsSensorTest.java b/plugins/sonar-findbugs-plugin/src/test/java/org/sonar/plugins/findbugs/FindbugsSensorTest.java new file mode 100644 index 00000000000..feed2b855a9 --- /dev/null +++ b/plugins/sonar-findbugs-plugin/src/test/java/org/sonar/plugins/findbugs/FindbugsSensorTest.java @@ -0,0 +1,137 @@ +/* + * Sonar, open source software quality management tool. + * Copyright (C) 2009 SonarSource SA + * mailto:contact AT sonarsource DOT com + * + * Sonar is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * Sonar is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with Sonar; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 + */ +package org.sonar.plugins.findbugs; + +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.nullValue; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.argThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.io.File; + +import org.apache.commons.configuration.Configuration; +import org.apache.maven.project.MavenProject; +import org.junit.Test; +import org.sonar.api.CoreProperties; +import org.sonar.api.batch.SensorContext; +import org.sonar.api.resources.DefaultProjectFileSystem; +import org.sonar.api.resources.JavaFile; +import org.sonar.api.resources.Project; +import org.sonar.api.resources.Resource; +import org.sonar.api.rules.Violation; +import org.sonar.api.test.IsViolation; + +public class FindbugsSensorTest extends FindbugsTests { + + @Test + public void shouldExecuteWhenSomeRulesAreActive() throws Exception { + FindbugsSensor sensor = new FindbugsSensor(createRulesProfileWithActiveRules(), createRulesManager(), null); + Project project = createProject(); + assertTrue(sensor.shouldExecuteOnProject(project)); + } + + @Test + public void shouldNotExecuteWhenNoRulesAreActive() throws Exception { + FindbugsSensor analyser = new FindbugsSensor(createRulesProfileWithoutActiveRules(), createRulesManager(), null); + Project pom = createProject(); + assertFalse(analyser.shouldExecuteOnProject(pom)); + } + + @Test + public void testGetMavenPluginHandlerWhenFindbugsReportPathExists() throws Exception { + FindbugsSensor analyser = new FindbugsSensor(createRulesProfileWithoutActiveRules(), createRulesManager(), + mock(FindbugsMavenPluginHandler.class)); + Project pom = createProject(); + Configuration conf = mock(Configuration.class); + when(conf.getString(CoreProperties.FINDBUGS_REPORT_PATH)).thenReturn("pathToFindbugsReport"); + when(pom.getConfiguration()).thenReturn(conf); + assertThat(analyser.getMavenPluginHandler(pom), is(nullValue())); + } + + @Test + public void testGetFindbugsReport() { + FindbugsSensor analyser = new FindbugsSensor(createRulesProfileWithActiveRules(), createRulesManager(), + null); + Project pom = createProject(); + Configuration conf = mock(Configuration.class); + when(pom.getConfiguration()).thenReturn(conf); + assertThat(analyser.getFindbugsReportFile(pom).getName(), is("findbugsXml.xml")); + + when(conf.getString(CoreProperties.FINDBUGS_REPORT_PATH)).thenReturn("myFindbugs.xml"); + assertThat(analyser.getFindbugsReportFile(pom).getName(), is("myFindbugs.xml")); + } + + @Test + public void shouldNotExecuteOnEar() { + Project project = createProject(); + when(project.getPom().getPackaging()).thenReturn("ear"); + FindbugsSensor analyser = new FindbugsSensor(createRulesProfileWithActiveRules(), createRulesManager(), null); + assertFalse(analyser.shouldExecuteOnProject(project)); + } + + @Test + public void testAnalyse() throws Exception { + + SensorContext context = mock(SensorContext.class); + Project project = createProject(); + Configuration conf = mock(Configuration.class); + File xmlFile = new File(getClass().getResource("/org/sonar/plugins/findbugs/findbugsXml.xml").toURI()); + when(conf.getString(CoreProperties.FINDBUGS_REPORT_PATH)).thenReturn(xmlFile.getAbsolutePath()); + when(project.getConfiguration()).thenReturn(conf); + when(context.getResource(any(Resource.class))).thenReturn(new JavaFile("org.sonar.MyClass")); + + FindbugsSensor analyser = new FindbugsSensor(createRulesProfileWithoutActiveRules(), createRulesManager(), + null); + analyser.analyse(project, context); + + verify(context, times(3)).saveViolation(any(Violation.class)); + + Violation wanted = new Violation(null, new JavaFile("org.sonar.commons.ZipUtils")) + .setMessage("Empty zip file entry created in org.sonar.commons.ZipUtils._zip(String, File, ZipOutputStream)") + .setLineId(107); + + verify(context).saveViolation(argThat(new IsViolation(wanted))); + + wanted = new Violation(null, new JavaFile("org.sonar.commons.resources.MeasuresDao")) + .setMessage("The class org.sonar.commons.resources.MeasuresDao$1 could be refactored into a named _static_ inner class") + .setLineId(56); + + verify(context).saveViolation(argThat(new IsViolation(wanted))); + } + + private Project createProject() { + DefaultProjectFileSystem fileSystem = mock(DefaultProjectFileSystem.class); + when(fileSystem.hasJavaSourceFiles()).thenReturn(Boolean.TRUE); + + MavenProject mavenProject = mock(MavenProject.class); + Project project = mock(Project.class); + when(project.getFileSystem()).thenReturn(fileSystem); + when(project.getPom()).thenReturn(mavenProject); + return project; + } + +} diff --git a/plugins/sonar-findbugs-plugin/src/test/java/org/sonar/plugins/findbugs/FindbugsTests.java b/plugins/sonar-findbugs-plugin/src/test/java/org/sonar/plugins/findbugs/FindbugsTests.java new file mode 100644 index 00000000000..88afed2cdcd --- /dev/null +++ b/plugins/sonar-findbugs-plugin/src/test/java/org/sonar/plugins/findbugs/FindbugsTests.java @@ -0,0 +1,115 @@ +/* + * Sonar, open source software quality management tool. + * Copyright (C) 2009 SonarSource SA + * mailto:contact AT sonarsource DOT com + * + * Sonar is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * Sonar is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with Sonar; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 + */ +package org.sonar.plugins.findbugs; + +import org.apache.commons.io.IOUtils; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; +import org.sonar.api.CoreProperties; +import org.sonar.api.profiles.RulesProfile; +import org.sonar.api.rules.ActiveRule; +import org.sonar.api.rules.Rule; +import org.sonar.api.rules.RulePriority; +import org.sonar.api.rules.RulesManager; +import org.sonar.test.TestUtils; +import org.xml.sax.SAXException; + +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import static org.mockito.Matchers.anyString; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +public abstract class FindbugsTests { + + protected void assertXmlAreSimilar(String actualContent, String expectedFileName) throws IOException, SAXException { + InputStream input = getClass().getResourceAsStream("/org/sonar/plugins/findbugs/" + expectedFileName); + String expectedContent = IOUtils.toString(input); + TestUtils.assertSimilarXml(expectedContent, actualContent); + } + + protected List buildRulesFixture() { + List rules = new ArrayList(); + + Rule rule1 = new Rule("DLS: Dead store to local variable", "DLS_DEAD_LOCAL_STORE", + "DLS_DEAD_LOCAL_STORE", null, CoreProperties.FINDBUGS_PLUGIN, null); + + Rule rule2 = new Rule("UrF: Unread field", "URF_UNREAD_FIELD", + "URF_UNREAD_FIELD", null, CoreProperties.FINDBUGS_PLUGIN, null); + + rules.add(rule1); + rules.add(rule2); + + return rules; + } + + protected List buildActiveRulesFixture(List rules) { + List activeRules = new ArrayList(); + ActiveRule activeRule1 = new ActiveRule(null, rules.get(0), RulePriority.CRITICAL); + activeRules.add(activeRule1); + ActiveRule activeRule2 = new ActiveRule(null, rules.get(1), RulePriority.MAJOR); + activeRules.add(activeRule2); + return activeRules; + } + + + protected RulesManager createRulesManager() { + RulesManager rulesManager = mock(RulesManager.class); + + when(rulesManager.getPluginRule(eq(CoreProperties.FINDBUGS_PLUGIN), anyString())).thenAnswer(new Answer() { + public Rule answer(InvocationOnMock invocationOnMock) throws Throwable { + Object[] args = invocationOnMock.getArguments(); + Rule rule = new Rule(); + rule.setPluginName((String) args[0]); + rule.setKey((String) args[1]); + return rule; + } + }); + return rulesManager; + } + + protected RulesProfile createRulesProfileWithActiveRules() { + RulesProfile rulesProfile = mock(RulesProfile.class); + when(rulesProfile.getActiveRule(eq(CoreProperties.FINDBUGS_PLUGIN), anyString())).thenAnswer(new Answer() { + public ActiveRule answer(InvocationOnMock invocationOnMock) throws Throwable { + Object[] args = invocationOnMock.getArguments(); + ActiveRule activeRule = mock(ActiveRule.class); + when(activeRule.getPluginName()).thenReturn((String) args[0]); + when(activeRule.getRuleKey()).thenReturn((String) args[1]); + when(activeRule.getPriority()).thenReturn(RulePriority.CRITICAL); + return activeRule; + } + }); + when(rulesProfile.getActiveRulesByPlugin(CoreProperties.FINDBUGS_PLUGIN)).thenReturn(Arrays.asList(new ActiveRule())); + return rulesProfile; + } + + protected RulesProfile createRulesProfileWithoutActiveRules() { + RulesProfile rulesProfile = new RulesProfile(); + List list = new ArrayList(); + rulesProfile.setActiveRules(list); + return rulesProfile; + } +} diff --git a/plugins/sonar-findbugs-plugin/src/test/java/org/sonar/plugins/findbugs/FindbugsXmlReportParserTest.java b/plugins/sonar-findbugs-plugin/src/test/java/org/sonar/plugins/findbugs/FindbugsXmlReportParserTest.java new file mode 100644 index 00000000000..ca6073ffdae --- /dev/null +++ b/plugins/sonar-findbugs-plugin/src/test/java/org/sonar/plugins/findbugs/FindbugsXmlReportParserTest.java @@ -0,0 +1,82 @@ +/* + * Sonar, open source software quality management tool. + * Copyright (C) 2009 SonarSource SA + * mailto:contact AT sonarsource DOT com + * + * Sonar is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * Sonar is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with Sonar; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 + */ +package org.sonar.plugins.findbugs; + +import static org.hamcrest.Matchers.is; +import static org.junit.Assert.assertThat; + +import java.io.File; +import java.net.URISyntaxException; +import java.util.List; + +import org.junit.Before; +import org.junit.Test; +import org.sonar.api.utils.SonarException; + +public class FindbugsXmlReportParserTest { + + private List violations; + + @Before + public void init() { + File findbugsXmlReport = getFile("/org/sonar/plugins/findbugs/findbugsXml.xml"); + FindbugsXmlReportParser xmlParser = new FindbugsXmlReportParser(findbugsXmlReport); + violations = xmlParser.getViolations(); + } + + @Test(expected = SonarException.class) + public void createFindbugsXmlReportParserWithUnexistedReportFile() { + File xmlReport = new File("doesntExist.xml"); + new FindbugsXmlReportParser(xmlReport); + } + + @Test + public void testGetViolations() { + assertThat(violations.size(), is(3)); + + FindbugsXmlReportParser.Violation fbViolation = violations.get(0); + assertThat(fbViolation.getType(), is("AM_CREATES_EMPTY_ZIP_FILE_ENTRY")); + assertThat(fbViolation.getLongMessage(), + is("Empty zip file entry created in org.sonar.commons.ZipUtils._zip(String, File, ZipOutputStream)")); + assertThat(fbViolation.getStart(), is(107)); + assertThat(fbViolation.getEnd(), is(107)); + assertThat(fbViolation.getClassName(), is("org.sonar.commons.ZipUtils")); + assertThat(fbViolation.getSourcePath(), is("org/sonar/commons/ZipUtils.java")); + } + + @Test + public void testGetSonarJavaFileKey() { + FindbugsXmlReportParser.Violation violation = new FindbugsXmlReportParser.Violation(); + violation.className = "org.sonar.batch.Sensor"; + assertThat(violation.getSonarJavaFileKey(), is("org.sonar.batch.Sensor")); + violation.className = "Sensor"; + assertThat(violation.getSonarJavaFileKey(), is("Sensor")); + violation.className = "org.sonar.batch.Sensor$1"; + assertThat(violation.getSonarJavaFileKey(), is("org.sonar.batch.Sensor")); + } + + private final File getFile(String filename) { + try { + return new File(getClass().getResource(filename).toURI()); + } catch (URISyntaxException e) { + throw new SonarException("Unable to open file " + filename, e); + } + } +} diff --git a/plugins/sonar-findbugs-plugin/src/test/java/org/sonar/plugins/findbugs/tools/RulesGenerator.java b/plugins/sonar-findbugs-plugin/src/test/java/org/sonar/plugins/findbugs/tools/RulesGenerator.java new file mode 100644 index 00000000000..d3701ed66cc --- /dev/null +++ b/plugins/sonar-findbugs-plugin/src/test/java/org/sonar/plugins/findbugs/tools/RulesGenerator.java @@ -0,0 +1,190 @@ +/* + * Sonar, open source software quality management tool. + * Copyright (C) 2009 SonarSource SA + * mailto:contact AT sonarsource DOT com + * + * Sonar is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * Sonar is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with Sonar; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 + */ +package org.sonar.plugins.findbugs.tools; + +import org.apache.commons.lang.StringUtils; +import org.codehaus.plexus.util.IOUtil; +import org.codehaus.staxmate.in.SMHierarchicCursor; +import org.codehaus.staxmate.in.SMInputCursor; +import org.sonar.api.rules.Rule; +import org.sonar.api.rules.RulesCategory; +import org.sonar.api.rules.StandardRulesXmlParser; +import org.sonar.api.utils.StaxParser; + +import javax.xml.stream.XMLStreamException; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.net.MalformedURLException; +import java.net.URL; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class RulesGenerator { + + private static final String FOR_VERSION = "1.3.8"; + + + private final static Map BUG_CATEGS = new HashMap(); + + static { + BUG_CATEGS.put("STYLE", "Usability"); + BUG_CATEGS.put("NOISE", "Reliability"); + BUG_CATEGS.put("CORRECTNESS", "Reliability"); + BUG_CATEGS.put("SECURITY", "Reliability"); + BUG_CATEGS.put("BAD_PRACTICE", "Maintainability"); + BUG_CATEGS.put("MT_CORRECTNESS", "Reliability"); + BUG_CATEGS.put("PERFORMANCE", "Efficiency"); + BUG_CATEGS.put("I18N", "Portability"); + BUG_CATEGS.put("MALICIOUS_CODE", "Reliability"); + } + + public static void main(String[] args) throws Exception { + List bugs = getBugsToImport(); + String generatedXML = parseMessages(bugs); + File out = new File(".", "rules.xml"); + IOUtil.copy(generatedXML.getBytes(), new FileOutputStream(out)); + System.out.println("Written to " + out.getPath()); + } + + private static List getBugsToImport() throws MalformedURLException, IOException, XMLStreamException { + URL messages = new URL("http://findbugs.googlecode.com/svn/branches/" + FOR_VERSION + "/findbugs/etc/findbugs.xml"); + InputStream in = messages.openStream(); + final List bugs = new ArrayList(); + StaxParser p = new StaxParser(new StaxParser.XmlStreamHandler() { + + public void stream(SMHierarchicCursor rootCursor) throws XMLStreamException { + rootCursor.advance(); + SMInputCursor bugPatterns = rootCursor.descendantElementCursor("BugPattern"); + collectBugDefs(bugs, bugPatterns); + } + + private void collectBugDefs(final List bugs, SMInputCursor bugPatterns) throws XMLStreamException { + while (bugPatterns.getNext() != null) { + if (bugPatterns.asEvent().isEndElement()) continue; + + String experimental = bugPatterns.getAttrValue("experimental"); + boolean isExperimental = (StringUtils.isNotEmpty(experimental) && Boolean.valueOf(experimental)) || bugPatterns.getAttrValue("category").equals("EXPERIMENTAL"); + String deprecated = bugPatterns.getAttrValue("deprecated"); + boolean isDeprecated = StringUtils.isNotEmpty(deprecated) && Boolean.valueOf(deprecated); + if (!isExperimental && !isDeprecated) { + bugs.add(new FindBugsBug(bugPatterns.getAttrValue("category"), bugPatterns.getAttrValue("type"))); + } + } + } + }); + p.parse(in); + in.close(); + return bugs; + } + + private static String parseMessages(final List bugs) throws MalformedURLException, IOException, XMLStreamException { + URL messages = new URL("http://findbugs.googlecode.com/svn/branches/" + FOR_VERSION + "/findbugs/etc/messages.xml"); + + InputStream in = messages.openStream(); + final List rules = new ArrayList(); + StaxParser p = new StaxParser(new StaxParser.XmlStreamHandler() { + + public void stream(SMHierarchicCursor rootCursor) throws XMLStreamException { + rootCursor.advance(); + Map bugCategoriesDecr = new HashMap(); + SMInputCursor childrens = rootCursor.childElementCursor(); + while (childrens.getNext() != null) { + if (childrens.asEvent().isEndElement()) continue; + if (childrens.getLocalName().equals("BugCategory")) { + String bugCateg = childrens.getAttrValue("category"); + bugCategoriesDecr.put(bugCateg, childrens.childElementCursor("Description").advance().collectDescendantText()); + } else if (childrens.getLocalName().equals("BugPattern")) { + String bugType = childrens.getAttrValue("type"); + FindBugsBug bug = getFindBugsBugByType(bugType, bugs); + if (bug == null) continue; + + rules.add(getRuleForBug(bugType, bug, bugCategoriesDecr, childrens)); + } + } + } + }); + + p.parse(in); + in.close(); + StandardRulesXmlParser parser = new StandardRulesXmlParser(); + return parser.toXml(rules); + } + + private static Rule getRuleForBug(String bugType, FindBugsBug bug, + Map bugCategoriesDecr, SMInputCursor childrens) throws XMLStreamException { + Rule rule = new Rule(); + rule.setKey(bugType); + rule.setConfigKey(bugType); + + String rulesCateg = BUG_CATEGS.get(bug.getCategory()); + if (StringUtils.isEmpty(rulesCateg)) { + throw new RuntimeException("Rules cat not found " + bug.getCategory()); + } + rule.setRulesCategory(new RulesCategory(rulesCateg)); + + SMInputCursor descendents = childrens.childElementCursor(); + while (descendents.getNext() != null) { + if (descendents.asEvent().isStartElement()) { + if (descendents.getLocalName().equals("ShortDescription")) { + String categName = bugCategoriesDecr.get(bug.getCategory()); + if (StringUtils.isEmpty(categName)) throw new RuntimeException("Cat not found " + bug.getCategory()); + rule.setName(categName + " - " + descendents.collectDescendantText()); + } else if (descendents.getLocalName().equals("Details")) { + rule.setDescription(descendents.collectDescendantText()); + } + } + } + return rule; + } + + private static FindBugsBug getFindBugsBugByType(String type, List bugs) { + for (FindBugsBug findBugsBug : bugs) { + if (findBugsBug.getType().equals(type)) { + return findBugsBug; + } + } + return null; + } + + private static class FindBugsBug { + private String category; + private String type; + + public FindBugsBug(String category, String type) { + super(); + this.category = category; + this.type = type; + } + + public String getCategory() { + return category; + } + + public String getType() { + return type; + } + + } + +} diff --git a/plugins/sonar-findbugs-plugin/src/test/java/org/sonar/plugins/findbugs/xml/FindBugsFilterTest.java b/plugins/sonar-findbugs-plugin/src/test/java/org/sonar/plugins/findbugs/xml/FindBugsFilterTest.java new file mode 100644 index 00000000000..384dc56882f --- /dev/null +++ b/plugins/sonar-findbugs-plugin/src/test/java/org/sonar/plugins/findbugs/xml/FindBugsFilterTest.java @@ -0,0 +1,124 @@ +/* + * Sonar, open source software quality management tool. + * Copyright (C) 2009 SonarSource SA + * mailto:contact AT sonarsource DOT com + * + * Sonar is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * Sonar is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with Sonar; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 + */ +package org.sonar.plugins.findbugs.xml; + +import org.apache.commons.io.IOUtils; +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; +import org.junit.Test; +import org.sonar.api.CoreProperties; +import org.sonar.api.rules.ActiveRule; +import org.sonar.api.rules.Rule; +import org.sonar.api.rules.RulePriority; +import org.sonar.plugins.findbugs.FindbugsRulePriorityMapper; +import org.xml.sax.SAXException; + +import java.io.IOException; +import java.io.InputStream; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +public class FindBugsFilterTest extends FindBugsXmlTests { + + @Test + public void shouldBuilXmlFromModuleTree() throws IOException, SAXException { + FindBugsFilter root = buildModuleTreeFixture(); + + String xml = root.toXml(); + + assertXmlAreSimilar(xml, "test_module_tree.xml"); + } + + @Test + public void shouldBuilModuleTreeFromXml() throws IOException { + InputStream input = getClass().getResourceAsStream("/org/sonar/plugins/findbugs/test_module_tree.xml"); + + FindBugsFilter module = FindBugsFilter.fromXml(IOUtils.toString(input)); + + List matches = module.getMatchs(); + assertThat(matches.size(), is(2)); + assertChild(matches.get(0), "DLS_DEAD_LOCAL_STORE"); + assertChild(matches.get(1), "URF_UNREAD_FIELD"); + } + + private static FindBugsFilter buildModuleTreeFixture() { + FindBugsFilter findBugsFilter = new FindBugsFilter(); + findBugsFilter.addMatch(new Match(new Bug("DLS_DEAD_LOCAL_STORE"))); + findBugsFilter.addMatch(new Match(new Bug("URF_UNREAD_FIELD"))); + return findBugsFilter; + } + + private static final String DLS_DEAD_LOCAL_STORE = "DLS_DEAD_LOCAL_STORE"; + private static final String SS_SHOULD_BE_STATIC = "SS_SHOULD_BE_STATIC"; + + @Test + public void shouldBuildModuleWithProperties() { + ActiveRule activeRule = anActiveRule(DLS_DEAD_LOCAL_STORE); + FindBugsFilter filter = FindBugsFilter.fromActiveRules(Arrays.asList(activeRule)); + + assertThat(filter.getMatchs().size(), is(1)); + assertChild(filter.getMatchs().get(0), DLS_DEAD_LOCAL_STORE); + } + + @Test + public void shouldBuildOnlyOneModuleWhenNoActiveRules() { + FindBugsFilter filter = FindBugsFilter.fromActiveRules(Collections.emptyList()); + assertThat(filter.getMatchs().size(), is(0)); + } + + @Test + public void shouldBuildTwoModulesEvenIfSameTwoRulesActivated() { + ActiveRule activeRule1 = anActiveRule(DLS_DEAD_LOCAL_STORE); + ActiveRule activeRule2 = anActiveRule(SS_SHOULD_BE_STATIC); + FindBugsFilter filter = FindBugsFilter.fromActiveRules(Arrays.asList(activeRule1, activeRule2)); + + List matches = filter.getMatchs(); + assertThat(matches.size(), is(2)); + + assertChild(matches.get(0), DLS_DEAD_LOCAL_STORE); + assertChild(matches.get(1), SS_SHOULD_BE_STATIC); + } + + @Test + public void shouldBuildOnlyOneModuleWhenNoFindbugsActiveRules() { + ActiveRule activeRule1 = anActiveRuleFromAnotherPlugin(); + ActiveRule activeRule2 = anActiveRuleFromAnotherPlugin(); + + FindBugsFilter filter = FindBugsFilter.fromActiveRules(Arrays.asList(activeRule1, activeRule2)); + assertThat(filter.getMatchs().size(), is(0)); + } + + private static ActiveRule anActiveRule(String configKey) { + Rule rule = new Rule(); + rule.setConfigKey(configKey); + rule.setPluginName(CoreProperties.FINDBUGS_PLUGIN); + ActiveRule activeRule = new ActiveRule(null, rule, RulePriority.CRITICAL); + return activeRule; + } + + private static ActiveRule anActiveRuleFromAnotherPlugin() { + Rule rule1 = new Rule(); + rule1.setPluginName("not-a-findbugs-plugin"); + ActiveRule activeRule1 = new ActiveRule(null, rule1, RulePriority.CRITICAL); + return activeRule1; + } + +} diff --git a/plugins/sonar-findbugs-plugin/src/test/java/org/sonar/plugins/findbugs/xml/FindBugsXmlTests.java b/plugins/sonar-findbugs-plugin/src/test/java/org/sonar/plugins/findbugs/xml/FindBugsXmlTests.java new file mode 100644 index 00000000000..907679f880a --- /dev/null +++ b/plugins/sonar-findbugs-plugin/src/test/java/org/sonar/plugins/findbugs/xml/FindBugsXmlTests.java @@ -0,0 +1,33 @@ +/* + * Sonar, open source software quality management tool. + * Copyright (C) 2009 SonarSource SA + * mailto:contact AT sonarsource DOT com + * + * Sonar is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * Sonar is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with Sonar; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 + */ +package org.sonar.plugins.findbugs.xml; + +import static org.hamcrest.CoreMatchers.*; +import static org.junit.Assert.*; +import org.sonar.plugins.findbugs.FindbugsTests; + +public class FindBugsXmlTests extends FindbugsTests { + + protected static void assertChild(Match child, String configKey) { + Bug bug = child.getBug(); + assertNotNull(bug); + assertThat(bug.getPattern(), is(configKey)); + } +} \ No newline at end of file diff --git a/plugins/sonar-findbugs-plugin/src/test/resources/org/sonar/plugins/findbugs/FindbugsRulesRepositoryTest/shouldImportCategories.xml b/plugins/sonar-findbugs-plugin/src/test/resources/org/sonar/plugins/findbugs/FindbugsRulesRepositoryTest/shouldImportCategories.xml new file mode 100644 index 00000000000..5f4ae48efa2 --- /dev/null +++ b/plugins/sonar-findbugs-plugin/src/test/resources/org/sonar/plugins/findbugs/FindbugsRulesRepositoryTest/shouldImportCategories.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/plugins/sonar-findbugs-plugin/src/test/resources/org/sonar/plugins/findbugs/FindbugsRulesRepositoryTest/shouldImportCodes.xml b/plugins/sonar-findbugs-plugin/src/test/resources/org/sonar/plugins/findbugs/FindbugsRulesRepositoryTest/shouldImportCodes.xml new file mode 100644 index 00000000000..0da831362e5 --- /dev/null +++ b/plugins/sonar-findbugs-plugin/src/test/resources/org/sonar/plugins/findbugs/FindbugsRulesRepositoryTest/shouldImportCodes.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/plugins/sonar-findbugs-plugin/src/test/resources/org/sonar/plugins/findbugs/FindbugsRulesRepositoryTest/shouldImportPatterns.xml b/plugins/sonar-findbugs-plugin/src/test/resources/org/sonar/plugins/findbugs/FindbugsRulesRepositoryTest/shouldImportPatterns.xml new file mode 100644 index 00000000000..072a4b077ce --- /dev/null +++ b/plugins/sonar-findbugs-plugin/src/test/resources/org/sonar/plugins/findbugs/FindbugsRulesRepositoryTest/shouldImportPatterns.xml @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/plugins/sonar-findbugs-plugin/src/test/resources/org/sonar/plugins/findbugs/findbugs-class-without-package.xml b/plugins/sonar-findbugs-plugin/src/test/resources/org/sonar/plugins/findbugs/findbugs-class-without-package.xml new file mode 100644 index 00000000000..50dec4a885a --- /dev/null +++ b/plugins/sonar-findbugs-plugin/src/test/resources/org/sonar/plugins/findbugs/findbugs-class-without-package.xml @@ -0,0 +1,7 @@ + + + + + + + diff --git a/plugins/sonar-findbugs-plugin/src/test/resources/org/sonar/plugins/findbugs/findbugs-include.xml b/plugins/sonar-findbugs-plugin/src/test/resources/org/sonar/plugins/findbugs/findbugs-include.xml new file mode 100644 index 00000000000..32e2e8f516c --- /dev/null +++ b/plugins/sonar-findbugs-plugin/src/test/resources/org/sonar/plugins/findbugs/findbugs-include.xml @@ -0,0 +1,36 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/plugins/sonar-findbugs-plugin/src/test/resources/org/sonar/plugins/findbugs/findbugsXml.xml b/plugins/sonar-findbugs-plugin/src/test/resources/org/sonar/plugins/findbugs/findbugsXml.xml new file mode 100644 index 00000000000..d5d47cf39b7 --- /dev/null +++ b/plugins/sonar-findbugs-plugin/src/test/resources/org/sonar/plugins/findbugs/findbugsXml.xml @@ -0,0 +1,48 @@ + + + /Users/freddy/Documents/sonar_projects/sonar/sonar-commons/target/classes + /Users/freddy/.m2/repository/org/apache/maven/reporting/maven-reporting-impl/2.0/maven-reporting-impl-2.0.jar + /Users/freddy/Documents/sonar_projects/sonar/sonar-commons/src/main/java + /Users/freddy/Documents/sonar_projects/sonar/sonar-commons/target + + + Creates an empty zip file entry + Empty zip file entry created in org.sonar.commons.ZipUtils._zip(String, File, ZipOutputStream) + + + At ZipUtils.java:[lines 33-139] + + In class org.sonar.commons.ZipUtils + + + + In method org.sonar.commons.ZipUtils._zip(String, File, ZipOutputStream) + + + At ZipUtils.java:[line 107] + + + At ZipUtils.java:[line 107] + + + + Could be refactored into a named static inner class + The class org.sonar.commons.resources.MeasuresDao$1 could be refactored into a named _static_ inner class + + + At MeasuresDao.java:[lines 56-57] + + In class org.sonar.commons.resources.MeasuresDao$1 + + + At MeasuresDao.java:[lines 56-57] + + + + + + + + + + \ No newline at end of file diff --git a/plugins/sonar-findbugs-plugin/src/test/resources/org/sonar/plugins/findbugs/test_header.xml b/plugins/sonar-findbugs-plugin/src/test/resources/org/sonar/plugins/findbugs/test_header.xml new file mode 100644 index 00000000000..bd0b26eb00a --- /dev/null +++ b/plugins/sonar-findbugs-plugin/src/test/resources/org/sonar/plugins/findbugs/test_header.xml @@ -0,0 +1,3 @@ + + + \ No newline at end of file diff --git a/plugins/sonar-findbugs-plugin/src/test/resources/org/sonar/plugins/findbugs/test_module_tree.xml b/plugins/sonar-findbugs-plugin/src/test/resources/org/sonar/plugins/findbugs/test_module_tree.xml new file mode 100644 index 00000000000..ec5853df727 --- /dev/null +++ b/plugins/sonar-findbugs-plugin/src/test/resources/org/sonar/plugins/findbugs/test_module_tree.xml @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/plugins/sonar-findbugs-plugin/src/test/resources/org/sonar/plugins/findbugs/test_xml_complete.xml b/plugins/sonar-findbugs-plugin/src/test/resources/org/sonar/plugins/findbugs/test_xml_complete.xml new file mode 100644 index 00000000000..6be898051d5 --- /dev/null +++ b/plugins/sonar-findbugs-plugin/src/test/resources/org/sonar/plugins/findbugs/test_xml_complete.xml @@ -0,0 +1,11 @@ + + + + + + + + + + + -- cgit v1.2.3