]> source.dussan.org Git - sonarqube.git/commitdiff
Fix quality flaws
authorJulien Lancelot <julien.lancelot@sonarsource.com>
Wed, 7 Sep 2016 13:06:57 +0000 (15:06 +0200)
committerJulien Lancelot <julien.lancelot@sonarsource.com>
Wed, 7 Sep 2016 13:06:57 +0000 (15:06 +0200)
17 files changed:
server/sonar-server/src/main/java/org/sonar/server/batch/BatchWs.java
server/sonar-server/src/main/java/org/sonar/server/component/ComponentsFinderSort.java
server/sonar-server/src/main/java/org/sonar/server/component/DefaultComponentFinder.java
server/sonar-server/src/main/java/org/sonar/server/computation/task/projectanalysis/step/ComputeMeasureVariationsStep.java
server/sonar-server/src/main/java/org/sonar/server/computation/task/projectanalysis/step/PersistEventsStep.java
server/sonar-server/src/main/java/org/sonar/server/computation/task/projectanalysis/step/PersistProjectLinksStep.java
server/sonar-server/src/main/java/org/sonar/server/computation/task/projectanalysis/step/PersistTestsStep.java
server/sonar-server/src/main/java/org/sonar/server/issue/IssuesFinderSort.java
server/sonar-server/src/main/java/org/sonar/server/issue/TransitionAction.java
server/sonar-server/src/main/java/org/sonar/server/permission/ws/TemplateUsersAction.java
server/sonar-server/src/main/java/org/sonar/server/rule/ws/ListAction.java
server/sonar-server/src/main/java/org/sonar/server/usergroups/ws/UpdateAction.java
server/sonar-server/src/test/java/org/sonar/server/usergroups/ws/UpdateActionTest.java
sonar-db/src/main/java/org/sonar/db/component/ResourceDao.java
sonar-db/src/main/java/org/sonar/db/version/v50/ReplaceIssueFiltersProjectKeyByUuid.java
sonar-plugin-api/src/main/java/org/sonar/api/measures/CoreMetrics.java
sonar-plugin-api/src/test/java/org/sonar/api/resources/CoreMetricsTest.java

index 4e7e32b779524a8ab05474d7a707094813e9d66b..0b8b5bcb13b3cc184f0d193b9323fa4a60a37ab2 100644 (file)
@@ -22,9 +22,6 @@ package org.sonar.server.batch;
 import java.io.IOException;
 import org.apache.commons.io.FileUtils;
 import org.apache.commons.io.IOUtils;
-import org.sonar.api.server.ws.Request;
-import org.sonar.api.server.ws.RequestHandler;
-import org.sonar.api.server.ws.Response;
 import org.sonar.api.server.ws.WebService;
 
 public class BatchWs implements WebService {
@@ -59,15 +56,12 @@ public class BatchWs implements WebService {
       .setInternal(true)
       .setSince("4.4")
       .setDescription("List the JAR files to be downloaded by source analyzer")
-      .setHandler(new RequestHandler() {
-        @Override
-        public void handle(Request request, Response response) {
-          try {
-            response.stream().setMediaType("text/plain");
-            IOUtils.write(batchIndex.getIndex(), response.stream().output());
-          } catch (IOException e) {
-            throw new IllegalStateException(e);
-          }
+      .setHandler((request, response) -> {
+        try {
+          response.stream().setMediaType("text/plain");
+          IOUtils.write(batchIndex.getIndex(), response.stream().output());
+        } catch (IOException e) {
+          throw new IllegalStateException(e);
         }
       })
       .setResponseExample(getClass().getResource("batch-index-example.txt"));
@@ -79,16 +73,13 @@ public class BatchWs implements WebService {
       .setSince("4.4")
       .setDescription("Download a JAR file required by source analyzer")
       .setResponseExample(getClass().getResource("batch-file-example.txt"))
-      .setHandler(new RequestHandler() {
-        @Override
-        public void handle(Request request, Response response) {
-          String filename = request.mandatoryParam("name");
-          try {
-            response.stream().setMediaType("application/java-archive");
-            FileUtils.copyFile(batchIndex.getFile(filename), response.stream().output());
-          } catch (IOException e) {
-            throw new IllegalStateException(e);
-          }
+      .setHandler((request, response) -> {
+        String filename = request.mandatoryParam("name");
+        try {
+          response.stream().setMediaType("application/java-archive");
+          FileUtils.copyFile(batchIndex.getFile(filename), response.stream().output());
+        } catch (IOException e) {
+          throw new IllegalStateException(e);
         }
       });
     action
index 66bcd75c00ebd541b1df03df61c307b2202f2691..d29920e980811adaa7221fd0aecdf882871d350e 100644 (file)
@@ -54,20 +54,20 @@ class ComponentsFinderSort {
     throw new IllegalArgumentException("Cannot sort on field : " + sort);
   }
 
-  abstract static class ComponentProcessor {
-    abstract Function sortFieldFunction();
+  interface ComponentProcessor {
+    Function sortFieldFunction();
 
-    abstract Ordering sortFieldOrdering(boolean ascending);
+    Ordering sortFieldOrdering(boolean ascending);
 
-    final List<? extends Component> sort(Collection<? extends Component> components, boolean ascending) {
+    default List<? extends Component> sort(Collection<? extends Component> components, boolean ascending) {
       Ordering<Component> ordering = sortFieldOrdering(ascending).onResultOf(sortFieldFunction());
       return ordering.immutableSortedCopy(components);
     }
   }
 
-  abstract static class TextSort extends ComponentProcessor {
+  abstract static class TextSort implements ComponentProcessor {
     @Override
-    Function sortFieldFunction() {
+    public Function sortFieldFunction() {
       return new Function<Component, String>() {
         @Override
         public String apply(Component component) {
@@ -79,7 +79,7 @@ class ComponentsFinderSort {
     abstract String sortField(Component component);
 
     @Override
-    Ordering sortFieldOrdering(boolean ascending) {
+    public Ordering sortFieldOrdering(boolean ascending) {
       Ordering<String> ordering = Ordering.from(String.CASE_INSENSITIVE_ORDER).nullsLast();
       if (!ascending) {
         ordering = ordering.reverse();
index 1d719d5661ad0bdf1fe94a2bdf7ae3f7da919f42..57c4fabf70862eda3e58bfb8a50d220ebb0ab714 100644 (file)
@@ -62,11 +62,11 @@ public class DefaultComponentFinder {
     return newArrayList(Iterables.filter(allComponents, new MatchQuery(query)));
   }
 
-  abstract static class Filter {
+  interface Filter {
 
-    abstract String field(Component component);
+    String field(Component component);
 
-    final boolean accept(Component component, Collection<String> collections) {
+    default boolean accept(Component component, Collection<String> collections) {
       if (!collections.isEmpty()) {
         for (String item : collections) {
           if (field(component).toLowerCase().contains(item.toLowerCase())) {
@@ -79,16 +79,16 @@ public class DefaultComponentFinder {
     }
   }
 
-  static class NameFilter extends Filter {
+  static class NameFilter implements Filter {
     @Override
-    String field(Component component) {
+    public String field(Component component) {
       return component.name();
     }
   }
 
-  static class KeyFilter extends Filter {
+  static class KeyFilter implements Filter {
     @Override
-    String field(Component component) {
+    public String field(Component component) {
       return component.key();
     }
   }
index a34da8128dae4b7ff0f0d5e766391ea72c069e56..26593d0ffc5d29ac3158f1c6da6f119545ee9298 100644 (file)
@@ -27,6 +27,8 @@ import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
+import java.util.stream.Collectors;
+import java.util.stream.StreamSupport;
 import javax.annotation.CheckForNull;
 import javax.annotation.Nonnull;
 import javax.annotation.Nullable;
@@ -49,8 +51,9 @@ import org.sonar.server.computation.task.projectanalysis.period.PeriodsHolder;
 import org.sonar.server.computation.task.step.ComputationStep;
 
 import static com.google.common.base.Preconditions.checkArgument;
-import static com.google.common.collect.FluentIterable.from;
 import static java.lang.String.format;
+import static java.util.function.Function.identity;
+import static org.sonar.core.util.stream.Collectors.uniqueIndex;
 import static org.sonar.server.computation.task.projectanalysis.component.Component.Type.DIRECTORY;
 import static org.sonar.server.computation.task.projectanalysis.component.Component.Type.SUBVIEW;
 import static org.sonar.server.computation.task.projectanalysis.component.ComponentVisitor.Order.PRE_ORDER;
@@ -69,15 +72,6 @@ public class ComputeMeasureVariationsStep implements ComputationStep {
   private final MetricRepository metricRepository;
   private final MeasureRepository measureRepository;
 
-  private final Function<PastMeasureDto, MeasureKey> pastMeasureToMeasureKey = new Function<PastMeasureDto, MeasureKey>() {
-    @Nullable
-    @Override
-    public MeasureKey apply(@Nonnull PastMeasureDto input) {
-      Metric metric = metricRepository.getById((long)input.getMetricId());
-      return new MeasureKey(metric.getKey(), null);
-    }
-  };
-
   public ComputeMeasureVariationsStep(DbClient dbClient, TreeRootHolder treeRootHolder, PeriodsHolder periodsHolder, MetricRepository metricRepository,
     MeasureRepository measureRepository) {
     this.dbClient = dbClient;
@@ -91,7 +85,7 @@ public class ComputeMeasureVariationsStep implements ComputationStep {
   public void execute() {
     DbSession dbSession = dbClient.openSession(false);
     try {
-      List<Metric> metrics = from(metricRepository.getAll()).filter(NumericMetric.INSTANCE).toList();
+      List<Metric> metrics = StreamSupport.stream(metricRepository.getAll().spliterator(), false).filter(NumericMetric.INSTANCE::apply).collect(Collectors.toList());
       new DepthTraversalTypeAwareCrawler(new VariationMeasuresVisitor(dbSession, metrics))
         .visit(treeRootHolder.getRoot());
     } finally {
@@ -109,7 +103,7 @@ public class ComputeMeasureVariationsStep implements ComputationStep {
       // measures on files are currently purged, so past measures are not available on files
       super(CrawlerDepthLimit.reportMaxDepth(DIRECTORY).withViewsMaxDepth(SUBVIEW), PRE_ORDER);
       this.session = session;
-      this.metricIds = from(metrics).transform(MetricDtoToMetricId.INSTANCE).toSet();
+      this.metricIds = metrics.stream().map(MetricDtoToMetricId.INSTANCE::apply).collect(Collectors.toSet());
       this.metrics = metrics;
     }
 
@@ -130,7 +124,9 @@ public class ComputeMeasureVariationsStep implements ComputationStep {
     }
 
     private void setVariationMeasures(Component component, List<PastMeasureDto> pastMeasures, int period, MeasuresWithVariationRepository measuresWithVariationRepository) {
-      Map<MeasureKey, PastMeasureDto> pastMeasuresByMeasureKey = from(pastMeasures).uniqueIndex(pastMeasureToMeasureKey);
+      Map<MeasureKey, PastMeasureDto> pastMeasuresByMeasureKey = pastMeasures
+        .stream()
+        .collect(uniqueIndex(m -> new MeasureKey(metricRepository.getById((long) m.getMetricId()).getKey(), null), identity()));
       for (Metric metric : metrics) {
         Optional<Measure> measure = measureRepository.getRawMeasure(component, metric);
         if (measure.isPresent() && !measure.get().hasVariations()) {
index 3ede645767aad95874fc5318bd7dc6995b99921d..644263f9304bbb694944f0c3489cfd011703f112 100644 (file)
@@ -19,7 +19,9 @@
  */
 package org.sonar.server.computation.task.projectanalysis.step;
 
-import com.google.common.base.Function;
+import java.util.function.Function;
+import java.util.stream.Collectors;
+import java.util.stream.StreamSupport;
 import org.sonar.api.utils.System2;
 import org.sonar.db.DbClient;
 import org.sonar.db.DbSession;
@@ -27,7 +29,6 @@ import org.sonar.db.MyBatis;
 import org.sonar.db.event.EventDto;
 import org.sonar.server.computation.task.projectanalysis.analysis.AnalysisMetadataHolder;
 import org.sonar.server.computation.task.projectanalysis.component.Component;
-import org.sonar.server.computation.task.projectanalysis.component.ComponentVisitor;
 import org.sonar.server.computation.task.projectanalysis.component.CrawlerDepthLimit;
 import org.sonar.server.computation.task.projectanalysis.component.DepthTraversalTypeAwareCrawler;
 import org.sonar.server.computation.task.projectanalysis.component.TreeRootHolder;
@@ -36,8 +37,6 @@ import org.sonar.server.computation.task.projectanalysis.event.Event;
 import org.sonar.server.computation.task.projectanalysis.event.EventRepository;
 import org.sonar.server.computation.task.step.ComputationStep;
 
-import static com.google.common.collect.Iterables.transform;
-
 public class PersistEventsStep implements ComputationStep {
 
   private final DbClient dbClient;
@@ -68,55 +67,6 @@ public class PersistEventsStep implements ComputationStep {
     }
   }
 
-  private void processEvents(DbSession session, Component component, Long analysisDate) {
-    Function<Event, EventDto> eventToEventDto = event -> newBaseEvent(component, analysisDate)
-      .setName(event.getName())
-      .setCategory(convertCategory(event.getCategory()))
-      .setDescription(event.getDescription())
-      .setData(event.getData());
-    // FIXME bulk insert
-    for (EventDto batchEventDto : transform(eventRepository.getEvents(component), eventToEventDto)) {
-      dbClient.eventDao().insert(session, batchEventDto);
-    }
-  }
-
-  private void saveVersionEvent(DbSession session, Component component, Long analysisDate) {
-    String version = component.getReportAttributes().getVersion();
-    if (version != null) {
-      deletePreviousEventsHavingSameVersion(session, version, component);
-      dbClient.eventDao().insert(session, newBaseEvent(component, analysisDate)
-        .setName(version)
-        .setCategory(EventDto.CATEGORY_VERSION));
-    }
-  }
-
-  private void deletePreviousEventsHavingSameVersion(DbSession session, String version, Component component) {
-    for (EventDto dto : dbClient.eventDao().selectByComponentUuid(session, component.getUuid())) {
-      if (dto.getCategory().equals(EventDto.CATEGORY_VERSION) && dto.getName().equals(version)) {
-        dbClient.eventDao().delete(session, dto.getId());
-      }
-    }
-  }
-
-  private EventDto newBaseEvent(Component component, Long analysisDate) {
-    return new EventDto()
-      .setAnalysisUuid(analysisMetadataHolder.getUuid())
-      .setComponentUuid(component.getUuid())
-      .setCreatedAt(system2.now())
-      .setDate(analysisDate);
-  }
-
-  private static String convertCategory(Event.Category category) {
-    switch (category) {
-      case ALERT:
-        return EventDto.CATEGORY_ALERT;
-      case PROFILE:
-        return EventDto.CATEGORY_PROFILE;
-      default:
-        throw new IllegalArgumentException(String.format("Unsupported category %s", category.name()));
-    }
-  }
-
   @Override
   public String getDescription() {
     return "Persist events";
@@ -126,8 +76,8 @@ public class PersistEventsStep implements ComputationStep {
     private final DbSession session;
     private final long analysisDate;
 
-    public PersistEventComponentVisitor(DbSession session, long analysisDate) {
-      super(CrawlerDepthLimit.PROJECT, ComponentVisitor.Order.PRE_ORDER);
+    PersistEventComponentVisitor(DbSession session, long analysisDate) {
+      super(CrawlerDepthLimit.PROJECT, Order.PRE_ORDER);
       this.session = session;
       this.analysisDate = analysisDate;
     }
@@ -138,5 +88,54 @@ public class PersistEventsStep implements ComputationStep {
       saveVersionEvent(session, project, analysisDate);
     }
 
+    private void processEvents(DbSession session, Component component, Long analysisDate) {
+      Function<Event, EventDto> eventToEventDto = event -> newBaseEvent(component, analysisDate)
+        .setName(event.getName())
+        .setCategory(convertCategory(event.getCategory()))
+        .setDescription(event.getDescription())
+        .setData(event.getData());
+      // FIXME bulk insert
+      for (EventDto batchEventDto : StreamSupport.stream(eventRepository.getEvents(component).spliterator(), false).map(eventToEventDto).collect(Collectors.toList())) {
+        dbClient.eventDao().insert(session, batchEventDto);
+      }
+    }
+
+    private void saveVersionEvent(DbSession session, Component component, Long analysisDate) {
+      String version = component.getReportAttributes().getVersion();
+      if (version != null) {
+        deletePreviousEventsHavingSameVersion(session, version, component);
+        dbClient.eventDao().insert(session, newBaseEvent(component, analysisDate)
+          .setName(version)
+          .setCategory(EventDto.CATEGORY_VERSION));
+      }
+    }
+
+    private void deletePreviousEventsHavingSameVersion(DbSession session, String version, Component component) {
+      for (EventDto dto : dbClient.eventDao().selectByComponentUuid(session, component.getUuid())) {
+        if (dto.getCategory().equals(EventDto.CATEGORY_VERSION) && dto.getName().equals(version)) {
+          dbClient.eventDao().delete(session, dto.getId());
+        }
+      }
+    }
+
+    private EventDto newBaseEvent(Component component, Long analysisDate) {
+      return new EventDto()
+        .setAnalysisUuid(analysisMetadataHolder.getUuid())
+        .setComponentUuid(component.getUuid())
+        .setCreatedAt(system2.now())
+        .setDate(analysisDate);
+    }
+
+    private String convertCategory(Event.Category category) {
+      switch (category) {
+        case ALERT:
+          return EventDto.CATEGORY_ALERT;
+        case PROFILE:
+          return EventDto.CATEGORY_PROFILE;
+        default:
+          throw new IllegalArgumentException(String.format("Unsupported category %s", category.name()));
+      }
+    }
+
   }
 }
index 403aecf24fa2ad5c3014de7cf1d2b8daea37913d..88a6a22e056ec2097b21c251913b950e25bb521d 100644 (file)
  */
 package org.sonar.server.computation.task.projectanalysis.step;
 
-import com.google.common.base.Predicate;
 import com.google.common.collect.ImmutableMap;
-import com.google.common.collect.Iterables;
 import java.util.List;
 import java.util.Locale;
 import java.util.Map;
+import java.util.Optional;
 import java.util.Set;
-import javax.annotation.Nullable;
 import org.sonar.api.i18n.I18n;
 import org.sonar.db.DbClient;
 import org.sonar.db.DbSession;
@@ -120,22 +118,19 @@ public class PersistProjectLinksStep implements ComputationStep {
           throw new IllegalArgumentException(String.format("Link of type '%s' has already been declared on component '%s'", type, componentUuid));
         }
 
-        ComponentLinkDto previousLink = Iterables.find(previousLinks, new Predicate<ComponentLinkDto>() {
-          @Override
-          public boolean apply(@Nullable ComponentLinkDto input) {
-            return input != null && input.getType().equals(convertType(link.getType()));
-          }
-        }, null);
-        if (previousLink == null) {
+        Optional<ComponentLinkDto> previousLink = previousLinks.stream()
+          .filter(input -> input != null && input.getType().equals(convertType(link.getType())))
+          .findFirst();
+        if (previousLink.isPresent()) {
+          previousLink.get().setHref(link.getHref());
+          dbClient.componentLinkDao().update(session, previousLink.get());
+        } else {
           dbClient.componentLinkDao().insert(session,
             new ComponentLinkDto()
               .setComponentUuid(componentUuid)
               .setType(type)
               .setName(i18n.message(Locale.ENGLISH, "project_links." + type, null))
               .setHref(link.getHref()));
-        } else {
-          previousLink.setHref(link.getHref());
-          dbClient.componentLinkDao().update(session, previousLink);
         }
       }
 
index 2f4925cd1347980bb69a132813c671897e52e0e0..5db2e83ad0003de67f5080b9e04aed62e11b8d80 100644 (file)
@@ -32,8 +32,6 @@ import java.util.HashSet;
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
-import org.apache.ibatis.session.ResultContext;
-import org.apache.ibatis.session.ResultHandler;
 import org.sonar.api.utils.System2;
 import org.sonar.api.utils.log.Logger;
 import org.sonar.api.utils.log.Loggers;
@@ -107,12 +105,9 @@ public class PersistTestsStep implements ComputationStep {
       this.projectKey = treeRootHolder.getRoot().getKey();
       session.select("org.sonar.db.source.FileSourceMapper.selectHashesForProject",
         ImmutableMap.of("projectUuid", treeRootHolder.getRoot().getUuid(), "dataType", Type.TEST),
-        new ResultHandler() {
-          @Override
-          public void handleResult(ResultContext context) {
-            FileSourceDto dto = (FileSourceDto) context.getResultObject();
-            existingFileSourcesByUuid.put(dto.getFileUuid(), dto);
-          }
+        context -> {
+          FileSourceDto dto = (FileSourceDto) context.getResultObject();
+          existingFileSourcesByUuid.put(dto.getFileUuid(), dto);
         });
     }
 
index f1d6ace71a8ceae823f2b079647432836280ae85..eb1d30925dab6a44a21d8d7132d3b84658b98c47 100644 (file)
@@ -72,20 +72,20 @@ class IssuesFinderSort {
     throw new IllegalArgumentException("Cannot sort on field : " + sort);
   }
 
-  abstract static class IssueProcessor {
-    abstract Function sortFieldFunction();
+  interface IssueProcessor {
+    Function sortFieldFunction();
 
-    abstract Ordering sortFieldOrdering(boolean ascending);
+    Ordering sortFieldOrdering(boolean ascending);
 
-    final List<IssueDto> sort(Collection<IssueDto> issueDtos, boolean ascending) {
+    default List<IssueDto> sort(Collection<IssueDto> issueDtos, boolean ascending) {
       Ordering<IssueDto> ordering = sortFieldOrdering(ascending).onResultOf(sortFieldFunction());
       return ordering.immutableSortedCopy(issueDtos);
     }
   }
 
-  abstract static class TextSortIssueProcessor extends IssueProcessor {
+  abstract static class TextSortIssueProcessor implements IssueProcessor {
     @Override
-    Function sortFieldFunction() {
+    public Function sortFieldFunction() {
       return new Function<IssueDto, String>() {
         @Override
         public String apply(IssueDto issueDto) {
@@ -97,7 +97,7 @@ class IssuesFinderSort {
     abstract String sortField(IssueDto issueDto);
 
     @Override
-    Ordering sortFieldOrdering(boolean ascending) {
+    public Ordering sortFieldOrdering(boolean ascending) {
       Ordering<String> ordering = Ordering.from(String.CASE_INSENSITIVE_ORDER).nullsLast();
       if (!ascending) {
         ordering = ordering.reverse();
@@ -120,14 +120,14 @@ class IssuesFinderSort {
     }
   }
 
-  static class SeveritySortIssueProcessor extends IssueProcessor {
+  static class SeveritySortIssueProcessor implements IssueProcessor {
     @Override
-    Function sortFieldFunction() {
+    public Function sortFieldFunction() {
       return IssueDtoToSeverity.INSTANCE;
     }
 
     @Override
-    Ordering sortFieldOrdering(boolean ascending) {
+    public Ordering sortFieldOrdering(boolean ascending) {
       Ordering<Integer> ordering = Ordering.<Integer>natural().nullsLast();
       if (!ascending) {
         ordering = ordering.reverse();
@@ -136,9 +136,9 @@ class IssuesFinderSort {
     }
   }
 
-  abstract static class DateSortRowProcessor extends IssueProcessor {
+  abstract static class DateSortRowProcessor implements IssueProcessor {
     @Override
-    Function sortFieldFunction() {
+    public Function sortFieldFunction() {
       return new Function<IssueDto, Date>() {
         @Override
         public Date apply(IssueDto issueDto) {
@@ -150,7 +150,7 @@ class IssuesFinderSort {
     abstract Date sortField(IssueDto issueDto);
 
     @Override
-    Ordering sortFieldOrdering(boolean ascending) {
+    public Ordering sortFieldOrdering(boolean ascending) {
       Ordering<Date> ordering = Ordering.<Date>natural().nullsLast();
       if (!ascending) {
         ordering = ordering.reverse();
index 9fd9ec3500f079f35f6084736f4c701d51cceabc..b7f84403407c4a211c43d3983851e6b56f040a33 100644 (file)
@@ -19,9 +19,7 @@
  */
 package org.sonar.server.issue;
 
-import com.google.common.base.Predicate;
 import com.google.common.base.Strings;
-import com.google.common.collect.Iterables;
 import java.util.Collection;
 import java.util.Map;
 import org.apache.commons.lang.StringUtils;
@@ -29,7 +27,6 @@ import org.sonar.api.issue.Issue;
 import org.sonar.api.server.ServerSide;
 import org.sonar.core.issue.DefaultIssue;
 import org.sonar.server.issue.workflow.IssueWorkflow;
-import org.sonar.server.issue.workflow.Transition;
 import org.sonar.server.user.UserSession;
 
 @ServerSide
@@ -64,14 +61,11 @@ public class TransitionAction extends Action {
 
   private boolean canExecuteTransition(Issue issue, final String transition) {
     final DefaultIssue defaultIssue = (DefaultIssue) issue;
-    return Iterables.find(workflow.outTransitions(issue), new Predicate<Transition>() {
-      @Override
-      public boolean apply(Transition input) {
-        return input.key().equals(transition) &&
-          (StringUtils.isBlank(input.requiredProjectPermission()) ||
-          userSession.hasComponentPermission(input.requiredProjectPermission(), defaultIssue.projectKey()));
-      }
-    }, null) != null;
+    return workflow.outTransitions(issue).stream()
+      .filter(input -> input.key().equals(transition) &&
+        (StringUtils.isBlank(input.requiredProjectPermission()) ||
+          userSession.hasComponentPermission(input.requiredProjectPermission(), defaultIssue.projectKey())))
+      .findFirst().orElseGet(() -> null) != null;
   }
 
   private static String transition(Map<String, Object> properties) {
index fb82ff7dcc0ca1926a84a94c6ecef8504fe89bd3..71cd78f9c2c6c0e24f823b4848ac6c5776651382 100644 (file)
@@ -121,7 +121,7 @@ public class TemplateUsersAction implements PermissionsWsAction {
     return query.build();
   }
 
-  private WsPermissions.UsersWsResponse buildResponse(List<UserDto> users, List<PermissionTemplateUserDto> permissionTemplateUsers, Paging paging) {
+  private static WsPermissions.UsersWsResponse buildResponse(List<UserDto> users, List<PermissionTemplateUserDto> permissionTemplateUsers, Paging paging) {
     Multimap<Long, String> permissionsByUserId = TreeMultimap.create();
     permissionTemplateUsers.forEach(userPermission -> permissionsByUserId.put(userPermission.getUserId(), userPermission.getPermission()));
 
@@ -145,7 +145,7 @@ public class TemplateUsersAction implements PermissionsWsAction {
     return responseBuilder.build();
   }
 
-  public List<UserDto> findUsers(DbSession dbSession, PermissionQuery query, PermissionTemplateDto template) {
+  private List<UserDto> findUsers(DbSession dbSession, PermissionQuery query, PermissionTemplateDto template) {
     List<String> orderedLogins = dbClient.permissionTemplateDao().selectUserLoginsByQueryAndTemplate(dbSession, query, template.getId());
     return Ordering.explicit(orderedLogins).onResultOf(UserDto::getLogin).immutableSortedCopy(dbClient.userDao().selectByLogins(dbSession, orderedLogins));
   }
index b459f7a7e2223aba5b6cacf4d1f9f5aac49db297..955bfa08823d5dfb0649311f0f82b95ea81bff0e 100644 (file)
@@ -19,8 +19,6 @@
  */
 package org.sonar.server.rule.ws;
 
-import org.apache.ibatis.session.ResultContext;
-import org.apache.ibatis.session.ResultHandler;
 import org.sonar.api.server.ws.Request;
 import org.sonar.api.server.ws.Response;
 import org.sonar.api.server.ws.WebService;
@@ -57,18 +55,15 @@ public class ListAction implements RulesWsAction {
     final ListResponse.Builder listResponseBuilder = ListResponse.newBuilder();
     final ListResponse.Rule.Builder ruleBuilder = ListResponse.Rule.newBuilder();
     try {
-      dbClient.ruleDao().selectEnabled(dbSession, new ResultHandler() {
-        @Override
-        public void handleResult(ResultContext resultContext) {
-          RuleDto dto = (RuleDto) resultContext.getResultObject();
-          ruleBuilder
-            .clear()
-            .setRepository(dto.getRepositoryKey())
-            .setKey(dto.getRuleKey())
-            .setName(nullToEmpty(dto.getName()))
-            .setInternalKey(nullToEmpty(dto.getConfigKey()));
-          listResponseBuilder.addRules(ruleBuilder.build());
-        }
+      dbClient.ruleDao().selectEnabled(dbSession, resultContext -> {
+        RuleDto dto = (RuleDto) resultContext.getResultObject();
+        ruleBuilder
+          .clear()
+          .setRepository(dto.getRepositoryKey())
+          .setKey(dto.getRuleKey())
+          .setName(nullToEmpty(dto.getName()))
+          .setInternalKey(nullToEmpty(dto.getConfigKey()));
+        listResponseBuilder.addRules(ruleBuilder.build());
       });
     } finally {
       dbClient.closeSession(dbSession);
index e0923bf8c200e716d411e55ec6a3b77885cbac98..76ea2367b2023a447f1f8acdf7401880992f4aee 100644 (file)
@@ -19,6 +19,7 @@
  */
 package org.sonar.server.usergroups.ws;
 
+import java.util.Objects;
 import org.sonar.api.server.ws.Request;
 import org.sonar.api.server.ws.Response;
 import org.sonar.api.server.ws.WebService.NewAction;
@@ -117,7 +118,7 @@ public class UpdateAction implements UserGroupsWsAction {
 
   private void updateDefaultGroupIfNeeded(DbSession dbSession, String oldName, String newName) {
     String defaultGroupName = persistentSettings.getString(CORE_DEFAULT_GROUP);
-    if (defaultGroupName.equals(oldName)) {
+    if (Objects.equals(defaultGroupName, oldName)) {
       persistentSettings.saveProperty(dbSession, CORE_DEFAULT_GROUP, newName);
     }
   }
index a14cab2d373f67c1e584341e519bc1d9fbe5bbdb..df57395d868807fb8da9d5d560e0334ead05e8e4 100644 (file)
@@ -44,6 +44,7 @@ import org.sonar.server.ws.WsTester;
 import static org.mockito.Matchers.any;
 import static org.mockito.Matchers.eq;
 import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
 import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.when;
 
@@ -143,6 +144,21 @@ public class UpdateActionTest {
     verify(settings).saveProperty(any(DbSession.class), eq(DEFAULT_GROUP_NAME_KEY), eq("new-name"));
   }
 
+  @Test
+  public void update_default_group_name_does_not_update_default_group_setting_when_null() throws Exception {
+    when(settings.getString(DEFAULT_GROUP_NAME_KEY)).thenReturn(null);
+    GroupDto existingGroup = groupDao.insert(dbSession, new GroupDto().setName(DEFAULT_GROUP_NAME_VALUE).setDescription("Default group name"));
+    dbSession.commit();
+
+    loginAsAdmin();
+    newRequest()
+      .setParam("id", existingGroup.getId().toString())
+      .setParam("name", "new-name")
+      .execute();
+
+    verify(settings, never()).saveProperty(any(DbSession.class), eq(DEFAULT_GROUP_NAME_KEY), eq("new-name"));
+  }
+
   @Test
   public void require_admin_permission() throws Exception {
     expectedException.expect(ForbiddenException.class);
index 9400dc07c2a79bf614fd25d4005ca685f1a3526b..8c5a2959344275745f94a806374086e452404b00 100644 (file)
@@ -114,7 +114,7 @@ public class ResourceDao extends AbstractDao {
    * The implementation should rather use a new column already containing the root project, see https://jira.sonarsource.com/browse/SONAR-5188.
    */
   @CheckForNull
-  private ResourceDto getRootProjectByComponentKey(DbSession session, String componentKey) {
+  private static ResourceDto getRootProjectByComponentKey(DbSession session, String componentKey) {
     ResourceDto component = selectResource(ResourceQuery.create().setKey(componentKey), session);
     if (component != null) {
       String rootUuid = component.getRootUuid();
index edcba952483d7aea0a55a44ad8dd671f9e9727bb..50760c97313fcdf771c704a09e23e64736e97ba0 100644 (file)
@@ -31,8 +31,6 @@ import org.sonar.db.Database;
 import org.sonar.db.DatabaseUtils;
 import org.sonar.db.version.BaseDataChange;
 import org.sonar.db.version.MassUpdate;
-import org.sonar.db.version.Select;
-import org.sonar.db.version.SqlStatement;
 
 /**
  * Used in the Active Record Migration 710
@@ -62,19 +60,16 @@ public class ReplaceIssueFiltersProjectKeyByUuid extends BaseDataChange {
       massUpdate.select("SELECT f.id, f.data FROM issue_filters f WHERE f.data like '%componentRoots=%'");
       massUpdate.update("UPDATE issue_filters SET data=?, updated_at=? WHERE id=?");
       final PreparedStatement finalPstmt = pstmt;
-      massUpdate.execute(new MassUpdate.Handler() {
-        @Override
-        public boolean handle(Select.Row row, SqlStatement update) throws SQLException {
-          Long id = row.getNullableLong(1);
-          String data = row.getNullableString(2);
-          if (data == null) {
-            return false;
-          }
-          update.setString(1, convertData(finalPstmt, data));
-          update.setDate(2, now);
-          update.setLong(3, id);
-          return true;
+      massUpdate.execute((row, update) -> {
+        Long id = row.getNullableLong(1);
+        String data = row.getNullableString(2);
+        if (data == null) {
+          return false;
         }
+        update.setString(1, convertData(finalPstmt, data));
+        update.setDate(2, now);
+        update.setLong(3, id);
+        return true;
       });
     } finally {
       DbUtils.closeQuietly(connection);
index 4effd8ea1b002c39aa6cef258a186b06234e27ee..9fcc693cc81299f1393cb6128a19872ed99bf7b2 100644 (file)
  */
 package org.sonar.api.measures;
 
-import com.google.common.base.Predicate;
-import com.google.common.collect.Iterables;
 import java.lang.reflect.Field;
 import java.lang.reflect.Modifier;
 import java.util.LinkedList;
 import java.util.List;
-import javax.annotation.Nullable;
+import java.util.NoSuchElementException;
 import org.sonar.api.test.MutableTestPlan;
 import org.sonar.api.utils.SonarException;
 
@@ -1440,7 +1438,7 @@ public final class CoreMetrics {
    * </duplications>
    * }
    * </pre>
-   * 
+   *
    * @deprecated since 4.5. Internal storage of duplication is not an API.
    */
   @Deprecated
@@ -2511,11 +2509,6 @@ public final class CoreMetrics {
   }
 
   public static Metric getMetric(final String key) {
-    return Iterables.find(METRICS, new Predicate<Metric>() {
-      @Override
-      public boolean apply(@Nullable Metric input) {
-        return input != null && input.getKey().equals(key);
-      }
-    });
+    return METRICS.stream().filter(metric -> metric != null && metric.getKey().equals(key)).findFirst().orElseThrow(NoSuchElementException::new);
   }
 }
index 854cef24431c0d0bfa2ce21a70c46e7b88d61c9d..6387ce003d078d6814930945f457b071954d4f05 100644 (file)
 package org.sonar.api.resources;
 
 import java.util.List;
+import java.util.NoSuchElementException;
+import org.junit.Rule;
 import org.junit.Test;
-import org.sonar.api.measures.CoreMetrics;
+import org.junit.rules.ExpectedException;
 import org.sonar.api.measures.Metric;
 
 import static org.assertj.core.api.Assertions.assertThat;
+import static org.sonar.api.measures.CoreMetrics.DIRECTORIES;
+import static org.sonar.api.measures.CoreMetrics.NCLOC;
+import static org.sonar.api.measures.CoreMetrics.getMetric;
+import static org.sonar.api.measures.CoreMetrics.getMetrics;
 
 public class CoreMetricsTest {
 
+  @Rule
+  public ExpectedException expectedException = ExpectedException.none();
+
   @Test
   public void read_metrics_from_class_reflection() {
-    List<Metric> metrics = CoreMetrics.getMetrics();
+    List<Metric> metrics = getMetrics();
     assertThat(metrics.size()).isGreaterThan(100);
-    assertThat(metrics).contains(CoreMetrics.NCLOC, CoreMetrics.DIRECTORIES);
+    assertThat(metrics).contains(NCLOC, DIRECTORIES);
+  }
+
+  @Test
+  public void get_metric_by_key() throws Exception {
+    Metric metric = getMetric("ncloc");
+    assertThat(metric.getKey()).isEqualTo("ncloc");
+  }
+
+  @Test
+  public void fail_get_unknown_metric_by_key() throws Exception {
+    expectedException.expect(NoSuchElementException.class);
+    getMetric("unknown");
   }
 }