]> source.dussan.org Git - sonarqube.git/commitdiff
remove use of Stream.peek()
authorPierre <pierre.guillot@sonarsource.com>
Tue, 8 Dec 2020 12:01:37 +0000 (13:01 +0100)
committersonartech <sonartech@sonarsource.com>
Wed, 9 Dec 2020 20:07:21 +0000 (20:07 +0000)
server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/issue/ComponentIssuesLoader.java
server/sonar-server-common/src/main/java/org/sonar/server/es/textsearch/ComponentTextSearchQueryFactory.java
server/sonar-server-common/src/main/java/org/sonar/server/issue/workflow/State.java
server/sonar-webserver-auth/src/main/java/org/sonar/server/qualityprofile/BuiltInQProfileInsertImpl.java
server/sonar-webserver-webapi/src/main/java/org/sonar/server/issue/ws/DeleteCommentAction.java
server/sonar-webserver-webapi/src/main/java/org/sonar/server/issue/ws/EditCommentAction.java
server/sonar-webserver-webapi/src/main/java/org/sonar/server/projectanalysis/ws/DeleteEventAction.java
server/sonar-webserver-webapi/src/main/java/org/sonar/server/projectanalysis/ws/UpdateEventAction.java
server/sonar-webserver-webapi/src/main/java/org/sonar/server/setting/ws/SetAction.java
server/sonar-webserver-webapi/src/main/java/org/sonar/server/ui/PageRepository.java
sonar-plugin-api/src/main/java/org/sonar/api/config/PropertyDefinition.java

index 062b535a1fd3ff3f6b7af84a92b5ab242bd83cd9..129b8b42aa52c037ac1dee05a3cf1a896c50b386 100644 (file)
@@ -103,10 +103,8 @@ public class ComponentIssuesLoader {
       .stream()
       .collect(groupingBy(IssueChangeDto::getIssueKey));
 
-    return issues
-      .stream()
-      .peek(i -> setChanges(changeDtoByIssueKey, i))
-      .collect(toList());
+    issues.forEach(i -> setChanges(changeDtoByIssueKey, i));
+    return new ArrayList<>(issues);
   }
 
   /**
@@ -175,7 +173,6 @@ public class ComponentIssuesLoader {
         // TODO to be improved, why setOnDisabledRule(true) is not enough ?
         issue.setBeingClosed(true);
       }
-      // FIXME
       issue.setSelectedAt(System.currentTimeMillis());
       result.add(issue);
     });
@@ -264,7 +261,6 @@ public class ComponentIssuesLoader {
       previousIssueKey = resultObject.getKey();
       DefaultIssue issue = resultObject.toDefaultIssue();
       issue.setLine(line);
-      // FIXME
       issue.setSelectedAt(System.currentTimeMillis());
 
       issues.add(issue);
index 060b0504956c4f24b44060b1721d32dbd657038b..462dd50d37878b11480290910d007b8fc1a0f6ec 100644 (file)
@@ -25,7 +25,6 @@ import java.util.Collections;
 import java.util.List;
 import java.util.Optional;
 import java.util.Set;
-import java.util.concurrent.atomic.AtomicBoolean;
 import org.elasticsearch.index.query.BoolQueryBuilder;
 import org.elasticsearch.index.query.QueryBuilder;
 import org.sonar.server.es.textsearch.ComponentTextSearchFeature.UseCase;
@@ -58,16 +57,15 @@ public class ComponentTextSearchQueryFactory {
 
   private static Optional<QueryBuilder> createQuery(ComponentTextSearchQuery query, ComponentTextSearchFeature[] features, UseCase useCase) {
     BoolQueryBuilder generateResults = boolQuery();
-    AtomicBoolean anyFeatures = new AtomicBoolean();
     Arrays.stream(features)
       .filter(f -> f.getUseCase() == useCase)
-      .peek(f -> anyFeatures.set(true))
       .flatMap(f -> f.getQueries(query))
       .forEach(generateResults::should);
-    if (anyFeatures.get()) {
+    if (!generateResults.should().isEmpty()) {
       return Optional.of(generateResults);
+    } else {
+      return Optional.empty();
     }
-    return Optional.empty();
   }
 
   public static class ComponentTextSearchQuery {
index 2e7dbbf74fada1af8a1573bf76082baac41d60e5..43a7b1c8bcfb18c62b7e66a90ab84d995a113063 100644 (file)
@@ -62,20 +62,14 @@ public class State {
 
   @CheckForNull
   public Transition outAutomaticTransition(Issue issue) {
-    final Transition[] result = new Transition[1];
-    Set<String> keys = new HashSet<>();
-
-    Arrays.stream(outTransitions)
+    List<Transition> transitions = Arrays.stream(outTransitions)
       .filter(Transition::automatic)
-      .filter(transition -> transition.supports(issue))
-      .peek(transition -> result[0] = transition)
-      .filter(transition -> !keys.add(transition.key()))
-      .findAny()
-      .ifPresent(transition -> {
-        throw new IllegalArgumentException("Several automatic transitions are available for issue: " + issue);
-      });
-
-    return result[0];
+      .filter(t -> t.supports(issue))
+      .collect(Collectors.toList());
+    if(transitions.size() > 1){
+      throw new IllegalArgumentException("Several automatic transitions are available for issue: " + issue);
+    }
+    return transitions.size() == 1 ? transitions.get(0) : null;
   }
 
   Transition transition(String transitionKey) {
index 8c3b290b79ed2a4ff59bd9f53bbc264716ff429c..5b368c40f9193dc00c6c348a037e741baf491250 100644 (file)
@@ -20,6 +20,7 @@
 package org.sonar.server.qualityprofile;
 
 import com.google.common.base.Splitter;
+import com.google.common.collect.ImmutableList;
 import com.google.common.collect.ImmutableSet;
 import com.google.common.collect.Sets;
 import java.util.Collections;
@@ -156,15 +157,14 @@ public class BuiltInQProfileInsertImpl implements BuiltInQProfileInsert {
     Map<String, String> valuesByParamKey = activeRule.getParams()
       .stream()
       .collect(MoreCollectors.uniqueIndex(BuiltInQualityProfilesDefinition.OverriddenParam::key, BuiltInQualityProfilesDefinition.OverriddenParam::overriddenValue));
-    return ruleRepository.getRuleParams(activeRule.getRuleKey())
+    List<ActiveRuleParamDto> rules = ruleRepository.getRuleParams(activeRule.getRuleKey())
       .stream()
-      .map(param -> {
-        String activeRuleValue = valuesByParamKey.get(param.getName());
-        return createParamDto(param, activeRuleValue == null ? param.getDefaultValue() : activeRuleValue);
-      })
+      .map(param -> createParamDto(param, Optional.ofNullable(valuesByParamKey.get(param.getName())).orElse(param.getDefaultValue())))
       .filter(Objects::nonNull)
-      .peek(paramDto -> dbClient.activeRuleDao().insertParam(session, activeRuleDto, paramDto))
-      .collect(MoreCollectors.toList());
+      .collect(Collectors.toList());
+
+    rules.forEach(paramDto -> dbClient.activeRuleDao().insertParam(session, activeRuleDto, paramDto));
+    return rules;
   }
 
   @CheckForNull
index 7cd18b5c262865edf52ed0eb25a8c088bbfb26ac..02c6e2370ddc39c785b7891719c148072ed1b7d7 100644 (file)
@@ -21,14 +21,10 @@ package org.sonar.server.issue.ws;
 
 import com.google.common.io.Resources;
 import java.util.Objects;
-import java.util.function.Consumer;
-import java.util.function.Function;
-import java.util.stream.Stream;
 import org.sonar.api.server.ws.Change;
 import org.sonar.api.server.ws.Request;
 import org.sonar.api.server.ws.Response;
 import org.sonar.api.server.ws.WebService;
-import org.sonar.core.util.stream.MoreCollectors;
 import org.sonar.db.DbClient;
 import org.sonar.db.DbSession;
 import org.sonar.db.issue.IssueChangeDto;
@@ -84,24 +80,20 @@ public class DeleteCommentAction implements IssuesWsAction {
   public void handle(Request request, Response response) {
     userSession.checkLoggedIn();
     try (DbSession dbSession = dbClient.openSession(false)) {
-      IssueDto issueDto = Stream.of(request)
-        .map(loadCommentData(dbSession))
-        .peek(deleteComment(dbSession))
-        .collect(MoreCollectors.toOneElement())
-        .getIssueDto();
+      CommentData commentData = loadCommentData(dbSession, request);
+      deleteComment(dbSession, commentData);
+      IssueDto issueDto = commentData.getIssueDto();
       responseWriter.write(issueDto.getKey(), new SearchResponseData(issueDto), request, response);
     }
   }
 
-  private Function<Request, CommentData> loadCommentData(DbSession dbSession) {
-    return request -> new CommentData(dbSession, request.mandatoryParam(PARAM_COMMENT));
+  private CommentData loadCommentData(DbSession dbSession, Request request) {
+    return new CommentData(dbSession, request.mandatoryParam(PARAM_COMMENT));
   }
 
-  private Consumer<CommentData> deleteComment(DbSession dbSession) {
-    return commentData -> {
-      dbClient.issueChangeDao().delete(dbSession, commentData.getIssueChangeDto().getKey());
-      dbSession.commit();
-    };
+  private void deleteComment(DbSession dbSession, CommentData commentData) {
+    dbClient.issueChangeDao().delete(dbSession, commentData.getIssueChangeDto().getKey());
+    dbSession.commit();
   }
 
   private class CommentData {
index 32507be1e70abc56e3fc04a78cc14bfbd4e998ff..74c3af754257cad2502627ccdb2414b16ece43c3 100644 (file)
@@ -21,8 +21,6 @@ package org.sonar.server.issue.ws;
 
 import com.google.common.io.Resources;
 import java.util.Objects;
-import java.util.function.Consumer;
-import java.util.function.Function;
 import java.util.stream.Stream;
 import org.sonar.api.server.ws.Change;
 import org.sonar.api.server.ws.Request;
@@ -94,35 +92,28 @@ public class EditCommentAction implements IssuesWsAction {
   public void handle(Request request, Response response) {
     userSession.checkLoggedIn();
     try (DbSession dbSession = dbClient.openSession(false)) {
-      IssueDto issueDto = Stream.of(request)
-        .map(toWsRequest())
-        .map(loadCommentData(dbSession))
-        .peek(updateComment(dbSession))
-        .collect(MoreCollectors.toOneElement())
-        .getIssueDto();
+      CommentData commentData = loadCommentData(dbSession, toWsRequest(request));
+      updateComment(dbSession, commentData);
+      IssueDto issueDto = commentData.getIssueDto();
       responseWriter.write(issueDto.getKey(), new SearchResponseData(issueDto), request, response);
     }
   }
 
-  private Function<EditCommentRequest, CommentData> loadCommentData(DbSession dbSession) {
-    return request -> new CommentData(dbSession, request);
+  private CommentData loadCommentData(DbSession dbSession, EditCommentRequest request) {
+    return new CommentData(dbSession, request);
   }
 
-  private Consumer<CommentData> updateComment(DbSession dbSession) {
-    return commentData -> {
-      commentData.getIssueChangeDto().setUpdatedAt(system2.now());
-      commentData.getIssueChangeDto().setChangeData(commentData.getRequest().getText());
-      dbClient.issueChangeDao().update(dbSession, commentData.getIssueChangeDto());
-      dbSession.commit();
-    };
+  private void updateComment(DbSession dbSession, CommentData commentData) {
+    commentData.getIssueChangeDto().setUpdatedAt(system2.now());
+    commentData.getIssueChangeDto().setChangeData(commentData.getRequest().getText());
+    dbClient.issueChangeDao().update(dbSession, commentData.getIssueChangeDto());
+    dbSession.commit();
   }
 
-  private static Function<Request, EditCommentRequest> toWsRequest() {
-    return request -> {
-      EditCommentRequest wsRequest = new EditCommentRequest(request.mandatoryParam(PARAM_COMMENT), request.mandatoryParam(PARAM_TEXT));
-      checkArgument(!isNullOrEmpty(wsRequest.getText()), "Cannot set empty comment to an issue");
-      return wsRequest;
-    };
+  private static EditCommentRequest toWsRequest(Request request) {
+    EditCommentRequest wsRequest = new EditCommentRequest(request.mandatoryParam(PARAM_COMMENT), request.mandatoryParam(PARAM_TEXT));
+    checkArgument(!isNullOrEmpty(wsRequest.getText()), "Cannot set empty comment to an issue");
+    return wsRequest;
   }
 
   private class CommentData {
index 7a4a1b54dd87c9f83010215c0ed7c534d9d0d639..85509c524dea6080ef180441d7eb36d95b942704 100644 (file)
@@ -19,8 +19,6 @@
  */
 package org.sonar.server.projectanalysis.ws;
 
-import java.util.function.Consumer;
-import java.util.stream.Stream;
 import org.sonar.api.server.ws.Request;
 import org.sonar.api.server.ws.Response;
 import org.sonar.api.server.ws.WebService;
@@ -35,9 +33,9 @@ import org.sonar.server.user.UserSession;
 
 import static com.google.common.base.Preconditions.checkArgument;
 import static java.lang.String.format;
-import static org.sonar.server.projectanalysis.ws.EventValidator.checkModifiable;
 import static org.sonar.server.projectanalysis.ws.EventCategory.OTHER;
 import static org.sonar.server.projectanalysis.ws.EventCategory.VERSION;
+import static org.sonar.server.projectanalysis.ws.EventValidator.checkModifiable;
 import static org.sonar.server.projectanalysis.ws.ProjectAnalysesWsParameters.PARAM_EVENT;
 
 public class DeleteEventAction implements ProjectAnalysesWsAction {
@@ -74,10 +72,10 @@ public class DeleteEventAction implements ProjectAnalysesWsAction {
   public void handle(Request request, Response response) throws Exception {
     String eventP = request.mandatoryParam(PARAM_EVENT);
     try (DbSession dbSession = dbClient.openSession(false)) {
-      Stream.of(getEvent(dbSession, eventP))
-              .peek(checkPermissions())
-              .peek(checkModifiable())
-              .forEach(event -> deleteEvent(dbSession, event));
+      EventDto event = getEvent(dbSession, eventP);
+      userSession.checkComponentUuidPermission(UserRole.ADMIN, event.getComponentUuid());
+      checkModifiable().accept(event);
+      deleteEvent(dbSession, event);
     }
     response.noContent();
   }
@@ -99,7 +97,4 @@ public class DeleteEventAction implements ProjectAnalysesWsAction {
     dbSession.commit();
   }
 
-  private Consumer<EventDto> checkPermissions() {
-    return event -> userSession.checkComponentUuidPermission(UserRole.ADMIN, event.getComponentUuid());
-  }
 }
index 858d40b29440d44f012c3c20f0a2b9d27e92ee37..e44ed554a2e56911c887e3248040d46e58d6f167 100644 (file)
@@ -20,6 +20,7 @@
 package org.sonar.server.projectanalysis.ws;
 
 import java.util.List;
+import java.util.Optional;
 import java.util.function.Consumer;
 import java.util.function.Function;
 import java.util.function.Predicate;
@@ -100,17 +101,14 @@ public class UpdateEventAction implements ProjectAnalysesWsAction {
 
   private UpdateEventResponse doHandle(UpdateEventRequest request) {
     try (DbSession dbSession = dbClient.openSession(false)) {
-      return Stream
-        .of(getDbEvent(dbSession, request))
-        .peek(checkPermissions())
-        .peek(checkModifiable())
-        .peek(checkVersionNameLength(request))
-        .map(updateNameAndDescription(request))
-        .peek(checkNonConflictingOtherEvents(dbSession))
-        .peek(updateInDb(dbSession))
-        .map(toWsResponse())
-        .findAny()
-        .orElseThrow(() -> new IllegalStateException("Event not found"));
+      EventDto event = Optional.ofNullable(getDbEvent(dbSession, request)).orElseThrow(() -> new IllegalStateException("Event not found"));
+      checkPermissions().accept(event);
+      checkModifiable().accept(event);
+      checkVersionNameLength(request).accept(event);
+      event = updateNameAndDescription(request).apply(event);
+      checkNonConflictingOtherEvents(dbSession).accept(event);
+      updateInDb(dbSession).accept(event);
+      return toWsResponse().apply(event);
     }
   }
 
index fbc75675971bdde99b2527c36858e6dc8091b10e..a0df64e67a24e2fcf0444ad40816b785bb36d237 100644 (file)
@@ -94,13 +94,13 @@ public class SetAction implements SettingsWsAction {
   public void define(WebService.NewController context) {
     WebService.NewAction action = context.createAction("set")
       .setDescription("Update a setting value.<br>" +
-          "Either '%s' or '%s' must be provided.<br> " +
-          "The settings defined in conf/sonar.properties are read-only and can't be changed.<br/>" +
-          "Requires one of the following permissions: " +
-          "<ul>" +
-          "<li>'Administer System'</li>" +
-          "<li>'Administer' rights on the specified component</li>" +
-          "</ul>",
+        "Either '%s' or '%s' must be provided.<br> " +
+        "The settings defined in conf/sonar.properties are read-only and can't be changed.<br/>" +
+        "Requires one of the following permissions: " +
+        "<ul>" +
+        "<li>'Administer System'</li>" +
+        "<li>'Administer' rights on the specified component</li>" +
+        "</ul>",
         PARAM_VALUE, PARAM_VALUES)
       .setSince("6.1")
       .setChangelog(
@@ -212,13 +212,16 @@ public class SetAction implements SettingsWsAction {
     Set<String> fieldKeys = definition.fields().stream().map(PropertyFieldDefinition::key).collect(Collectors.toSet());
     ListMultimap<String, String> valuesByFieldKeys = ArrayListMultimap.create(fieldKeys.size(), request.getFieldValues().size() * fieldKeys.size());
 
-    request.getFieldValues().stream()
+    List<Map<String, String>> maps = request.getFieldValues().stream()
       .map(oneFieldValues -> readOneFieldValues(oneFieldValues, request.getKey()))
-      .peek(map -> checkRequest(map.values().stream().anyMatch(StringUtils::isNotBlank), MSG_NO_EMPTY_VALUE))
-      .flatMap(map -> map.entrySet().stream())
-      .peek(entry -> valuesByFieldKeys.put(entry.getKey(), entry.getValue()))
-      .forEach(entry -> checkRequest(fieldKeys.contains(entry.getKey()), "Unknown field key '%s' for setting '%s'", entry.getKey(), request.getKey()));
+      .collect(Collectors.toList());
 
+    for (Map<String, String> map : maps) {
+      checkRequest(map.values().stream().anyMatch(StringUtils::isNotBlank), MSG_NO_EMPTY_VALUE);
+    }
+    List<Map.Entry<String, String>> entries = maps.stream().flatMap(map -> map.entrySet().stream()).collect(Collectors.toList());
+    entries.forEach(entry -> valuesByFieldKeys.put(entry.getKey(), entry.getValue()));
+    entries.forEach(entry -> checkRequest(fieldKeys.contains(entry.getKey()), "Unknown field key '%s' for setting '%s'", entry.getKey(), request.getKey()));
     checkFieldType(request, definition, valuesByFieldKeys);
   }
 
index 5723dfa97e4af800c0a6e5877b948153db85d042..070acdd6cda2b6116620e90aca9b11510a3862b7 100644 (file)
@@ -21,8 +21,8 @@ package org.sonar.server.ui;
 
 import com.google.common.annotations.VisibleForTesting;
 import com.google.common.collect.ImmutableList;
+import java.util.ArrayList;
 import java.util.List;
-import java.util.stream.Stream;
 import javax.annotation.Nullable;
 import org.sonar.api.Startable;
 import org.sonar.api.server.ServerSide;
@@ -31,8 +31,8 @@ import org.sonar.api.web.page.Page;
 import org.sonar.api.web.page.Page.Qualifier;
 import org.sonar.api.web.page.Page.Scope;
 import org.sonar.api.web.page.PageDefinition;
-import org.sonar.core.platform.PluginRepository;
 import org.sonar.core.extension.CoreExtensionRepository;
+import org.sonar.core.platform.PluginRepository;
 import org.sonar.server.ui.page.CorePageDefinition;
 
 import static com.google.common.base.Preconditions.checkState;
@@ -105,11 +105,12 @@ public class PageRepository implements Startable {
     corePageDefinitions.stream()
       .map(CorePageDefinition::getPageDefinition)
       .forEach(definition -> definition.define(coreContext));
-    pages = Stream.concat(
-      context.getPages().stream().peek(this::checkPluginExists),
-      coreContext.getPages().stream().peek(this::checkCoreExtensionExists))
-      .sorted(comparing(Page::getKey))
-      .collect(toList());
+    context.getPages().forEach(this::checkPluginExists);
+    coreContext.getPages().forEach(this::checkCoreExtensionExists);
+    pages = new ArrayList<>();
+    pages.addAll(context.getPages());
+    pages.addAll(coreContext.getPages());
+    pages.sort(comparing(Page::getKey));
   }
 
   @Override
index 45d5fcc31848b2dfa13f6d745bf9ac4ded53110b..cb20a4195f648cde82aaec70d3bc9646afabcfc1 100644 (file)
@@ -20,6 +20,7 @@
 package org.sonar.api.config;
 
 import java.util.ArrayList;
+import java.util.Arrays;
 import java.util.EnumMap;
 import java.util.LinkedHashSet;
 import java.util.List;
@@ -510,11 +511,15 @@ public final class PropertyDefinition {
     }
 
     private static void addQualifiers(List<String> target, String first, String... rest) {
-      Stream.concat(Stream.of(first), stream(rest)).peek(PropertyDefinition.Builder::validateQualifier).forEach(target::add);
+      List<String> qualifiers = new ArrayList<>();
+      qualifiers.add(first);
+      qualifiers.addAll(Arrays.asList(rest));
+      addQualifiers(target, qualifiers);
     }
 
     private static void addQualifiers(List<String> target, List<String> qualifiers) {
-      qualifiers.stream().peek(PropertyDefinition.Builder::validateQualifier).forEach(target::add);
+      qualifiers.forEach(PropertyDefinition.Builder::validateQualifier);
+      target.addAll(qualifiers);
     }
 
     private static void validateQualifier(@Nullable String qualifier) {