From 0264a155e42c32c812807e9155ffee6e6e9de3b2 Mon Sep 17 00:00:00 2001 From: Julien HENRY Date: Wed, 28 Aug 2013 18:14:14 +0200 Subject: [PATCH] Fix some quality flaws --- .../org/sonar/colorizer/GroovyTokenizers.java | 10 ++++--- .../org/sonar/core/component/ScanGraph.java | 5 ++-- .../core/metric/DefaultMetricFinder.java | 7 +++-- .../sonar/core/persistence/SemaphoreDao.java | 7 +++-- .../sonar/core/plugins/PluginInstaller.java | 8 +++-- .../sonar/core/properties/PropertiesDao.java | 5 ++-- .../core/resource/ResourceIndexerDao.java | 22 +++++++------- .../org/sonar/core/test/DefaultTestPlan.java | 6 ++-- .../org/sonar/core/test/DefaultTestable.java | 10 ++++--- .../java/org/sonar/api/batch/SquidUtils.java | 10 ++++--- .../sonar/api/batch/maven/MavenPlugin.java | 22 +++++++------- .../org/sonar/api/batch/maven/MavenUtils.java | 17 ++++++----- .../api/checks/AnnotationCheckFactory.java | 5 ++-- .../java/org/sonar/api/measures/Measure.java | 6 ++-- .../sonar/api/profiles/XMLProfileParser.java | 15 ++++++---- .../java/org/sonar/api/resources/Project.java | 15 ++++++---- .../org/sonar/api/resources/ResourceType.java | 5 ++-- .../main/java/org/sonar/api/rules/Rule.java | 18 ++++++++--- .../org/sonar/api/rules/RulePriority.java | 9 ++++-- .../org/sonar/api/utils/HttpDownloader.java | 14 +++++---- .../org/sonar/api/utils/TimeProfiler.java | 7 +++-- .../java/org/sonar/api/utils/XpathParser.java | 30 +++++++++++++------ .../java/org/sonar/api/utils/ZipUtils.java | 6 ++-- .../java/org/sonar/api/web/Criterion.java | 19 ++++++------ .../org/sonar/server/db/DatabaseMigrator.java | 7 +++-- .../server/issue/ServerIssueStorage.java | 10 ++++--- 26 files changed, 178 insertions(+), 117 deletions(-) diff --git a/sonar-colorizer/src/main/java/org/sonar/colorizer/GroovyTokenizers.java b/sonar-colorizer/src/main/java/org/sonar/colorizer/GroovyTokenizers.java index 61ce2caa067..00b81250ae4 100644 --- a/sonar-colorizer/src/main/java/org/sonar/colorizer/GroovyTokenizers.java +++ b/sonar-colorizer/src/main/java/org/sonar/colorizer/GroovyTokenizers.java @@ -25,13 +25,15 @@ import java.util.List; public final class GroovyTokenizers { + private static final String SPAN_END = ""; + private GroovyTokenizers() { } public static List forHtml() { - return Collections.unmodifiableList(Arrays.asList(new JavaAnnotationTokenizer("", ""), new LiteralTokenizer( - "", ""), new CDocTokenizer("", ""), new CppDocTokenizer("", - ""), new JavadocTokenizer("", ""), new JavaConstantTokenizer("", ""), - new KeywordsTokenizer("", "", GroovyKeywords.get()))); + return Collections.unmodifiableList(Arrays.asList(new JavaAnnotationTokenizer("", SPAN_END), new LiteralTokenizer( + "", SPAN_END), new CDocTokenizer("", SPAN_END), new CppDocTokenizer("", + SPAN_END), new JavadocTokenizer("", SPAN_END), new JavaConstantTokenizer("", SPAN_END), + new KeywordsTokenizer("", SPAN_END, GroovyKeywords.get()))); } } diff --git a/sonar-core/src/main/java/org/sonar/core/component/ScanGraph.java b/sonar-core/src/main/java/org/sonar/core/component/ScanGraph.java index 91db3d7440e..82661baf7d5 100644 --- a/sonar-core/src/main/java/org/sonar/core/component/ScanGraph.java +++ b/sonar-core/src/main/java/org/sonar/core/component/ScanGraph.java @@ -35,6 +35,7 @@ import javax.annotation.Nullable; public class ScanGraph extends BeanGraph implements BatchComponent { + private static final String COMPONENT = "component"; private final Vertex componentsRoot; private ScanGraph(Graph graph) { @@ -63,13 +64,13 @@ public class ScanGraph extends BeanGraph implements BatchComponent { } public Iterable getComponents() { - Iterable componentVertices = componentsRoot.getVertices(Direction.OUT, "component"); + Iterable componentVertices = componentsRoot.getVertices(Direction.OUT, COMPONENT); return new BeanIterable(this, ComponentVertex.class, componentVertices); } public ComponentVertex addComponent(Component component) { Vertex vertex = getUnderlyingGraph().addVertex(null); - getUnderlyingGraph().addEdge(null, componentsRoot, vertex, "component"); + getUnderlyingGraph().addEdge(null, componentsRoot, vertex, COMPONENT); ComponentVertex wrapper = wrap(vertex, ComponentVertex.class); wrapper.copyFrom(component); return wrapper; diff --git a/sonar-core/src/main/java/org/sonar/core/metric/DefaultMetricFinder.java b/sonar-core/src/main/java/org/sonar/core/metric/DefaultMetricFinder.java index d5925f8d8bd..dbec63946f0 100644 --- a/sonar-core/src/main/java/org/sonar/core/metric/DefaultMetricFinder.java +++ b/sonar-core/src/main/java/org/sonar/core/metric/DefaultMetricFinder.java @@ -29,6 +29,7 @@ import java.util.List; public class DefaultMetricFinder implements MetricFinder { + private static final String ENABLED = "enabled"; private DatabaseSessionFactory sessionFactory; public DefaultMetricFinder(DatabaseSessionFactory sessionFactory) { @@ -36,11 +37,11 @@ public class DefaultMetricFinder implements MetricFinder { } public Metric findById(int id) { - return sessionFactory.getSession().getSingleResult(Metric.class, "id", id, "enabled", true); + return sessionFactory.getSession().getSingleResult(Metric.class, "id", id, ENABLED, true); } public Metric findByKey(String key) { - return sessionFactory.getSession().getSingleResult(Metric.class, "key", key, "enabled", true); + return sessionFactory.getSession().getSingleResult(Metric.class, "key", key, ENABLED, true); } public Collection findAll(List metricKeys) { @@ -59,7 +60,7 @@ public class DefaultMetricFinder implements MetricFinder { } protected Collection doFindAll() { - return sessionFactory.getSession().getResults(Metric.class, "enabled", true); + return sessionFactory.getSession().getResults(Metric.class, ENABLED, true); } } diff --git a/sonar-core/src/main/java/org/sonar/core/persistence/SemaphoreDao.java b/sonar-core/src/main/java/org/sonar/core/persistence/SemaphoreDao.java index 7e18a8e87c1..e3db45d736a 100644 --- a/sonar-core/src/main/java/org/sonar/core/persistence/SemaphoreDao.java +++ b/sonar-core/src/main/java/org/sonar/core/persistence/SemaphoreDao.java @@ -32,6 +32,7 @@ import java.util.Date; */ public class SemaphoreDao { + private static final String SEMAPHORE_NAME_MUST_NOT_BE_EMPTY = "Semaphore name must not be empty"; private final MyBatis mybatis; public SemaphoreDao(MyBatis mybatis) { @@ -39,7 +40,7 @@ public class SemaphoreDao { } public Semaphores.Semaphore acquire(String name, int maxAgeInSeconds) { - Preconditions.checkArgument(!Strings.isNullOrEmpty(name), "Semaphore name must not be empty"); + Preconditions.checkArgument(!Strings.isNullOrEmpty(name), SEMAPHORE_NAME_MUST_NOT_BE_EMPTY); Preconditions.checkArgument(maxAgeInSeconds >= 0, "Semaphore max age must be positive: " + maxAgeInSeconds); SqlSession session = mybatis.openSession(); @@ -60,7 +61,7 @@ public class SemaphoreDao { } public Semaphores.Semaphore acquire(String name) { - Preconditions.checkArgument(!Strings.isNullOrEmpty(name), "Semaphore name must not be empty"); + Preconditions.checkArgument(!Strings.isNullOrEmpty(name), SEMAPHORE_NAME_MUST_NOT_BE_EMPTY); SqlSession session = mybatis.openSession(); try { @@ -92,7 +93,7 @@ public class SemaphoreDao { } public void release(String name) { - Preconditions.checkArgument(!Strings.isNullOrEmpty(name), "Semaphore name must not be empty"); + Preconditions.checkArgument(!Strings.isNullOrEmpty(name), SEMAPHORE_NAME_MUST_NOT_BE_EMPTY); SqlSession session = mybatis.openSession(); try { session.getMapper(SemaphoreMapper.class).release(name); diff --git a/sonar-core/src/main/java/org/sonar/core/plugins/PluginInstaller.java b/sonar-core/src/main/java/org/sonar/core/plugins/PluginInstaller.java index 65c7b728355..351f31d8917 100644 --- a/sonar-core/src/main/java/org/sonar/core/plugins/PluginInstaller.java +++ b/sonar-core/src/main/java/org/sonar/core/plugins/PluginInstaller.java @@ -32,6 +32,8 @@ import java.util.zip.ZipEntry; public class PluginInstaller { + private static final String FAIL_TO_INSTALL_PLUGIN = "Fail to install plugin: "; + public DefaultPluginMetadata install(File pluginFile, boolean isCore, List deprecatedExtensions, File pluginBasedir) { try { // Copy the plugin before extracting metadata to avoid file lock on Widnows @@ -41,7 +43,7 @@ public class PluginInstaller { install(metadata, pluginBasedir, deployedPlugin); return metadata; } catch (IOException e) { - throw new SonarException("Fail to install plugin: " + pluginFile, e); + throw new SonarException(FAIL_TO_INSTALL_PLUGIN + pluginFile, e); } } @@ -51,7 +53,7 @@ public class PluginInstaller { File deployedPlugin = copyPlugin(pluginBasedir, pluginFile); install(metadata, pluginBasedir, deployedPlugin); } catch (IOException e) { - throw new SonarException("Fail to install plugin: " + metadata, e); + throw new SonarException(FAIL_TO_INSTALL_PLUGIN + metadata, e); } } @@ -61,7 +63,7 @@ public class PluginInstaller { copyDependencies(metadata, deployedPlugin, pluginBasedir); copyDeprecatedExtensions(metadata, pluginBasedir); } catch (IOException e) { - throw new SonarException("Fail to install plugin: " + metadata, e); + throw new SonarException(FAIL_TO_INSTALL_PLUGIN + metadata, e); } } diff --git a/sonar-core/src/main/java/org/sonar/core/properties/PropertiesDao.java b/sonar-core/src/main/java/org/sonar/core/properties/PropertiesDao.java index c2bab0b4cea..dd4dae1138d 100644 --- a/sonar-core/src/main/java/org/sonar/core/properties/PropertiesDao.java +++ b/sonar-core/src/main/java/org/sonar/core/properties/PropertiesDao.java @@ -34,6 +34,7 @@ import java.util.Map; public class PropertiesDao implements BatchComponent, ServerComponent { + private static final String NOTIFICATION_PREFIX = "notification."; private MyBatis mybatis; public PropertiesDao(MyBatis mybatis) { @@ -53,7 +54,7 @@ public class PropertiesDao implements BatchComponent, ServerComponent { SqlSession session = mybatis.openSession(); PropertiesMapper mapper = session.getMapper(PropertiesMapper.class); try { - return mapper.findUsersForNotification("notification." + notificationDispatcherKey + "." + notificationChannelKey, resourceId); + return mapper.findUsersForNotification(NOTIFICATION_PREFIX + notificationDispatcherKey + "." + notificationChannelKey, resourceId); } finally { MyBatis.closeQuietly(session); } @@ -63,7 +64,7 @@ public class PropertiesDao implements BatchComponent, ServerComponent { SqlSession session = mybatis.openSession(); PropertiesMapper mapper = session.getMapper(PropertiesMapper.class); try { - return mapper.findNotificationSubscribers("notification." + notificationDispatcherKey + "." + notificationChannelKey, componentKey); + return mapper.findNotificationSubscribers(NOTIFICATION_PREFIX + notificationDispatcherKey + "." + notificationChannelKey, componentKey); } finally { MyBatis.closeQuietly(session); } diff --git a/sonar-core/src/main/java/org/sonar/core/resource/ResourceIndexerDao.java b/sonar-core/src/main/java/org/sonar/core/resource/ResourceIndexerDao.java index 0256c625bc0..cce1141aaec 100644 --- a/sonar-core/src/main/java/org/sonar/core/resource/ResourceIndexerDao.java +++ b/sonar-core/src/main/java/org/sonar/core/resource/ResourceIndexerDao.java @@ -29,6 +29,7 @@ import org.sonar.core.persistence.MyBatis; public class ResourceIndexerDao { + private static final String SELECT_RESOURCES = "org.sonar.core.resource.ResourceIndexerMapper.selectResources"; public static final int MINIMUM_KEY_SIZE = 3; public static final int SINGLE_INDEX_SIZE = 2; @@ -85,12 +86,12 @@ public class ResourceIndexerDao { private void doIndexProject(int rootProjectId, SqlSession session, final ResourceIndexerMapper mapper) { // non indexed resources ResourceIndexerQuery query = ResourceIndexerQuery.create() - .setNonIndexedOnly(true) - .setQualifiers(NOT_RENAMABLE_QUALIFIERS) - .setScopes(NOT_RENAMABLE_SCOPES) - .setRootProjectId(rootProjectId); + .setNonIndexedOnly(true) + .setQualifiers(NOT_RENAMABLE_QUALIFIERS) + .setScopes(NOT_RENAMABLE_SCOPES) + .setRootProjectId(rootProjectId); - session.select("org.sonar.core.resource.ResourceIndexerMapper.selectResources", query, new ResultHandler() { + session.select(SELECT_RESOURCES, query, new ResultHandler() { public void handleResult(ResultContext context) { ResourceDto resource = (ResourceDto) context.getResultObject(); doIndex(resource, mapper); @@ -100,12 +101,12 @@ public class ResourceIndexerDao { // some resources can be renamed, so index must be regenerated // -> delete existing rows and create them again query = ResourceIndexerQuery.create() - .setNonIndexedOnly(false) - .setQualifiers(RENAMABLE_QUALIFIERS) - .setScopes(RENAMABLE_SCOPES) - .setRootProjectId(rootProjectId); + .setNonIndexedOnly(false) + .setQualifiers(RENAMABLE_QUALIFIERS) + .setScopes(RENAMABLE_SCOPES) + .setRootProjectId(rootProjectId); - session.select("org.sonar.core.resource.ResourceIndexerMapper.selectResources", query, new ResultHandler() { + session.select(SELECT_RESOURCES, query, new ResultHandler() { public void handleResult(ResultContext context) { ResourceDto resource = (ResourceDto) context.getResultObject(); @@ -115,7 +116,6 @@ public class ResourceIndexerDao { }); } - void doIndex(ResourceDto resource, ResourceIndexerMapper mapper) { String key = nameToKey(resource.getName()); if (key.length() >= MINIMUM_KEY_SIZE || key.length() == SINGLE_INDEX_SIZE) { diff --git a/sonar-core/src/main/java/org/sonar/core/test/DefaultTestPlan.java b/sonar-core/src/main/java/org/sonar/core/test/DefaultTestPlan.java index 5cbc2dfbbb9..de16ae780d0 100644 --- a/sonar-core/src/main/java/org/sonar/core/test/DefaultTestPlan.java +++ b/sonar-core/src/main/java/org/sonar/core/test/DefaultTestPlan.java @@ -34,6 +34,8 @@ import javax.annotation.CheckForNull; import java.util.List; public class DefaultTestPlan extends BeanVertex implements MutableTestPlan { + private static final String TESTCASE = "testcase"; + public Component component() { Vertex component = GraphUtil.singleAdjacent(element(), Direction.IN, "testplan"); return beanGraph().wrap(component, ComponentVertex.class); @@ -51,13 +53,13 @@ public class DefaultTestPlan extends BeanVertex implements MutableTestPlan { } public MutableTestCase addTestCase(String name) { - DefaultTestCase testCase = beanGraph().createAdjacentVertex(this, DefaultTestCase.class, "testcase"); + DefaultTestCase testCase = beanGraph().createAdjacentVertex(this, DefaultTestCase.class, TESTCASE); testCase.setName(name); return testCase; } public Iterable testCases() { - return (Iterable) getVertices(DefaultTestCase.class, Direction.OUT, "testcase"); + return (Iterable) getVertices(DefaultTestCase.class, Direction.OUT, TESTCASE); } } diff --git a/sonar-core/src/main/java/org/sonar/core/test/DefaultTestable.java b/sonar-core/src/main/java/org/sonar/core/test/DefaultTestable.java index 3a431397eaa..1111fafe00e 100644 --- a/sonar-core/src/main/java/org/sonar/core/test/DefaultTestable.java +++ b/sonar-core/src/main/java/org/sonar/core/test/DefaultTestable.java @@ -39,6 +39,8 @@ import java.util.SortedSet; public class DefaultTestable extends BeanVertex implements MutableTestable { + private static final String COVERS = "covers"; + public Component component() { Vertex component = GraphUtil.singleAdjacent(element(), Direction.IN, "testable"); return beanGraph().wrap(component, ComponentVertex.class); @@ -92,7 +94,7 @@ public class DefaultTestable extends BeanVertex implements MutableTestable { } public CoverageBlock coverageBlock(final TestCase testCase) { - return Iterables.find(getEdges(DefaultCoverageBlock.class, Direction.IN, "covers"), new Predicate() { + return Iterables.find(getEdges(DefaultCoverageBlock.class, Direction.IN, COVERS), new Predicate() { public boolean apply(CoverageBlock input) { return input.testCase().name().equals(testCase.name()); } @@ -100,14 +102,14 @@ public class DefaultTestable extends BeanVertex implements MutableTestable { } public Iterable coverageBlocks() { - return (Iterable)getEdges(DefaultCoverageBlock.class, Direction.IN, "covers"); + return (Iterable) getEdges(DefaultCoverageBlock.class, Direction.IN, COVERS); } private Iterable coverEdges() { - return element().query().labels("covers").direction(Direction.IN).edges(); + return element().query().labels(COVERS).direction(Direction.IN).edges(); } private List lines(Edge edge) { return (List) edge.getProperty("lines"); } -} \ No newline at end of file +} diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/batch/SquidUtils.java b/sonar-plugin-api/src/main/java/org/sonar/api/batch/SquidUtils.java index 318868e15c2..dbb2e2e2132 100644 --- a/sonar-plugin-api/src/main/java/org/sonar/api/batch/SquidUtils.java +++ b/sonar-plugin-api/src/main/java/org/sonar/api/batch/SquidUtils.java @@ -25,14 +25,16 @@ import org.sonar.api.resources.JavaPackage; public final class SquidUtils { + private static final String JAVA_FILE_SUFFIX = ".java"; + private SquidUtils() { // only static methods } public static JavaFile convertJavaFileKeyFromSquidFormat(String key) { - boolean isJavaFile = key.endsWith(".java"); + boolean isJavaFile = key.endsWith(JAVA_FILE_SUFFIX); if (isJavaFile) { - key = key.substring(0, key.length() - ".java".length()); + key = key.substring(0, key.length() - JAVA_FILE_SUFFIX.length()); } String convertedKey = key.replace('/', '.'); @@ -53,11 +55,11 @@ public final class SquidUtils { public static String convertToSquidKeyFormat(JavaFile file) { String key = file.getKey(); - if (file.getParent()==null || file.getParent().isDefault()) { + if (file.getParent() == null || file.getParent().isDefault()) { key = StringUtils.substringAfterLast(file.getKey(), "."); } else { key = StringUtils.replace(key, ".", "/"); } - return key + ".java"; + return key + JAVA_FILE_SUFFIX; } } diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/batch/maven/MavenPlugin.java b/sonar-plugin-api/src/main/java/org/sonar/api/batch/maven/MavenPlugin.java index f8217841cbf..fad61ba028e 100644 --- a/sonar-plugin-api/src/main/java/org/sonar/api/batch/maven/MavenPlugin.java +++ b/sonar-plugin-api/src/main/java/org/sonar/api/batch/maven/MavenPlugin.java @@ -37,6 +37,7 @@ import java.util.List; */ public class MavenPlugin { + private static final String CONFIGURATION_ELEMENT = "configuration"; private Plugin plugin; private Xpp3Dom configuration; @@ -49,7 +50,7 @@ public class MavenPlugin { this.plugin = plugin; this.configuration = (Xpp3Dom) plugin.getConfiguration(); if (this.configuration == null) { - configuration = new Xpp3Dom("configuration"); + configuration = new Xpp3Dom(CONFIGURATION_ELEMENT); plugin.setConfiguration(this.configuration); } } @@ -66,7 +67,7 @@ public class MavenPlugin { plugin.setGroupId(groupId); plugin.setArtifactId(artifactId); plugin.setVersion(version); - configuration = new Xpp3Dom("configuration"); + configuration = new Xpp3Dom(CONFIGURATION_ELEMENT); plugin.setConfiguration(this.configuration); } @@ -163,7 +164,7 @@ public class MavenPlugin { * Removes all parameters from the maven plugin */ public void removeParameters() { - configuration = new Xpp3Dom("configuration"); + configuration = new Xpp3Dom(CONFIGURATION_ELEMENT); plugin.setConfiguration(this.configuration); } @@ -200,7 +201,7 @@ public class MavenPlugin { } private static int getIndex(String key) { - //parsing index-syntax (e.g. item[1]) + // parsing index-syntax (e.g. item[1]) if (key.matches(".*?\\[\\d+\\]")) { return Integer.parseInt(StringUtils.substringBetween(key, "[", "]")); } @@ -231,7 +232,7 @@ public class MavenPlugin { Xpp3Dom node = configuration; for (String keyPart : keyParts) { - if(node.getChildren(removeIndexSnippet(keyPart)).length <= getIndex(keyPart)) { + if (node.getChildren(removeIndexSnippet(keyPart)).length <= getIndex(keyPart)) { return null; } @@ -258,7 +259,7 @@ public class MavenPlugin { * @return whether the maven plugin has got configuration */ public boolean hasConfiguration() { - return configuration.getChildCount()>0; + return configuration.getChildCount() > 0; } private static void checkKeyArgument(String key) { @@ -416,13 +417,12 @@ public class MavenPlugin { } } - @Override public String toString() { return new ToStringBuilder(this) - .append("groupId", plugin.getGroupId()) - .append("artifactId", plugin.getArtifactId()) - .append("version", plugin.getVersion()) - .toString(); + .append("groupId", plugin.getGroupId()) + .append("artifactId", plugin.getArtifactId()) + .append("version", plugin.getVersion()) + .toString(); } } diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/batch/maven/MavenUtils.java b/sonar-plugin-api/src/main/java/org/sonar/api/batch/maven/MavenUtils.java index 16806f1d7a6..3b4c9120f55 100644 --- a/sonar-plugin-api/src/main/java/org/sonar/api/batch/maven/MavenUtils.java +++ b/sonar-plugin-api/src/main/java/org/sonar/api/batch/maven/MavenUtils.java @@ -30,11 +30,12 @@ import java.util.Collection; /** * An utility class to manipulate Maven concepts - * + * * @since 1.10 */ public final class MavenUtils { + private static final String MAVEN_COMPILER_PLUGIN = "maven-compiler-plugin"; public static final String GROUP_ID_APACHE_MAVEN = "org.apache.maven.plugins"; public static final String GROUP_ID_CODEHAUS_MOJO = "org.codehaus.mojo"; @@ -44,12 +45,12 @@ public final class MavenUtils { /** * Returns the version of Java used by the maven compiler plugin - * + * * @param pom the project pom * @return the java version */ public static String getJavaVersion(MavenProject pom) { - MavenPlugin compilerPlugin = MavenPlugin.getPlugin(pom, GROUP_ID_APACHE_MAVEN, "maven-compiler-plugin"); + MavenPlugin compilerPlugin = MavenPlugin.getPlugin(pom, GROUP_ID_APACHE_MAVEN, MAVEN_COMPILER_PLUGIN); if (compilerPlugin != null) { return compilerPlugin.getParameter("target"); } @@ -57,7 +58,7 @@ public final class MavenUtils { } public static String getJavaSourceVersion(MavenProject pom) { - MavenPlugin compilerPlugin = MavenPlugin.getPlugin(pom, GROUP_ID_APACHE_MAVEN, "maven-compiler-plugin"); + MavenPlugin compilerPlugin = MavenPlugin.getPlugin(pom, GROUP_ID_APACHE_MAVEN, MAVEN_COMPILER_PLUGIN); if (compilerPlugin != null) { return compilerPlugin.getParameter("source"); } @@ -66,7 +67,7 @@ public final class MavenUtils { /** * Queries a collection of plugins based on a group id and an artifact id and returns the plugin if it exists - * + * * @param plugins the plugins collection * @param groupId the group id * @param artifactId the artifact id @@ -85,7 +86,7 @@ public final class MavenUtils { /** * Tests whether a plugin has got a given artifact id and group id - * + * * @param plugin the plugin to test * @param groupId the group id * @param artifactId the artifact id @@ -103,7 +104,7 @@ public final class MavenUtils { /** * Tests whether a ReportPlugin has got a given artifact id and group id - * + * * @param plugin the ReportPlugin to test * @param groupId the group id * @param artifactId the artifact id @@ -128,7 +129,7 @@ public final class MavenUtils { /** * Returns the charset of a pom - * + * * @param pom the project pom * @return the charset */ diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/checks/AnnotationCheckFactory.java b/sonar-plugin-api/src/main/java/org/sonar/api/checks/AnnotationCheckFactory.java index b231829e8f5..e706da53015 100644 --- a/sonar-plugin-api/src/main/java/org/sonar/api/checks/AnnotationCheckFactory.java +++ b/sonar-plugin-api/src/main/java/org/sonar/api/checks/AnnotationCheckFactory.java @@ -40,6 +40,7 @@ import java.util.Map; */ public final class AnnotationCheckFactory extends CheckFactory { + private static final String CAN_NOT_INSTANTIATE_THE_CHECK_RELATED_TO_THE_RULE = "Can not instantiate the check related to the rule "; private Map checksByKey = Maps.newHashMap(); private AnnotationCheckFactory(RulesProfile profile, String repositoryKey, Collection checks) { @@ -81,10 +82,10 @@ public final class AnnotationCheckFactory extends CheckFactory { return check; } catch (InstantiationException e) { - throw new SonarException("Can not instantiate the check related to the rule " + activeRule, e); + throw new SonarException(CAN_NOT_INSTANTIATE_THE_CHECK_RELATED_TO_THE_RULE + activeRule, e); } catch (IllegalAccessException e) { - throw new SonarException("Can not instantiate the check related to the rule " + activeRule, e); + throw new SonarException(CAN_NOT_INSTANTIATE_THE_CHECK_RELATED_TO_THE_RULE + activeRule, e); } } diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/measures/Measure.java b/sonar-plugin-api/src/main/java/org/sonar/api/measures/Measure.java index c08ad379867..f286c28790f 100644 --- a/sonar-plugin-api/src/main/java/org/sonar/api/measures/Measure.java +++ b/sonar-plugin-api/src/main/java/org/sonar/api/measures/Measure.java @@ -36,6 +36,8 @@ import java.util.Date; * @since 1.10 */ public class Measure { + private static final String INDEX_SHOULD_BE_IN_RANGE_FROM_1_TO_5 = "Index should be in range from 1 to 5"; + protected static final int MAX_TEXT_SIZE = 96; /** @@ -531,7 +533,7 @@ public class Measure { case 5: return variation5; default: - throw new IndexOutOfBoundsException("Index should be in range from 1 to 5"); + throw new IndexOutOfBoundsException(INDEX_SHOULD_BE_IN_RANGE_FROM_1_TO_5); } } @@ -558,7 +560,7 @@ public class Measure { variation5 = d; break; default: - throw new IndexOutOfBoundsException("Index should be in range from 1 to 5"); + throw new IndexOutOfBoundsException(INDEX_SHOULD_BE_IN_RANGE_FROM_1_TO_5); } return this; } diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/profiles/XMLProfileParser.java b/sonar-plugin-api/src/main/java/org/sonar/api/profiles/XMLProfileParser.java index 2a42997edf2..ea6f038e4f3 100644 --- a/sonar-plugin-api/src/main/java/org/sonar/api/profiles/XMLProfileParser.java +++ b/sonar-plugin-api/src/main/java/org/sonar/api/profiles/XMLProfileParser.java @@ -45,7 +45,7 @@ import java.util.Map; /** * TODO should be an interface - * + * * @since 2.3 */ public final class XMLProfileParser implements ServerComponent { @@ -55,7 +55,7 @@ public final class XMLProfileParser implements ServerComponent { /** * For backward compatibility. - * + * * @deprecated since 2.5. Plugins shouldn't directly instantiate this class, * because it should be retrieved as an IoC dependency. */ @@ -163,14 +163,13 @@ public final class XMLProfileParser implements ServerComponent { Rule rule = ruleFinder.findByKey(repositoryKey, key); if (rule == null) { - messages.addWarningText("Rule not found: [repository=" + repositoryKey + ", key=" + key + "]"); + messages.addWarningText("Rule not found: " + ruleToString(repositoryKey, key)); } else { ActiveRule activeRule = profile.activateRule(rule, priority); for (Map.Entry entry : parameters.entrySet()) { if (rule.getParam(entry.getKey()) == null) { - messages.addWarningText("The parameter '" + entry.getKey() + "' does not exist in the rule: [repository=" + repositoryKey - + ", key=" + key + "]"); + messages.addWarningText("The parameter '" + entry.getKey() + "' does not exist in the rule: " + ruleToString(repositoryKey, key)); } else { activeRule.setParameter(entry.getKey(), entry.getValue()); } @@ -179,6 +178,10 @@ public final class XMLProfileParser implements ServerComponent { } } + private String ruleToString(String repositoryKey, String key) { + return "[repository=" + repositoryKey + ", key=" + key + "]"; + } + private void processParameters(SMInputCursor propsCursor, Map parameters) throws XMLStreamException { while (propsCursor.getNext() != null) { SMInputCursor propCursor = propsCursor.childElementCursor(); @@ -222,7 +225,7 @@ public final class XMLProfileParser implements ServerComponent { if (StringUtils.isNotBlank(periodParameter)) { period = Integer.parseInt(periodParameter); } - }else if (StringUtils.equals("operator", nodeName)) { + } else if (StringUtils.equals("operator", nodeName)) { operator = StringUtils.trim(alertCursor.collectDescendantText(false)); } else if (StringUtils.equals("warning", nodeName)) { diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/resources/Project.java b/sonar-plugin-api/src/main/java/org/sonar/api/resources/Project.java index 0e93c6a00b8..68c9b62e7fb 100644 --- a/sonar-plugin-api/src/main/java/org/sonar/api/resources/Project.java +++ b/sonar-plugin-api/src/main/java/org/sonar/api/resources/Project.java @@ -34,11 +34,14 @@ import java.util.List; /** * A class that manipulates Projects in the Sonar way. - * + * * @since 1.10 */ public class Project extends Resource implements Component { + private static final String MAVEN_KEY_FORMAT = "%s:%s"; + private static final String BRANCH_KEY_FORMAT = "%s:%s"; + public static final String SCOPE = Scopes.PROJECT; /** @@ -86,7 +89,7 @@ public class Project extends Resource implements Component { public Project(String key, String branch, String name) { if (StringUtils.isNotBlank(branch)) { - setKey(String.format("%s:%s", key, branch)); + setKey(String.format(BRANCH_KEY_FORMAT, key, branch)); this.name = String.format("%s %s", name, branch); } else { setKey(key); @@ -158,7 +161,7 @@ public class Project extends Resource implements Component { /** * For internal use only. - * + * * @deprecated in 2.8. See http://jira.codehaus.org/browse/SONAR-2341 */ @Deprecated @@ -199,7 +202,7 @@ public class Project extends Resource implements Component { /** * whether it's the latest analysis done on this project (displayed in sonar dashboard) or an analysis on a past revision. - * + * * @since 2.0 * @deprecated in 3.6. The analysis is now always the latest one (past analysis must be done in a chronological order). See http://jira.codehaus.org/browse/SONAR-4334 */ @@ -396,7 +399,7 @@ public class Project extends Resource implements Component { /** * For internal use only. - * + * * @deprecated since 2.6. See http://jira.codehaus.org/browse/SONAR-2126 */ @Deprecated @@ -457,7 +460,7 @@ public class Project extends Resource implements Component { } public static Project createFromMavenIds(String groupId, String artifactId) { - return new Project(String.format("%s:%s", groupId, artifactId)); + return new Project(String.format(MAVEN_KEY_FORMAT, groupId, artifactId)); } @Override diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/resources/ResourceType.java b/sonar-plugin-api/src/main/java/org/sonar/api/resources/ResourceType.java index d5aa6d2e402..3d7f4f6b8fa 100644 --- a/sonar-plugin-api/src/main/java/org/sonar/api/resources/ResourceType.java +++ b/sonar-plugin-api/src/main/java/org/sonar/api/resources/ResourceType.java @@ -59,6 +59,7 @@ public class ResourceType { * Builder used to create {@link ResourceType} objects. */ public static class Builder { + private static final String SUPPORTS_MEASURE_FILTERS = "supportsMeasureFilters"; private String qualifier; private String iconPath; private boolean hasSourceCode = false; @@ -88,7 +89,7 @@ public class ResourceType { */ @Deprecated public Builder availableForFilters() { - setProperty("supportsMeasureFilters", "true"); + setProperty(SUPPORTS_MEASURE_FILTERS, "true"); return this; } @@ -112,7 +113,7 @@ public class ResourceType { // for backward-compatibility since version 3.4 if ("availableForFilters".equals(key)) { - properties.put("supportsMeasureFilters", value); + properties.put(SUPPORTS_MEASURE_FILTERS, value); } return this; } diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/rules/Rule.java b/sonar-plugin-api/src/main/java/org/sonar/api/rules/Rule.java index 02612902def..afa876940d6 100644 --- a/sonar-plugin-api/src/main/java/org/sonar/api/rules/Rule.java +++ b/sonar-plugin-api/src/main/java/org/sonar/api/rules/Rule.java @@ -34,7 +34,19 @@ import org.sonar.check.Cardinality; import javax.annotation.CheckForNull; import javax.annotation.Nullable; -import javax.persistence.*; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.EnumType; +import javax.persistence.Enumerated; +import javax.persistence.FetchType; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.ManyToOne; +import javax.persistence.OneToMany; +import javax.persistence.Table; +import javax.persistence.Temporal; +import javax.persistence.TemporalType; import java.util.ArrayList; import java.util.Date; @@ -70,7 +82,6 @@ public final class Rule { */ private static final Set STATUS_LIST = ImmutableSet.of(STATUS_READY, STATUS_BETA, STATUS_DEPRECATED, STATUS_REMOVED); - @Id @Column(name = "id") @GeneratedValue @@ -282,7 +293,7 @@ public final class Rule { } public Boolean isEnabled() { - return !"REMOVED".equals(status); + return !STATUS_REMOVED.equals(status); } public List getParams() { @@ -450,7 +461,6 @@ public final class Rule { return this; } - /** * @since 3.6 */ diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/rules/RulePriority.java b/sonar-plugin-api/src/main/java/org/sonar/api/rules/RulePriority.java index f62d342a0eb..faf640d4ac1 100644 --- a/sonar-plugin-api/src/main/java/org/sonar/api/rules/RulePriority.java +++ b/sonar-plugin-api/src/main/java/org/sonar/api/rules/RulePriority.java @@ -32,6 +32,9 @@ public enum RulePriority { */ INFO, MINOR, MAJOR, CRITICAL, BLOCKER; + private static final String UNKNOWN_PRIORITY = "Unknown priority "; + + /** * A class to map priority level prior to Sonar 1.10 to the new ones * @@ -52,7 +55,7 @@ public enum RulePriority { return RulePriority.INFO; } } - throw new IllegalArgumentException("Unknown priority " + level); + throw new IllegalArgumentException(UNKNOWN_PRIORITY + level); } @@ -72,6 +75,6 @@ public enum RulePriority { if (checkPriority == Priority.INFO) { return RulePriority.INFO; } - throw new IllegalArgumentException("Unknown priority " + checkPriority); + throw new IllegalArgumentException(UNKNOWN_PRIORITY + checkPriority); } -} \ No newline at end of file +} diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/utils/HttpDownloader.java b/sonar-plugin-api/src/main/java/org/sonar/api/utils/HttpDownloader.java index 00fa4c82678..bfcb689b2c7 100644 --- a/sonar-plugin-api/src/main/java/org/sonar/api/utils/HttpDownloader.java +++ b/sonar-plugin-api/src/main/java/org/sonar/api/utils/HttpDownloader.java @@ -143,9 +143,13 @@ public class HttpDownloader extends UriReader.SchemeProcessor implements BatchCo } public static class BaseHttpDownloader { + + private static final String HTTP_PROXY_USER = "http.proxyUser"; + private static final String HTTP_PROXY_PASSWORD = "http.proxyPassword"; + private static final List PROXY_SETTINGS = ImmutableList.of( - "http.proxyHost", "http.proxyPort", "http.nonProxyHosts", - "http.auth.ntlm.domain", "socksProxyHost", "socksProxyPort"); + "http.proxyHost", "http.proxyPort", "http.nonProxyHosts", + "http.auth.ntlm.domain", "socksProxyHost", "socksProxyPort"); private String userAgent; @@ -189,12 +193,12 @@ public class HttpDownloader extends UriReader.SchemeProcessor implements BatchCo private void registerProxyCredentials(Map settings) { Authenticator.setDefault(new ProxyAuthenticator( - settings.get("http.proxyUser"), - settings.get("http.proxyPassword"))); + settings.get(HTTP_PROXY_USER), + settings.get(HTTP_PROXY_PASSWORD))); } private boolean requiresProxyAuthentication(Map settings) { - return settings.containsKey("http.proxyUser"); + return settings.containsKey(HTTP_PROXY_USER); } private void propagateProxySystemProperties(Map settings) { diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/utils/TimeProfiler.java b/sonar-plugin-api/src/main/java/org/sonar/api/utils/TimeProfiler.java index 0b156cd2c48..d451aad884c 100644 --- a/sonar-plugin-api/src/main/java/org/sonar/api/utils/TimeProfiler.java +++ b/sonar-plugin-api/src/main/java/org/sonar/api/utils/TimeProfiler.java @@ -25,7 +25,7 @@ import org.slf4j.LoggerFactory; /** * A very simple profiler to log the time elapsed performing some tasks. * This implementation is not thread-safe. - * + * * @since 2.0 */ public class TimeProfiler { @@ -80,10 +80,11 @@ public class TimeProfiler { public TimeProfiler stop() { if (start > 0) { + String format = "{} done: {} ms"; if (debug) { - logger.debug("{} done: {} ms", name, System.currentTimeMillis() - start); + logger.debug(format, name, System.currentTimeMillis() - start); } else { - logger.info("{} done: {} ms", name, System.currentTimeMillis() - start); + logger.info(format, name, System.currentTimeMillis() - start); } } start = 0; diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/utils/XpathParser.java b/sonar-plugin-api/src/main/java/org/sonar/api/utils/XpathParser.java index 65487c327a3..f48cd8e450e 100644 --- a/sonar-plugin-api/src/main/java/org/sonar/api/utils/XpathParser.java +++ b/sonar-plugin-api/src/main/java/org/sonar/api/utils/XpathParser.java @@ -28,18 +28,29 @@ import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; -import java.io.*; +import javax.xml.namespace.QName; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.xpath.XPath; +import javax.xml.xpath.XPathConstants; +import javax.xml.xpath.XPathExpression; +import javax.xml.xpath.XPathExpressionException; +import javax.xml.xpath.XPathFactory; + +import java.io.BufferedReader; +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; -import javax.xml.namespace.QName; -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.xpath.*; /** * XML Parsing tool using XPATH. It's recommended to use StaxParser when parsing big XML files. @@ -48,6 +59,7 @@ import javax.xml.xpath.*; */ public class XpathParser { + private static final String CAN_NOT_PARSE_XML = "can not parse xml : "; private Element root = null; private Document doc = null; private DocumentBuilder builder; @@ -120,9 +132,9 @@ public class XpathParser { xpath = factory.newXPath(); } catch (SAXException e) { - throw new XmlParserException("can not parse xml : " + xml, e); + throw new XmlParserException(CAN_NOT_PARSE_XML + xml, e); } catch (IOException e) { - throw new XmlParserException("can not parse xml : " + xml, e); + throw new XmlParserException(CAN_NOT_PARSE_XML + xml, e); } } @@ -265,4 +277,4 @@ public class XpathParser { } return replace.toString(); } -} \ No newline at end of file +} diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/utils/ZipUtils.java b/sonar-plugin-api/src/main/java/org/sonar/api/utils/ZipUtils.java index 0b6dfae9842..e367fcc2435 100644 --- a/sonar-plugin-api/src/main/java/org/sonar/api/utils/ZipUtils.java +++ b/sonar-plugin-api/src/main/java/org/sonar/api/utils/ZipUtils.java @@ -39,6 +39,8 @@ import java.util.zip.ZipOutputStream; */ public final class ZipUtils { + private static final String ERROR_CREATING_DIRECTORY = "Error creating directory: "; + private ZipUtils() { // only static methods } @@ -86,12 +88,12 @@ public final class ZipUtils { File to = new File(toDir, entry.getName()); if (entry.isDirectory()) { if (!to.exists() && !to.mkdirs()) { - throw new IOException("Error creating directory: " + to); + throw new IOException(ERROR_CREATING_DIRECTORY + to); } } else { File parent = to.getParentFile(); if (parent != null && !parent.exists() && !parent.mkdirs()) { - throw new IOException("Error creating directory: " + parent); + throw new IOException(ERROR_CREATING_DIRECTORY + parent); } FileOutputStream fos = new FileOutputStream(to); diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/web/Criterion.java b/sonar-plugin-api/src/main/java/org/sonar/api/web/Criterion.java index a1e8cba29fa..1eaf10eb920 100644 --- a/sonar-plugin-api/src/main/java/org/sonar/api/web/Criterion.java +++ b/sonar-plugin-api/src/main/java/org/sonar/api/web/Criterion.java @@ -20,7 +20,6 @@ package org.sonar.api.web; import com.google.common.base.Joiner; - import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableSortedSet; @@ -32,6 +31,8 @@ import java.util.Set; * @since 3.1 */ public final class Criterion { + private static final String METRIC_FAMILY = "metric"; + private static final String QUALIFIER_FAMILY = "qualifier"; public static final String EQ = "eq"; public static final String GT = "gt"; public static final String GTE = "gte"; @@ -87,7 +88,7 @@ public final class Criterion { * @throws IllegalArgumentException if {@code operator} is not valid */ public static Criterion createForMetric(String key, String operator, Float value, boolean variation) { - return new Criterion("metric", key, operator, value, null, variation); + return new Criterion(METRIC_FAMILY, key, operator, value, null, variation); } /** @@ -98,19 +99,19 @@ public final class Criterion { * @throws IllegalArgumentException if {@code operator} is not valid */ public static Criterion createForMetric(String key, String operator, String textValue, boolean variation) { - return new Criterion("metric", key, operator, null, textValue, variation); + return new Criterion(METRIC_FAMILY, key, operator, null, textValue, variation); } /** * Creates a new {@link Criterion} on a qualifier. */ public static Criterion createForQualifier(Object... values) { - return new Criterion("qualifier", null, EQ, null, Joiner.on(',').join(values), false); + return new Criterion(QUALIFIER_FAMILY, null, EQ, null, Joiner.on(',').join(values), false); } /** * Get the the criterion's family. - * + * * @return the family */ public String getFamily() { @@ -119,7 +120,7 @@ public final class Criterion { /** * Get the the criterion's key. - * + * * @return the key */ public String getKey() { @@ -139,7 +140,7 @@ public final class Criterion { /** * Get the the criterion's value. - * + * * @return the value */ public Float getValue() { @@ -148,7 +149,7 @@ public final class Criterion { /** * Get the the criterion's value as text. - * + * * @return the value as text */ public String getTextValue() { @@ -157,7 +158,7 @@ public final class Criterion { /** * A criterion can be based on the varation of a value rather than on the value itself. - * + * * @return true when the variation is used rather than the value */ public boolean isVariation() { diff --git a/sonar-server/src/main/java/org/sonar/server/db/DatabaseMigrator.java b/sonar-server/src/main/java/org/sonar/server/db/DatabaseMigrator.java index f805b2de492..6b36e055134 100644 --- a/sonar-server/src/main/java/org/sonar/server/db/DatabaseMigrator.java +++ b/sonar-server/src/main/java/org/sonar/server/db/DatabaseMigrator.java @@ -73,14 +73,15 @@ public class DatabaseMigrator implements ServerComponent { public void executeMigration(String className) { try { - Class migrationClass = (Class)Class.forName(className); + Class migrationClass = (Class) Class.forName(className); DatabaseMigration migration = migrationClass.newInstance(); migration.execute(database); } catch (Exception e) { // duplication between log and exception because webapp does not correctly log initial stacktrace - LoggerFactory.getLogger(getClass()).error("Fail to execute database migration: " + className, e); - throw new IllegalStateException("Fail to execute database migration: " + className, e); + String msg = "Fail to execute database migration: " + className; + LoggerFactory.getLogger(getClass()).error(msg, e); + throw new IllegalStateException(msg, e); } } diff --git a/sonar-server/src/main/java/org/sonar/server/issue/ServerIssueStorage.java b/sonar-server/src/main/java/org/sonar/server/issue/ServerIssueStorage.java index 6c84ad9c2f0..4b77083ca3e 100644 --- a/sonar-server/src/main/java/org/sonar/server/issue/ServerIssueStorage.java +++ b/sonar-server/src/main/java/org/sonar/server/issue/ServerIssueStorage.java @@ -43,18 +43,20 @@ public class ServerIssueStorage extends IssueStorage implements ServerComponent @Override protected long componentId(DefaultIssue issue) { ResourceDto resourceDto = resourceDao.getResource(ResourceQuery.create().setKey(issue.componentKey())); - if (resourceDto == null) { - throw new IllegalStateException("Unknown component: " + issue.componentKey()); - } + validate(issue, resourceDto); return resourceDto.getId(); } @Override protected long projectId(DefaultIssue issue) { ResourceDto resourceDto = resourceDao.getRootProjectByComponentKey(issue.componentKey()); + validate(issue, resourceDto); + return resourceDto.getId(); + } + + private void validate(DefaultIssue issue, ResourceDto resourceDto) { if (resourceDto == null) { throw new IllegalStateException("Unknown component: " + issue.componentKey()); } - return resourceDto.getId(); } } -- 2.39.5