]> source.dussan.org Git - sonarqube.git/commitdiff
Fix Quality flaws
authorSimon Brandhof <simon.brandhof@sonarsource.com>
Mon, 2 Jan 2017 15:49:02 +0000 (16:49 +0100)
committerSimon Brandhof <simon.brandhof@sonarsource.com>
Mon, 2 Jan 2017 15:49:02 +0000 (16:49 +0100)
Signed-off-by: Simon Brandhof <simon.brandhof@sonarsource.com>
server/sonar-search/src/main/java/org/sonar/search/EsSettings.java
server/sonar-server/src/main/java/org/sonar/server/computation/task/projectanalysis/api/measurecomputer/MeasureImpl.java
server/sonar-server/src/main/java/org/sonar/server/computation/task/projectanalysis/api/posttask/ConditionImpl.java
server/sonar-server/src/main/java/org/sonar/server/computation/task/projectanalysis/component/MapBasedDbIdsRepository.java
server/sonar-server/src/main/java/org/sonar/server/computation/task/projectanalysis/measure/MeasureVariations.java
server/sonar-server/src/main/java/org/sonar/server/computation/task/projectanalysis/period/PeriodsHolderImpl.java
server/sonar-server/src/main/java/org/sonar/server/computation/task/projectanalysis/scm/DbScmInfo.java
server/sonar-server/src/main/java/org/sonar/server/computation/task/projectanalysis/source/SourceLinesRepositoryImpl.java
server/sonar-server/src/main/java/org/sonar/server/computation/task/projectanalysis/step/LoadMeasureComputersStep.java
sonar-plugin-api/src/main/java/org/sonar/api/batch/sensor/coverage/internal/DefaultCoverage.java
sonar-plugin-api/src/main/java/org/sonar/api/server/rule/RulesDefinition.java

index 5736ecd771f73bd2a2b4fd96f3765448ee7386d0..03c430b1e07358e481bdbef00633e9ff2f29e23e 100644 (file)
@@ -183,7 +183,7 @@ public class EsSettings implements EsSettingsMBean {
     // If we're collecting indexing data send them to the Marvel host(s)
     if (!marvels.isEmpty()) {
       String hosts = StringUtils.join(marvels, ",");
-      LOGGER.info(String.format("Elasticsearch Marvel is enabled for %s", hosts));
+      LOGGER.info("Elasticsearch Marvel is enabled for %s", hosts);
       builder.put("marvel.agent.exporter.es.hosts", hosts);
     }
   }
index f4be39250885458163dc0c84647c8d73e7dca9c3..27cc2b08678c410c66da24640dd4da19d2d5c674 100644 (file)
@@ -25,6 +25,7 @@ import javax.annotation.concurrent.Immutable;
 import org.sonar.api.ce.measure.Measure;
 
 import static com.google.common.base.Preconditions.checkState;
+import static java.lang.String.format;
 import static java.util.Objects.requireNonNull;
 import static org.sonar.server.computation.task.projectanalysis.measure.Measure.ValueType.BOOLEAN;
 import static org.sonar.server.computation.task.projectanalysis.measure.Measure.ValueType.DOUBLE;
@@ -41,7 +42,7 @@ public class MeasureImpl implements Measure {
 
   public MeasureImpl(org.sonar.server.computation.task.projectanalysis.measure.Measure measure) {
     this.measure = requireNonNull(measure, "Measure couldn't be null");
-    checkState(ALLOWED_VALUE_TYPES.contains(measure.getValueType()), String.format("Only following types are allowed %s", ALLOWED_VALUE_TYPES));
+    checkState(ALLOWED_VALUE_TYPES.contains(measure.getValueType()), "Only following types are allowed %s", ALLOWED_VALUE_TYPES);
   }
 
   @Override
@@ -75,10 +76,11 @@ public class MeasureImpl implements Measure {
   }
 
   private void checkValueType(org.sonar.server.computation.task.projectanalysis.measure.Measure.ValueType expected) {
-    checkState(measure.getValueType() == expected, String.format(
-      "Value can not be converted to %s because current value type is a %s",
-      expected.toString().toLowerCase(Locale.US),
-      measure.getValueType()));
+    if (measure.getValueType() != expected) {
+      throw new IllegalStateException(format("Value can not be converted to %s because current value type is a %s",
+        expected.toString().toLowerCase(Locale.US),
+        measure.getValueType()));
+    }
   }
 
   @Override
index 78ef18aebf8cc73a99596902f2fdbe87e9146ea0..3454df3e6b840b631494aad93476b6280c1a7124 100644 (file)
@@ -163,7 +163,7 @@ class ConditionImpl implements QualityGate.Condition {
 
   @Override
   public String getValue() {
-    checkState(status != NO_VALUE, "There is no value when status is " + NO_VALUE);
+    checkState(status != NO_VALUE, "There is no value when status is %s", NO_VALUE);
 
     return value;
   }
index e19905947d80f515f7e0efb19b9a8a02930cac68..1ef23c33832eebc4821f4b9e1b9dc135680edc04 100644 (file)
@@ -24,7 +24,6 @@ import java.util.HashMap;
 import java.util.Map;
 
 import static com.google.common.base.Preconditions.checkState;
-import static java.lang.String.format;
 
 /**
  * Cache of database ids for components (component id and snapshot id) based in Maps.
@@ -47,7 +46,7 @@ public final class MapBasedDbIdsRepository<T> implements MutableDbIdsRepository
     T ref = componentToKey.apply(component);
     Long existingComponentId = componentIdsByRef.get(ref);
     checkState(existingComponentId == null,
-      format("Component id '%s' is already registered in repository for Component '%s', can not set new id '%s'", existingComponentId, component.getKey(), componentId));
+      "Component id '%s' is already registered in repository for Component '%s', can not set new id '%s'", existingComponentId, component.getKey(), componentId);
     componentIdsByRef.put(ref, componentId);
     return this;
   }
@@ -56,14 +55,14 @@ public final class MapBasedDbIdsRepository<T> implements MutableDbIdsRepository
   public long getComponentId(Component component) {
     T ref = componentToKey.apply(component);
     Long componentId = componentIdsByRef.get(ref);
-    checkState(componentId != null, format("No component id registered in repository for Component '%s'", component.getKey()));
+    checkState(componentId != null, "No component id registered in repository for Component '%s'", component.getKey());
     return componentId;
   }
 
   @Override
   public DbIdsRepository setDeveloperId(Developer developer, long developerId) {
     Long existingId = developerIdsByKey.get(developer);
-    checkState(existingId == null, format("Id '%s' is already registered in repository for Developer '%s', can not set new id '%s'", existingId, developer, developerId));
+    checkState(existingId == null, "Id '%s' is already registered in repository for Developer '%s', can not set new id '%s'", existingId, developer, developerId);
     developerIdsByKey.put(developer, developerId);
     return this;
   }
@@ -71,7 +70,7 @@ public final class MapBasedDbIdsRepository<T> implements MutableDbIdsRepository
   @Override
   public long getDeveloperId(Developer developer) {
     Long devId = developerIdsByKey.get(developer);
-    checkState(devId != null, format("No id registered in repository for Developer '%s'", developer));
+    checkState(devId != null, "No id registered in repository for Developer '%s'", developer);
     return devId;
   }
 }
index ec94293013fe4a951b3e927e4c9611e7e9816514..da67bcfa31fac17b4c33922a80065210d85cd919 100644 (file)
@@ -21,14 +21,13 @@ package org.sonar.server.computation.task.projectanalysis.measure;
 
 import com.google.common.base.MoreObjects;
 import java.util.Arrays;
+import java.util.Objects;
 import javax.annotation.Nullable;
 import javax.annotation.concurrent.Immutable;
 import org.sonar.server.computation.task.projectanalysis.period.Period;
 
 import static com.google.common.base.Preconditions.checkArgument;
 import static com.google.common.base.Preconditions.checkState;
-import static com.google.common.base.Predicates.notNull;
-import static com.google.common.collect.FluentIterable.from;
 
 @Immutable
 public final class MeasureVariations {
@@ -38,7 +37,7 @@ public final class MeasureVariations {
 
   public MeasureVariations(Double... variations) {
     checkArgument(variations.length <= 5, "There can not be more than 5 variations");
-    checkArgument(!from(Arrays.asList(variations)).filter(notNull()).isEmpty(), "There must be at least one variation");
+    checkArgument(Arrays.stream(variations).anyMatch(Objects::nonNull), "There must be at least one variation");
     for (Double variation : variations) {
       checkArgument(variation == null || !Double.isNaN(variation), NAN_ERROR_MESSAGE);
     }
@@ -58,7 +57,7 @@ public final class MeasureVariations {
 
     public Builder setVariation(Period period, double variation) {
       int arrayIndex = period.getIndex() - 1;
-      checkState(variations[arrayIndex] == null, String.format("Variation for Period %s has already been set", period.getIndex()));
+      checkState(variations[arrayIndex] == null, "Variation for Period %s has already been set", period.getIndex());
       checkArgument(!Double.isNaN(variation), NAN_ERROR_MESSAGE);
       variations[arrayIndex] = variation;
       return this;
index c8f016c536af3ae26071464aa56ac76e57e2fa2a..0f401e800a15d937ec55bfa37c1e716263d8e76c 100644 (file)
 package org.sonar.server.computation.task.projectanalysis.period;
 
 import com.google.common.base.Predicate;
-import com.google.common.base.Predicates;
 import com.google.common.collect.Iterables;
 import java.util.Arrays;
 import java.util.List;
+import java.util.Objects;
 import javax.annotation.CheckForNull;
 import javax.annotation.Nullable;
+import org.sonar.core.util.stream.Collectors;
 
 import static com.google.common.base.Preconditions.checkArgument;
 import static com.google.common.base.Preconditions.checkState;
@@ -64,7 +65,7 @@ public class PeriodsHolderImpl implements PeriodsHolder {
   @Override
   public List<Period> getPeriods() {
     checkHolderIsInitialized();
-    return from(Arrays.asList(periods)).filter(Predicates.notNull()).toList();
+    return Arrays.stream(periods).filter(Objects::nonNull).collect(Collectors.toList());
   }
 
   @Override
@@ -78,7 +79,7 @@ public class PeriodsHolderImpl implements PeriodsHolder {
 
   @Override
   public Period getPeriod(int i) {
-    checkState(hasPeriod(i), "Holder has no Period for index " + i);
+    checkState(hasPeriod(i), "Holder has no Period for index %s", i);
     return this.periods[i - 1];
   }
 
index 35f26c2ac33037cc57825e4359fc227331c6ed15..b1fdd42a104c9a1deb46610354dd83347ccf057a 100644 (file)
  */
 package org.sonar.server.computation.task.projectanalysis.scm;
 
-import com.google.common.base.Function;
 import com.google.common.base.Optional;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
+import java.util.Objects;
+import java.util.function.Function;
+import java.util.stream.StreamSupport;
 import javax.annotation.Nonnull;
 import javax.annotation.Nullable;
 import javax.annotation.concurrent.Immutable;
+import org.sonar.core.util.stream.Collectors;
 import org.sonar.db.protobuf.DbFileSources;
 import org.sonar.server.computation.task.projectanalysis.component.Component;
 
 import static com.google.common.base.Preconditions.checkState;
-import static com.google.common.base.Predicates.notNull;
-import static com.google.common.collect.FluentIterable.from;
-import static java.lang.String.format;
 
 /**
  * ScmInfo implementation based on the lines stored in DB
@@ -49,16 +49,16 @@ class DbScmInfo implements ScmInfo {
 
   static Optional<ScmInfo> create(Component component, Iterable<DbFileSources.Line> lines) {
     LineToChangeset lineToChangeset = new LineToChangeset();
-    List<Changeset> lineChangesets = from(lines)
-      .transform(lineToChangeset)
-      .filter(notNull())
-      .toList();
+    List<Changeset> lineChangesets = StreamSupport.stream(lines.spliterator(), false)
+      .map(lineToChangeset)
+      .filter(Objects::nonNull)
+      .collect(Collectors.toList());
     if (lineChangesets.isEmpty()) {
       return Optional.absent();
     }
     checkState(!lineToChangeset.isEncounteredLineWithoutScmInfo(),
-      format("Partial scm information stored in DB for component '%s'. Not all lines have SCM info. Can not proceed", component));
-    return Optional.<ScmInfo>of(new DbScmInfo(new ScmInfoImpl(lineChangesets)));
+      "Partial scm information stored in DB for component '%s'. Not all lines have SCM info. Can not proceed", component);
+    return Optional.of(new DbScmInfo(new ScmInfoImpl(lineChangesets)));
   }
 
   @Override
@@ -95,23 +95,18 @@ class DbScmInfo implements ScmInfo {
     public Changeset apply(@Nonnull DbFileSources.Line input) {
       if (input.hasScmRevision() && input.hasScmDate()) {
         String revision = input.getScmRevision();
-        Changeset changeset = cache.get(revision);
-        if (changeset == null) {
-          changeset = builder
-              .setRevision(revision)
-              .setAuthor(input.hasScmAuthor() ? input.getScmAuthor() : null)
-              .setDate(input.getScmDate())
-              .build();
-          cache.put(revision, changeset);
-        }
-        return changeset;
+        return cache.computeIfAbsent(revision, k -> builder
+          .setRevision(revision)
+          .setAuthor(input.hasScmAuthor() ? input.getScmAuthor() : null)
+          .setDate(input.getScmDate())
+          .build());
       }
 
       this.encounteredLineWithoutScmInfo = true;
       return null;
     }
 
-    public boolean isEncounteredLineWithoutScmInfo() {
+    boolean isEncounteredLineWithoutScmInfo() {
       return encounteredLineWithoutScmInfo;
     }
   }
index 44a3413c4ca6cc18c038ee32cbfc8d4bea923d4d..564b619f4d5f2147a80c4b800010adf817f9e96b 100644 (file)
@@ -44,7 +44,7 @@ public class SourceLinesRepositoryImpl implements SourceLinesRepository {
 
     Optional<CloseableIterator<String>> linesIteratorOptional = reportReader.readFileSource(file.getReportAttributes().getRef());
 
-    checkState(linesIteratorOptional.isPresent(), String.format("File '%s' has no source code", file));
+    checkState(linesIteratorOptional.isPresent(), "File '%s' has no source code", file);
     int numberOfLines = reportReader.readComponent(file.getReportAttributes().getRef()).getLines();
     CloseableIterator<String> lineIterator = linesIteratorOptional.get();
 
@@ -59,7 +59,7 @@ public class SourceLinesRepositoryImpl implements SourceLinesRepository {
     private final int numberOfLines;
     private int currentLine = 0;
 
-    public ComponentLinesCloseableIterator(Component file, CloseableIterator<String> lineIterator, int numberOfLines) {
+    private ComponentLinesCloseableIterator(Component file, CloseableIterator<String> lineIterator, int numberOfLines) {
       this.file = file;
       this.delegate = lineIterator;
       this.numberOfLines = numberOfLines;
index 5c5b8b40d82243bdd1bb8b2d180ee6cdd156a717..918e0dbc904884b862b3ae68daeb3533a0f9f6b7 100644 (file)
@@ -36,9 +36,9 @@ import org.sonar.api.measures.CoreMetrics;
 import org.sonar.api.measures.Metric;
 import org.sonar.api.measures.Metrics;
 import org.sonar.api.utils.dag.DirectAcyclicGraph;
-import org.sonar.server.computation.task.projectanalysis.measure.MutableMeasureComputersHolder;
 import org.sonar.server.computation.task.projectanalysis.api.measurecomputer.MeasureComputerDefinitionImpl;
 import org.sonar.server.computation.task.projectanalysis.api.measurecomputer.MeasureComputerWrapper;
+import org.sonar.server.computation.task.projectanalysis.measure.MutableMeasureComputersHolder;
 import org.sonar.server.computation.task.step.ComputationStep;
 
 import static com.google.common.base.Preconditions.checkState;
@@ -111,7 +111,7 @@ public class LoadMeasureComputersStep implements ComputationStep {
   }
 
   private static void feedComputersByMetric(List<MeasureComputerWrapper> wrappers, Map<String, MeasureComputerWrapper> computersByOutputMetric,
-                                            Map<String, MeasureComputerWrapper> computersByInputMetric) {
+    Map<String, MeasureComputerWrapper> computersByInputMetric) {
     for (MeasureComputerWrapper computer : wrappers) {
       for (String outputMetric : computer.getDefinition().getOutputMetrics()) {
         computersByOutputMetric.put(outputMetric, computer);
@@ -205,7 +205,7 @@ public class LoadMeasureComputersStep implements ComputationStep {
     @Override
     public boolean apply(@Nonnull String metric) {
       checkState(pluginMetricKeys.contains(metric) || CORE_METRIC_KEYS.contains(metric),
-        String.format("Metric '%s' cannot be used as an input metric as it's not a core metric and no plugin declare this metric", metric));
+        "Metric '%s' cannot be used as an input metric as it's not a core metric and no plugin declare this metric", metric);
       return true;
     }
   }
@@ -222,8 +222,8 @@ public class LoadMeasureComputersStep implements ComputationStep {
   private class ValidateOutputMetric implements Predicate<String> {
     @Override
     public boolean apply(@Nonnull String metric) {
-      checkState(!CORE_METRIC_KEYS.contains(metric), String.format("Metric '%s' cannot be used as an output metric as it's a core metric", metric));
-      checkState(pluginMetricKeys.contains(metric), String.format("Metric '%s' cannot be used as an output metric as no plugin declare this metric", metric));
+      checkState(!CORE_METRIC_KEYS.contains(metric), "Metric '%s' cannot be used as an output metric as it's a core metric", metric);
+      checkState(pluginMetricKeys.contains(metric), "Metric '%s' cannot be used as an output metric as no plugin declare this metric", metric);
       return true;
     }
   }
@@ -232,10 +232,10 @@ public class LoadMeasureComputersStep implements ComputationStep {
     private Set<String> allOutputMetrics = new HashSet<>();
 
     @Override
-    public boolean apply(@Nonnull MeasureComputerWrapper wrapper ) {
+    public boolean apply(@Nonnull MeasureComputerWrapper wrapper) {
       for (String outputMetric : wrapper.getDefinition().getOutputMetrics()) {
         checkState(!allOutputMetrics.contains(outputMetric),
-          String.format("Output metric '%s' is already defined by another measure computer '%s'", outputMetric, wrapper.getComputer()));
+          "Output metric '%s' is already defined by another measure computer '%s'", outputMetric, wrapper.getComputer());
         allOutputMetrics.add(outputMetric);
       }
       return true;
index bb0090fd8e83b0752bf62cb2883ee6b12827d538..fc84bd2fc5e3a195ee266bb355e5fd133e2e9cfb 100644 (file)
@@ -19,7 +19,6 @@
  */
 package org.sonar.api.batch.sensor.coverage.internal;
 
-import com.google.common.base.Preconditions;
 import com.google.common.collect.Maps;
 import java.util.Collections;
 import java.util.SortedMap;
@@ -31,6 +30,9 @@ import org.sonar.api.batch.sensor.coverage.NewCoverage;
 import org.sonar.api.batch.sensor.internal.DefaultStorable;
 import org.sonar.api.batch.sensor.internal.SensorStorage;
 
+import static com.google.common.base.Preconditions.checkNotNull;
+import static com.google.common.base.Preconditions.checkState;
+
 public class DefaultCoverage extends DefaultStorable implements NewCoverage {
 
   private DefaultInputFile inputFile;
@@ -62,7 +64,7 @@ public class DefaultCoverage extends DefaultStorable implements NewCoverage {
 
   @Override
   public NewCoverage ofType(CoverageType type) {
-    Preconditions.checkNotNull(type, "type can't be null");
+    checkNotNull(type, "type can't be null");
     this.type = type;
     return this;
   }
@@ -86,12 +88,12 @@ public class DefaultCoverage extends DefaultStorable implements NewCoverage {
   }
 
   private void validateLine(int line) {
-    Preconditions.checkState(line <= inputFile.lines(), String.format("Line %d is out of range in the file %s (lines: %d)", line, inputFile.relativePath(), inputFile.lines()));
-    Preconditions.checkState(line > 0, "Line number must be strictly positive: " + line);
+    checkState(line <= inputFile.lines(), "Line %s is out of range in the file %s (lines: %s)", line, inputFile.relativePath(), inputFile.lines());
+    checkState(line > 0, "Line number must be strictly positive: %s", line);
   }
 
   private void validateFile() {
-    Preconditions.checkNotNull(inputFile, "Call onFile() first");
+    checkNotNull(inputFile, "Call onFile() first");
   }
 
   @Override
index 722b7ed623377b52ac36a54d9e635336a9885920..9a3fc8e4646eb7be7d59d26b215010d7a37a0d1c 100644 (file)
@@ -431,9 +431,10 @@ public interface RulesDefinition {
     private void registerRepository(NewRepositoryImpl newRepository) {
       Repository existing = repositoriesByKey.get(newRepository.key());
       if (existing != null) {
-        checkState(existing.language().equals(newRepository.language),
+        String existingLanguage = existing.language();
+        checkState(existingLanguage.equals(newRepository.language),
           "The rule repository '%s' must not be defined for two different languages: %s and %s",
-          newRepository.key, existing.language(), newRepository.language);
+          newRepository.key, existingLanguage, newRepository.language);
       }
       repositoriesByKey.put(newRepository.key, new RepositoryImpl(newRepository, existing));
     }