From d1e8b9e9c57728d36e703af5f6108d5f19883376 Mon Sep 17 00:00:00 2001 From: Julien Lancelot Date: Thu, 29 Aug 2013 14:11:01 +0200 Subject: [PATCH] Fix quality flaws --- .../batch/index/DefaultResourcePersister.java | 22 ++++-- .../org/sonar/batch/phases/PhaseExecutor.java | 22 +++--- .../core/measure/MeasureFilterFactory.java | 40 ++++++---- .../core/persistence/DefaultDatabase.java | 43 ++++++----- .../org/sonar/core/test/DefaultTestCase.java | 46 ++++++----- .../server/configuration/ProfilesBackup.java | 77 ++++++++++--------- .../server/configuration/RulesBackup.java | 65 +++++++++------- 7 files changed, 181 insertions(+), 134 deletions(-) diff --git a/sonar-batch/src/main/java/org/sonar/batch/index/DefaultResourcePersister.java b/sonar-batch/src/main/java/org/sonar/batch/index/DefaultResourcePersister.java index 636122f849a..ac2ad1c546c 100644 --- a/sonar-batch/src/main/java/org/sonar/batch/index/DefaultResourcePersister.java +++ b/sonar-batch/src/main/java/org/sonar/batch/index/DefaultResourcePersister.java @@ -39,6 +39,12 @@ import java.util.Map; public final class DefaultResourcePersister implements ResourcePersister { + private static final String RESOURCE_ID = "resourceId"; + private static final String LAST = "last"; + private static final String VERSION = "version"; + private static final String SCOPE = "scope"; + private static final String QUALIFIER = "qualifier"; + private final DatabaseSession session; private final Map snapshotsByResource = Maps.newHashMap(); private final ResourcePermissions permissions; @@ -182,14 +188,14 @@ public final class DefaultResourcePersister implements ResourcePersister { private Snapshot findLibrarySnapshot(Integer resourceId, String version) { Query query = session.createQuery("from " + Snapshot.class.getSimpleName() + " s WHERE s.resourceId=:resourceId AND s.version=:version AND s.scope=:scope AND s.qualifier<>:qualifier AND s.last=:last"); - query.setParameter("resourceId", resourceId); - query.setParameter("version", version); - query.setParameter("scope", Scopes.PROJECT); - query.setParameter("qualifier", Qualifiers.LIBRARY); - query.setParameter("last", Boolean.TRUE); + query.setParameter(RESOURCE_ID, resourceId); + query.setParameter(VERSION, version); + query.setParameter(SCOPE, Scopes.PROJECT); + query.setParameter(QUALIFIER, Qualifiers.LIBRARY); + query.setParameter(LAST, Boolean.TRUE); List snapshots = query.getResultList(); if (snapshots.isEmpty()) { - snapshots = session.getResults(Snapshot.class, "resourceId", resourceId, "version", version, "scope", Scopes.PROJECT, "qualifier", Qualifiers.LIBRARY); + snapshots = session.getResults(Snapshot.class, RESOURCE_ID, resourceId, VERSION, version, SCOPE, Scopes.PROJECT, QUALIFIER, Qualifiers.LIBRARY); } return snapshots.isEmpty() ? null : snapshots.get(0); } @@ -218,8 +224,8 @@ public final class DefaultResourcePersister implements ResourcePersister { hql += " AND s.createdAt<:date"; } Query query = session.createQuery(hql); - query.setParameter("last", true); - query.setParameter("resourceId", snapshot.getResourceId()); + query.setParameter(LAST, true); + query.setParameter(RESOURCE_ID, snapshot.getResourceId()); if (onlyOlder) { query.setParameter("date", snapshot.getCreatedAt()); } diff --git a/sonar-batch/src/main/java/org/sonar/batch/phases/PhaseExecutor.java b/sonar-batch/src/main/java/org/sonar/batch/phases/PhaseExecutor.java index 8b8dd93c7a9..940237ee1a3 100644 --- a/sonar-batch/src/main/java/org/sonar/batch/phases/PhaseExecutor.java +++ b/sonar-batch/src/main/java/org/sonar/batch/phases/PhaseExecutor.java @@ -118,9 +118,10 @@ public final class PhaseExecutor { decoratorsExecutor.execute(); } - eventBus.fireEvent(new BatchStepEvent("Save measures", true)); + String saveMeasures = "Save measures"; + eventBus.fireEvent(new BatchStepEvent(saveMeasures, true)); persistenceManager.dump(); - eventBus.fireEvent(new BatchStepEvent("Save measures", false)); + eventBus.fireEvent(new BatchStepEvent(saveMeasures, false)); persistenceManager.setDelayedMode(false); if (module.isRoot()) { @@ -138,19 +139,21 @@ public final class PhaseExecutor { private void executePersisters() { LOGGER.info("Store results in database"); - eventBus.fireEvent(new BatchStepEvent("Persisters", true)); + String persistersStep = "Persisters"; + eventBus.fireEvent(new BatchStepEvent(persistersStep, true)); for (ScanPersister persister : persisters) { LOGGER.debug("Execute {}", persister.getClass().getName()); persister.persist(); } - eventBus.fireEvent(new BatchStepEvent("Persisters", false)); + eventBus.fireEvent(new BatchStepEvent(persistersStep, false)); } private void updateStatusJob() { if (updateStatusJob != null) { - eventBus.fireEvent(new BatchStepEvent("Update status job", true)); - updateStatusJob.execute(); - eventBus.fireEvent(new BatchStepEvent("Update status job", false)); + String updateStatusJob = "Update status job"; + eventBus.fireEvent(new BatchStepEvent(updateStatusJob, true)); + this.updateStatusJob.execute(); + eventBus.fireEvent(new BatchStepEvent(updateStatusJob, false)); } } @@ -171,9 +174,10 @@ public final class PhaseExecutor { } private void cleanMemory() { - eventBus.fireEvent(new BatchStepEvent("Clean memory", true)); + String cleanMemory = "Clean memory"; + eventBus.fireEvent(new BatchStepEvent(cleanMemory, true)); persistenceManager.clear(); index.clear(); - eventBus.fireEvent(new BatchStepEvent("Clean memory", false)); + eventBus.fireEvent(new BatchStepEvent(cleanMemory, false)); } } diff --git a/sonar-core/src/main/java/org/sonar/core/measure/MeasureFilterFactory.java b/sonar-core/src/main/java/org/sonar/core/measure/MeasureFilterFactory.java index 1431b303019..f8737af80e0 100644 --- a/sonar-core/src/main/java/org/sonar/core/measure/MeasureFilterFactory.java +++ b/sonar-core/src/main/java/org/sonar/core/measure/MeasureFilterFactory.java @@ -43,10 +43,12 @@ public class MeasureFilterFactory implements ServerComponent { } public MeasureFilter create(Map properties) { + MeasureFilter filter = new MeasureFilter(); filter.setBaseResourceKey((String) properties.get("base")); - if (properties.containsKey("baseId")) { - filter.setBaseResourceId(Long.valueOf((String) properties.get("baseId"))); + String baseId = "baseId"; + if (properties.containsKey(baseId)) { + filter.setBaseResourceId(Long.valueOf((String) properties.get(baseId))); } filter.setResourceScopes(toList(properties.get("scopes"))); filter.setResourceQualifiers(toList(properties.get("qualifiers"))); @@ -55,13 +57,15 @@ public class MeasureFilterFactory implements ServerComponent { if (condition != null) { filter.addCondition(condition); } - if (properties.containsKey("onBaseComponents")) { - filter.setOnBaseResourceChildren(Boolean.valueOf((String) properties.get("onBaseComponents"))); + String onBaseComponents = "onBaseComponents"; + if (properties.containsKey(onBaseComponents)) { + filter.setOnBaseResourceChildren(Boolean.valueOf((String) properties.get(onBaseComponents))); } filter.setResourceName((String) properties.get("nameSearch")); filter.setResourceKeyRegexp((String) properties.get("keyRegexp")); - if (properties.containsKey("onFavourites")) { - filter.setUserFavourites(Boolean.valueOf((String) properties.get("onFavourites"))); + String onFavourites = "onFavourites"; + if (properties.containsKey(onFavourites)) { + filter.setUserFavourites(Boolean.valueOf((String) properties.get(onFavourites))); } fillDateConditions(filter, properties); fillSorting(filter, properties); @@ -70,15 +74,23 @@ public class MeasureFilterFactory implements ServerComponent { } private void fillDateConditions(MeasureFilter filter, Map properties) { - if (properties.containsKey("fromDate")) { - filter.setFromDate(toDate((String) properties.get("fromDate"))); - } else if (properties.containsKey("ageMaxDays")) { - filter.setFromDate(toDays((String) properties.get("ageMaxDays"))); + String fromDate = "fromDate"; + if (properties.containsKey(fromDate)) { + filter.setFromDate(toDate((String) properties.get(fromDate))); + } else { + String ageMaxDays = "ageMaxDays"; + if (properties.containsKey(ageMaxDays)) { + filter.setFromDate(toDays((String) properties.get(ageMaxDays))); + } } - if (properties.containsKey("toDate")) { - filter.setToDate(toDate((String) properties.get("toDate"))); - } else if (properties.containsKey("ageMinDays")) { - filter.setToDate(toDays((String) properties.get("ageMinDays"))); + String toDate = "toDate"; + if (properties.containsKey(toDate)) { + filter.setToDate(toDate((String) properties.get(toDate))); + } else { + String ageMinDays = "ageMinDays"; + if (properties.containsKey(ageMinDays)) { + filter.setToDate(toDays((String) properties.get(ageMinDays))); + } } } diff --git a/sonar-core/src/main/java/org/sonar/core/persistence/DefaultDatabase.java b/sonar-core/src/main/java/org/sonar/core/persistence/DefaultDatabase.java index 5d0752f0d4d..202deabe441 100644 --- a/sonar-core/src/main/java/org/sonar/core/persistence/DefaultDatabase.java +++ b/sonar-core/src/main/java/org/sonar/core/persistence/DefaultDatabase.java @@ -30,11 +30,7 @@ import org.slf4j.LoggerFactory; import org.sonar.api.CoreProperties; import org.sonar.api.config.Settings; import org.sonar.api.database.DatabaseProperties; -import org.sonar.core.persistence.dialect.Dialect; -import org.sonar.core.persistence.dialect.DialectUtils; -import org.sonar.core.persistence.dialect.H2; -import org.sonar.core.persistence.dialect.Oracle; -import org.sonar.core.persistence.dialect.PostgreSql; +import org.sonar.core.persistence.dialect.*; import org.sonar.jpa.session.CustomHibernateConnectionProvider; import javax.sql.DataSource; @@ -53,6 +49,13 @@ public class DefaultDatabase implements Database { private static final Logger LOG = LoggerFactory.getLogger(Database.class); private static final String DEFAULT_URL = "jdbc:h2:tcp://localhost/sonar"; + private static final String SONAR_JDBC = "sonar.jdbc."; + private static final String SONAR_HIBERNATE = "sonar.hibernate."; + private static final String SONAR_JDBC_DIALECT = "sonar.jdbc.dialect"; + private static final String SONAR_JDBC_URL = "sonar.jdbc.url"; + private static final String SONAR_JDBC_DRIVER_CLASS_NAME = "sonar.jdbc.driverClassName"; + private static final String SONAR_JDBC_SCHEMA = "sonar.jdbc.schema"; + private static final String VALIDATE = "validate"; private Settings settings; private BasicDataSource datasource; @@ -92,22 +95,22 @@ public class DefaultDatabase implements Database { private void initProperties() { properties = new Properties(); - completeProperties(settings, properties, "sonar.jdbc."); - completeProperties(settings, properties, "sonar.hibernate."); + completeProperties(settings, properties, SONAR_JDBC); + completeProperties(settings, properties, SONAR_HIBERNATE); completeDefaultProperties(properties); doCompleteProperties(properties); } private void initDialect() { - dialect = DialectUtils.find(properties.getProperty("sonar.jdbc.dialect"), properties.getProperty("sonar.jdbc.url")); + dialect = DialectUtils.find(properties.getProperty(SONAR_JDBC_DIALECT), properties.getProperty(SONAR_JDBC_URL)); if (dialect == null) { - throw new IllegalStateException("Can not guess the JDBC dialect. Please check the property sonar.jdbc.url."); + throw new IllegalStateException("Can not guess the JDBC dialect. Please check the property "+ SONAR_JDBC_URL + "."); } if (H2.ID.equals(dialect.getId()) && !settings.getBoolean(CoreProperties.DRY_RUN)) { LoggerFactory.getLogger(DefaultDatabase.class).warn("H2 database should be used for evaluation purpose only"); } - if (!properties.containsKey("sonar.jdbc.driverClassName")) { - properties.setProperty("sonar.jdbc.driverClassName", dialect.getDefaultDriverClassName()); + if (!properties.containsKey(SONAR_JDBC_DRIVER_CLASS_NAME)) { + properties.setProperty(SONAR_JDBC_DRIVER_CLASS_NAME, dialect.getDefaultDriverClassName()); } } @@ -122,7 +125,7 @@ public class DefaultDatabase implements Database { deprecatedSchema = getSchemaPropertyValue(properties, "sonar.hibernate.default_schema"); } if (StringUtils.isNotBlank(deprecatedSchema)) { - properties.setProperty("sonar.jdbc.schema", deprecatedSchema); + properties.setProperty(SONAR_JDBC_SCHEMA, deprecatedSchema); } } @@ -162,19 +165,19 @@ public class DefaultDatabase implements Database { } public final String getSchema() { - return properties.getProperty("sonar.jdbc.schema"); + return properties.getProperty(SONAR_JDBC_SCHEMA); } public Properties getHibernateProperties() { Properties props = new Properties(); - List hibernateKeys = settings.getKeysStartingWith("sonar.hibernate."); + List hibernateKeys = settings.getKeysStartingWith(SONAR_HIBERNATE); for (String hibernateKey : hibernateKeys) { props.put(StringUtils.removeStart(hibernateKey, "sonar."), settings.getString(hibernateKey)); } props.put(Environment.DIALECT, getDialect().getHibernateDialectClass().getName()); props.put("hibernate.generate_statistics", settings.getBoolean(DatabaseProperties.PROP_HIBERNATE_GENERATE_STATISTICS)); - props.put("hibernate.hbm2ddl.auto", "validate"); + props.put("hibernate.hbm2ddl.auto", VALIDATE); props.put(Environment.CONNECTION_PROVIDER, CustomHibernateConnectionProvider.class.getName()); String schema = getSchema(); @@ -209,8 +212,8 @@ public class DefaultDatabase implements Database { Properties result = new Properties(); for (Map.Entry entry : properties.entrySet()) { String key = (String) entry.getKey(); - if (StringUtils.startsWith(key, "sonar.jdbc.")) { - result.setProperty(StringUtils.removeStart(key, "sonar.jdbc."), (String) entry.getValue()); + if (StringUtils.startsWith(key, SONAR_JDBC)) { + result.setProperty(StringUtils.removeStart(key, SONAR_JDBC), (String) entry.getValue()); } } @@ -221,7 +224,7 @@ public class DefaultDatabase implements Database { } private static String getSchemaPropertyValue(Properties props, String deprecatedKey) { - String value = props.getProperty("sonar.jdbc.schema"); + String value = props.getProperty(SONAR_JDBC_SCHEMA); if (StringUtils.isBlank(value) && deprecatedKey != null) { value = props.getProperty(deprecatedKey); } @@ -233,7 +236,7 @@ public class DefaultDatabase implements Database { completeDefaultProperty(props, DatabaseProperties.PROP_URL, DEFAULT_URL); completeDefaultProperty(props, DatabaseProperties.PROP_USER, props.getProperty(DatabaseProperties.PROP_USER_DEPRECATED, DatabaseProperties.PROP_USER_DEFAULT_VALUE)); completeDefaultProperty(props, DatabaseProperties.PROP_PASSWORD, DatabaseProperties.PROP_PASSWORD_DEFAULT_VALUE); - completeDefaultProperty(props, DatabaseProperties.PROP_HIBERNATE_HBM2DLL, "validate"); + completeDefaultProperty(props, DatabaseProperties.PROP_HIBERNATE_HBM2DLL, VALIDATE); } private static void completeDefaultProperty(Properties props, String key, String defaultValue) { @@ -244,6 +247,6 @@ public class DefaultDatabase implements Database { @Override public String toString() { - return "Database[" + properties.getProperty("sonar.jdbc.url") + "]"; + return "Database[" + properties.getProperty(SONAR_JDBC_URL) + "]"; } } diff --git a/sonar-core/src/main/java/org/sonar/core/test/DefaultTestCase.java b/sonar-core/src/main/java/org/sonar/core/test/DefaultTestCase.java index 30f58a73e11..593ea670fed 100644 --- a/sonar-core/src/main/java/org/sonar/core/test/DefaultTestCase.java +++ b/sonar-core/src/main/java/org/sonar/core/test/DefaultTestCase.java @@ -39,60 +39,70 @@ import java.util.List; public class DefaultTestCase extends BeanVertex implements MutableTestCase { + private static final String DURATION = "duration"; + private static final String TYPE = "type"; + private static final String STATUS = "status"; + private static final String NAME = "name"; + private static final String MESSAGE = "message"; + private static final String STACK_TRACE = "stackTrace"; + private static final String COVERS = "covers"; + private static final String LINES = "lines"; + private static final String TESTCASE = "testcase"; + public String type() { - return (String) getProperty("type"); + return (String) getProperty(TYPE); } public MutableTestCase setType(@Nullable String s) { - setProperty("type", s); + setProperty(TYPE, s); return this; } public Long durationInMs() { - return (Long) getProperty("duration"); + return (Long) getProperty(DURATION); } public MutableTestCase setDurationInMs(@Nullable Long l) { if (l != null && l < 0) { throw new IllegalDurationException("Test duration must be positive (got: " + l + ")"); } - setProperty("duration", l); + setProperty(DURATION, l); return this; } public Status status() { - return Status.of((String) getProperty("status")); + return Status.of((String) getProperty(STATUS)); } public MutableTestCase setStatus(@Nullable Status s) { - setProperty("status", s == null ? null : s.name()); + setProperty(STATUS, s == null ? null : s.name()); return this; } public String name() { - return (String) getProperty("name"); + return (String) getProperty(NAME); } public MutableTestCase setName(String s) { - setProperty("name", s); + setProperty(NAME, s); return this; } public String message() { - return (String) getProperty("message"); + return (String) getProperty(MESSAGE); } public MutableTestCase setMessage(String s) { - setProperty("message", s); + setProperty(MESSAGE, s); return this; } public String stackTrace() { - return (String) getProperty("stackTrace"); + return (String) getProperty(STACK_TRACE); } public MutableTestCase setStackTrace(String s) { - setProperty("stackTrace", s); + setProperty(STACK_TRACE, s); return this; } @@ -100,12 +110,12 @@ public class DefaultTestCase extends BeanVertex implements MutableTestCase { if (coverageBlock(testable) != null) { throw new CoverageAlreadyExistsException("The link between " + name() + " and " + testable.component().key() + " already exists"); } - beanGraph().getUnderlyingGraph().addEdge(null, element(), ((BeanVertex) testable).element(), "covers").setProperty("lines", lines); + beanGraph().getUnderlyingGraph().addEdge(null, element(), ((BeanVertex) testable).element(), COVERS).setProperty(LINES, lines); return this; } public TestPlan testPlan() { - Vertex plan = GraphUtil.singleAdjacent(element(), Direction.IN, "testcase"); + Vertex plan = GraphUtil.singleAdjacent(element(), Direction.IN, TESTCASE); return beanGraph().wrap(plan, DefaultTestPlan.class); } @@ -116,18 +126,18 @@ public class DefaultTestCase extends BeanVertex implements MutableTestCase { public int countCoveredLines() { int result = 0; for (Edge edge : edgeCovers()) { - List lines = (List) edge.getProperty("lines"); + List lines = (List) edge.getProperty(LINES); result = result + lines.size(); } return result; } public Iterable coverageBlocks() { - return (Iterable) getEdges(DefaultCoverageBlock.class, Direction.OUT, "covers"); + return (Iterable) getEdges(DefaultCoverageBlock.class, Direction.OUT, COVERS); } public CoverageBlock coverageBlock(final Testable testable) { - return Iterables.find(getEdges(DefaultCoverageBlock.class, Direction.OUT, "covers"), new Predicate() { + return Iterables.find(getEdges(DefaultCoverageBlock.class, Direction.OUT, COVERS), new Predicate() { public boolean apply(CoverageBlock input) { return input.testable().component().key().equals(testable.component().key()); } @@ -135,7 +145,7 @@ public class DefaultTestCase extends BeanVertex implements MutableTestCase { } private Iterable edgeCovers() { - return element().query().labels("covers").direction(Direction.OUT).edges(); + return element().query().labels(COVERS).direction(Direction.OUT).edges(); } } diff --git a/sonar-server/src/main/java/org/sonar/server/configuration/ProfilesBackup.java b/sonar-server/src/main/java/org/sonar/server/configuration/ProfilesBackup.java index 86eccc26b46..4237dca8025 100644 --- a/sonar-server/src/main/java/org/sonar/server/configuration/ProfilesBackup.java +++ b/sonar-server/src/main/java/org/sonar/server/configuration/ProfilesBackup.java @@ -31,22 +31,25 @@ import org.sonar.api.database.DatabaseSession; import org.sonar.api.measures.Metric; import org.sonar.api.profiles.Alert; import org.sonar.api.profiles.RulesProfile; -import org.sonar.api.rules.ActiveRule; -import org.sonar.api.rules.ActiveRuleParam; -import org.sonar.api.rules.Rule; -import org.sonar.api.rules.RuleParam; -import org.sonar.api.rules.RulePriority; +import org.sonar.api.rules.*; import org.sonar.jpa.dao.RulesDao; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; +import java.util.*; public class ProfilesBackup implements Backupable { + private static final String OPERATOR = "operator"; + private static final String VALUE_ERROR = "value-error"; + private static final String VALUE_WARNING = "value-warning"; + private static final String PERIOD = "period"; + private static final String METRIC_KEY = "metric-key"; + private static final String KEY = "key"; + private static final String PLUGIN = "plugin"; + private static final String LEVEL = "level"; + private static final String INHERITANCE = "inheritance"; + private static final String PARAMS = "params"; + private static final String VALUE = "value"; + private Collection profiles; private DatabaseSession session; @@ -62,15 +65,17 @@ public class ProfilesBackup implements Backupable { } public void configure(XStream xStream) { + String defaultProfile = "defaultProfile"; + xStream.alias("profile", RulesProfile.class); xStream.alias("alert", Alert.class); xStream.alias("active-rule", ActiveRule.class); xStream.aliasField("active-rules", RulesProfile.class, "activeRules"); - xStream.aliasField("default-profile", RulesProfile.class, "defaultProfile"); + xStream.aliasField("default-profile", RulesProfile.class, defaultProfile); xStream.omitField(RulesProfile.class, "id"); xStream.omitField(RulesProfile.class, "projects"); xStream.omitField(RulesProfile.class, "provided"); - xStream.omitField(RulesProfile.class, "defaultProfile"); + xStream.omitField(RulesProfile.class, defaultProfile); xStream.omitField(RulesProfile.class, "enabled"); xStream.registerConverter(getActiveRuleConverter()); xStream.registerConverter(getAlertsConverter()); @@ -121,7 +126,7 @@ public class ProfilesBackup implements Backupable { Alert alert = ia.next(); Metric unMarshalledMetric = alert.getMetric(); String validKey = unMarshalledMetric.getKey(); - Metric matchingMetricInDb = session.getSingleResult(Metric.class, "key", validKey); + Metric matchingMetricInDb = session.getSingleResult(Metric.class, KEY, validKey); if (matchingMetricInDb == null) { LoggerFactory.getLogger(getClass()).error("Unable to find metric " + validKey); ia.remove(); @@ -167,20 +172,20 @@ public class ProfilesBackup implements Backupable { public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) { Alert alert = (Alert) source; - writeNode(writer, "operator", alert.getOperator()); - writeNode(writer, "value-error", alert.getValueError()); - writeNode(writer, "value-warning", alert.getValueWarning()); + writeNode(writer, OPERATOR, alert.getOperator()); + writeNode(writer, VALUE_ERROR, alert.getValueError()); + writeNode(writer, VALUE_WARNING, alert.getValueWarning()); if (alert.getPeriod() != null) { - writeNode(writer, "period", Integer.toString(alert.getPeriod())); + writeNode(writer, PERIOD, Integer.toString(alert.getPeriod())); } - writeNode(writer, "metric-key", alert.getMetric().getKey()); + writeNode(writer, METRIC_KEY, alert.getMetric().getKey()); } public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) { Map values = readNode(reader); - Alert alert = new Alert(null, new Metric(values.get("metric-key")), values.get("operator"), values.get("value-error"), - values.get("value-warning")); - String periodText = values.get("period"); + Alert alert = new Alert(null, new Metric(values.get(METRIC_KEY)), values.get(OPERATOR), values.get(VALUE_ERROR), + values.get(VALUE_WARNING)); + String periodText = values.get(PERIOD); if (StringUtils.isNotEmpty(periodText)) { alert.setPeriod(Integer.parseInt(periodText)); } @@ -198,17 +203,17 @@ public class ProfilesBackup implements Backupable { public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) { ActiveRule rule = (ActiveRule) source; - writeNode(writer, "key", rule.getRule().getKey()); - writeNode(writer, "plugin", rule.getRule().getRepositoryKey()); - writeNode(writer, "level", rule.getSeverity().name()); - writeNode(writer, "inheritance", rule.getInheritance()); + writeNode(writer, KEY, rule.getRule().getKey()); + writeNode(writer, PLUGIN, rule.getRule().getRepositoryKey()); + writeNode(writer, LEVEL, rule.getSeverity().name()); + writeNode(writer, INHERITANCE, rule.getInheritance()); if (!rule.getActiveRuleParams().isEmpty()) { - writer.startNode("params"); + writer.startNode(PARAMS); for (ActiveRuleParam activeRuleParam : rule.getActiveRuleParams()) { writer.startNode("param"); - writeNode(writer, "key", activeRuleParam.getRuleParam().getKey()); - writeNode(writer, "value", activeRuleParam.getValue()); + writeNode(writer, KEY, activeRuleParam.getRuleParam().getKey()); + writeNode(writer, VALUE, activeRuleParam.getValue()); writer.endNode(); } writer.endNode(); @@ -221,12 +226,12 @@ public class ProfilesBackup implements Backupable { while (reader.hasMoreChildren()) { reader.moveDown(); valuesRule.put(reader.getNodeName(), reader.getValue()); - if ("params".equals(reader.getNodeName())) { + if (PARAMS.equals(reader.getNodeName())) { while (reader.hasMoreChildren()) { reader.moveDown(); Map valuesParam = readNode(reader); - ActiveRuleParam activeRuleParam = new ActiveRuleParam(null, new RuleParam(null, valuesParam.get("key"), null, null), - valuesParam.get("value")); + ActiveRuleParam activeRuleParam = new ActiveRuleParam(null, new RuleParam(null, valuesParam.get(KEY), null, null), + valuesParam.get(VALUE)); params.add(activeRuleParam); reader.moveUp(); } @@ -234,11 +239,11 @@ public class ProfilesBackup implements Backupable { reader.moveUp(); } - ActiveRule activeRule = new ActiveRule(null, new Rule(valuesRule.get("plugin"), valuesRule.get("key")), RulePriority - .valueOf(valuesRule.get("level"))); + ActiveRule activeRule = new ActiveRule(null, new Rule(valuesRule.get(PLUGIN), valuesRule.get(KEY)), RulePriority + .valueOf(valuesRule.get(LEVEL))); activeRule.setActiveRuleParams(params); - if (valuesRule.containsKey("inheritance")) { - activeRule.setInheritance(valuesRule.get("inheritance")); + if (valuesRule.containsKey(INHERITANCE)) { + activeRule.setInheritance(valuesRule.get(INHERITANCE)); } return activeRule; } diff --git a/sonar-server/src/main/java/org/sonar/server/configuration/RulesBackup.java b/sonar-server/src/main/java/org/sonar/server/configuration/RulesBackup.java index 7e905f1672c..f2cc6061024 100644 --- a/sonar-server/src/main/java/org/sonar/server/configuration/RulesBackup.java +++ b/sonar-server/src/main/java/org/sonar/server/configuration/RulesBackup.java @@ -33,14 +33,21 @@ import org.sonar.api.rules.RuleParam; import org.sonar.api.rules.RulePriority; import org.sonar.jpa.dao.RulesDao; -import java.util.Collection; -import java.util.Date; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; +import java.util.*; public class RulesBackup implements Backupable { + + private static final String PARENT_REPOSITORY_KEY = "parentRepositoryKey"; + private static final String PARENT_KEY = "parentKey"; + private static final String REPOSITORY_KEY = "repositoryKey"; + private static final String KEY = "key"; + private static final String CONFIG_KEY = "configKey"; + private static final String LEVEL = "level"; + private static final String NAME = "name"; + private static final String DESCRIPTION = "description"; + private static final String PARAMS = "params"; + private static final String VALUE = "value"; + private Collection rules; private RulesDao rulesDao; private DatabaseSession session; @@ -112,7 +119,7 @@ public class RulesBackup implements Backupable { rule.setLanguage(matchingParentRuleInDb.getLanguage()); Rule matchingRuleInDb = session.getSingleResult(Rule.class, "pluginName", rule.getRepositoryKey(), - "key", rule.getKey()); + KEY, rule.getKey()); if (matchingRuleInDb != null) { // merge matchingRuleInDb.setParent(matchingParentRuleInDb); @@ -138,21 +145,21 @@ public class RulesBackup implements Backupable { xStream.registerConverter(new Converter() { public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) { Rule rule = (Rule) source; - writeNode(writer, "parentRepositoryKey", rule.getParent().getRepositoryKey()); - writeNode(writer, "parentKey", rule.getParent().getKey()); - writeNode(writer, "repositoryKey", rule.getRepositoryKey()); - writeNode(writer, "key", rule.getKey()); - writeNode(writer, "configKey", rule.getConfigKey()); - writeNode(writer, "level", rule.getSeverity().name()); - writeNode(writer, "name", rule.getName()); - writeNode(writer, "description", rule.getDescription()); + writeNode(writer, PARENT_REPOSITORY_KEY, rule.getParent().getRepositoryKey()); + writeNode(writer, PARENT_KEY, rule.getParent().getKey()); + writeNode(writer, REPOSITORY_KEY, rule.getRepositoryKey()); + writeNode(writer, KEY, rule.getKey()); + writeNode(writer, CONFIG_KEY, rule.getConfigKey()); + writeNode(writer, LEVEL, rule.getSeverity().name()); + writeNode(writer, NAME, rule.getName()); + writeNode(writer, DESCRIPTION, rule.getDescription()); if (!rule.getParams().isEmpty()) { - writer.startNode("params"); + writer.startNode(PARAMS); for (RuleParam ruleParam : rule.getParams()) { writer.startNode("param"); - writeNode(writer, "key", ruleParam.getKey()); - writeNode(writer, "value", ruleParam.getDefaultValue()); + writeNode(writer, KEY, ruleParam.getKey()); + writeNode(writer, VALUE, ruleParam.getDefaultValue()); writer.endNode(); } writer.endNode(); @@ -166,13 +173,13 @@ public class RulesBackup implements Backupable { while (reader.hasMoreChildren()) { reader.moveDown(); valuesRule.put(reader.getNodeName(), reader.getValue()); - if ("params".equals(reader.getNodeName())) { + if (PARAMS.equals(reader.getNodeName())) { while (reader.hasMoreChildren()) { reader.moveDown(); Map valuesParam = readNode(reader); rule.createParameter() - .setKey(valuesParam.get("key")) - .setDefaultValue(valuesParam.get("value")); + .setKey(valuesParam.get(KEY)) + .setDefaultValue(valuesParam.get(VALUE)); reader.moveUp(); } } @@ -180,15 +187,15 @@ public class RulesBackup implements Backupable { } Rule parent = Rule.create() - .setRepositoryKey(valuesRule.get("parentRepositoryKey")) - .setKey(valuesRule.get("parentKey")); + .setRepositoryKey(valuesRule.get(PARENT_REPOSITORY_KEY)) + .setKey(valuesRule.get(PARENT_KEY)); rule.setParent(parent) - .setRepositoryKey(valuesRule.get("repositoryKey")) - .setKey(valuesRule.get("key")) - .setConfigKey(valuesRule.get("configKey")) - .setName(valuesRule.get("name")) - .setDescription(valuesRule.get("description")) - .setSeverity(RulePriority.valueOf(valuesRule.get("level"))); + .setRepositoryKey(valuesRule.get(REPOSITORY_KEY)) + .setKey(valuesRule.get(KEY)) + .setConfigKey(valuesRule.get(CONFIG_KEY)) + .setName(valuesRule.get(NAME)) + .setDescription(valuesRule.get(DESCRIPTION)) + .setSeverity(RulePriority.valueOf(valuesRule.get(LEVEL))); return rule; } -- 2.39.5