From de208873b9be69a92ca00398350fc213187c4220 Mon Sep 17 00:00:00 2001 From: Julien Lancelot Date: Wed, 7 Sep 2016 15:06:57 +0200 Subject: [PATCH] Fix quality flaws --- .../java/org/sonar/server/batch/BatchWs.java | 35 +++--- .../component/ComponentsFinderSort.java | 14 +-- .../component/DefaultComponentFinder.java | 14 +-- .../step/ComputeMeasureVariationsStep.java | 22 ++-- .../step/PersistEventsStep.java | 109 +++++++++--------- .../step/PersistProjectLinksStep.java | 21 ++-- .../step/PersistTestsStep.java | 11 +- .../sonar/server/issue/IssuesFinderSort.java | 26 ++--- .../sonar/server/issue/TransitionAction.java | 16 +-- .../permission/ws/TemplateUsersAction.java | 4 +- .../org/sonar/server/rule/ws/ListAction.java | 23 ++-- .../server/usergroups/ws/UpdateAction.java | 3 +- .../usergroups/ws/UpdateActionTest.java | 16 +++ .../org/sonar/db/component/ResourceDao.java | 2 +- .../ReplaceIssueFiltersProjectKeyByUuid.java | 23 ++-- .../org/sonar/api/measures/CoreMetrics.java | 13 +-- .../sonar/api/resources/CoreMetricsTest.java | 27 ++++- 17 files changed, 185 insertions(+), 194 deletions(-) diff --git a/server/sonar-server/src/main/java/org/sonar/server/batch/BatchWs.java b/server/sonar-server/src/main/java/org/sonar/server/batch/BatchWs.java index 4e7e32b7795..0b8b5bcb13b 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/batch/BatchWs.java +++ b/server/sonar-server/src/main/java/org/sonar/server/batch/BatchWs.java @@ -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 diff --git a/server/sonar-server/src/main/java/org/sonar/server/component/ComponentsFinderSort.java b/server/sonar-server/src/main/java/org/sonar/server/component/ComponentsFinderSort.java index 66bcd75c00e..d29920e9808 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/component/ComponentsFinderSort.java +++ b/server/sonar-server/src/main/java/org/sonar/server/component/ComponentsFinderSort.java @@ -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 sort(Collection components, boolean ascending) { + default List sort(Collection components, boolean ascending) { Ordering 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() { @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 ordering = Ordering.from(String.CASE_INSENSITIVE_ORDER).nullsLast(); if (!ascending) { ordering = ordering.reverse(); diff --git a/server/sonar-server/src/main/java/org/sonar/server/component/DefaultComponentFinder.java b/server/sonar-server/src/main/java/org/sonar/server/component/DefaultComponentFinder.java index 1d719d5661a..57c4fabf708 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/component/DefaultComponentFinder.java +++ b/server/sonar-server/src/main/java/org/sonar/server/component/DefaultComponentFinder.java @@ -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 collections) { + default boolean accept(Component component, Collection 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(); } } diff --git a/server/sonar-server/src/main/java/org/sonar/server/computation/task/projectanalysis/step/ComputeMeasureVariationsStep.java b/server/sonar-server/src/main/java/org/sonar/server/computation/task/projectanalysis/step/ComputeMeasureVariationsStep.java index a34da8128da..26593d0ffc5 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/computation/task/projectanalysis/step/ComputeMeasureVariationsStep.java +++ b/server/sonar-server/src/main/java/org/sonar/server/computation/task/projectanalysis/step/ComputeMeasureVariationsStep.java @@ -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 pastMeasureToMeasureKey = new Function() { - @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 metrics = from(metricRepository.getAll()).filter(NumericMetric.INSTANCE).toList(); + List 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 pastMeasures, int period, MeasuresWithVariationRepository measuresWithVariationRepository) { - Map pastMeasuresByMeasureKey = from(pastMeasures).uniqueIndex(pastMeasureToMeasureKey); + Map pastMeasuresByMeasureKey = pastMeasures + .stream() + .collect(uniqueIndex(m -> new MeasureKey(metricRepository.getById((long) m.getMetricId()).getKey(), null), identity())); for (Metric metric : metrics) { Optional measure = measureRepository.getRawMeasure(component, metric); if (measure.isPresent() && !measure.get().hasVariations()) { diff --git a/server/sonar-server/src/main/java/org/sonar/server/computation/task/projectanalysis/step/PersistEventsStep.java b/server/sonar-server/src/main/java/org/sonar/server/computation/task/projectanalysis/step/PersistEventsStep.java index 3ede645767a..644263f9304 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/computation/task/projectanalysis/step/PersistEventsStep.java +++ b/server/sonar-server/src/main/java/org/sonar/server/computation/task/projectanalysis/step/PersistEventsStep.java @@ -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 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 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())); + } + } + } } diff --git a/server/sonar-server/src/main/java/org/sonar/server/computation/task/projectanalysis/step/PersistProjectLinksStep.java b/server/sonar-server/src/main/java/org/sonar/server/computation/task/projectanalysis/step/PersistProjectLinksStep.java index 403aecf24fa..88a6a22e056 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/computation/task/projectanalysis/step/PersistProjectLinksStep.java +++ b/server/sonar-server/src/main/java/org/sonar/server/computation/task/projectanalysis/step/PersistProjectLinksStep.java @@ -19,14 +19,12 @@ */ 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() { - @Override - public boolean apply(@Nullable ComponentLinkDto input) { - return input != null && input.getType().equals(convertType(link.getType())); - } - }, null); - if (previousLink == null) { + Optional 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); } } diff --git a/server/sonar-server/src/main/java/org/sonar/server/computation/task/projectanalysis/step/PersistTestsStep.java b/server/sonar-server/src/main/java/org/sonar/server/computation/task/projectanalysis/step/PersistTestsStep.java index 2f4925cd134..5db2e83ad00 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/computation/task/projectanalysis/step/PersistTestsStep.java +++ b/server/sonar-server/src/main/java/org/sonar/server/computation/task/projectanalysis/step/PersistTestsStep.java @@ -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); }); } diff --git a/server/sonar-server/src/main/java/org/sonar/server/issue/IssuesFinderSort.java b/server/sonar-server/src/main/java/org/sonar/server/issue/IssuesFinderSort.java index f1d6ace71a8..eb1d30925da 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/issue/IssuesFinderSort.java +++ b/server/sonar-server/src/main/java/org/sonar/server/issue/IssuesFinderSort.java @@ -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 sort(Collection issueDtos, boolean ascending) { + default List sort(Collection issueDtos, boolean ascending) { Ordering 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() { @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 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 ordering = Ordering.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() { @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 ordering = Ordering.natural().nullsLast(); if (!ascending) { ordering = ordering.reverse(); diff --git a/server/sonar-server/src/main/java/org/sonar/server/issue/TransitionAction.java b/server/sonar-server/src/main/java/org/sonar/server/issue/TransitionAction.java index 9fd9ec3500f..b7f84403407 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/issue/TransitionAction.java +++ b/server/sonar-server/src/main/java/org/sonar/server/issue/TransitionAction.java @@ -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() { - @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 properties) { diff --git a/server/sonar-server/src/main/java/org/sonar/server/permission/ws/TemplateUsersAction.java b/server/sonar-server/src/main/java/org/sonar/server/permission/ws/TemplateUsersAction.java index fb82ff7dcc0..71cd78f9c2c 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/permission/ws/TemplateUsersAction.java +++ b/server/sonar-server/src/main/java/org/sonar/server/permission/ws/TemplateUsersAction.java @@ -121,7 +121,7 @@ public class TemplateUsersAction implements PermissionsWsAction { return query.build(); } - private WsPermissions.UsersWsResponse buildResponse(List users, List permissionTemplateUsers, Paging paging) { + private static WsPermissions.UsersWsResponse buildResponse(List users, List permissionTemplateUsers, Paging paging) { Multimap 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 findUsers(DbSession dbSession, PermissionQuery query, PermissionTemplateDto template) { + private List findUsers(DbSession dbSession, PermissionQuery query, PermissionTemplateDto template) { List orderedLogins = dbClient.permissionTemplateDao().selectUserLoginsByQueryAndTemplate(dbSession, query, template.getId()); return Ordering.explicit(orderedLogins).onResultOf(UserDto::getLogin).immutableSortedCopy(dbClient.userDao().selectByLogins(dbSession, orderedLogins)); } diff --git a/server/sonar-server/src/main/java/org/sonar/server/rule/ws/ListAction.java b/server/sonar-server/src/main/java/org/sonar/server/rule/ws/ListAction.java index b459f7a7e22..955bfa08823 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/rule/ws/ListAction.java +++ b/server/sonar-server/src/main/java/org/sonar/server/rule/ws/ListAction.java @@ -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); diff --git a/server/sonar-server/src/main/java/org/sonar/server/usergroups/ws/UpdateAction.java b/server/sonar-server/src/main/java/org/sonar/server/usergroups/ws/UpdateAction.java index e0923bf8c20..76ea2367b20 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/usergroups/ws/UpdateAction.java +++ b/server/sonar-server/src/main/java/org/sonar/server/usergroups/ws/UpdateAction.java @@ -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); } } diff --git a/server/sonar-server/src/test/java/org/sonar/server/usergroups/ws/UpdateActionTest.java b/server/sonar-server/src/test/java/org/sonar/server/usergroups/ws/UpdateActionTest.java index a14cab2d373..df57395d868 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/usergroups/ws/UpdateActionTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/usergroups/ws/UpdateActionTest.java @@ -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); diff --git a/sonar-db/src/main/java/org/sonar/db/component/ResourceDao.java b/sonar-db/src/main/java/org/sonar/db/component/ResourceDao.java index 9400dc07c2a..8c5a2959344 100644 --- a/sonar-db/src/main/java/org/sonar/db/component/ResourceDao.java +++ b/sonar-db/src/main/java/org/sonar/db/component/ResourceDao.java @@ -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(); diff --git a/sonar-db/src/main/java/org/sonar/db/version/v50/ReplaceIssueFiltersProjectKeyByUuid.java b/sonar-db/src/main/java/org/sonar/db/version/v50/ReplaceIssueFiltersProjectKeyByUuid.java index edcba952483..50760c97313 100644 --- a/sonar-db/src/main/java/org/sonar/db/version/v50/ReplaceIssueFiltersProjectKeyByUuid.java +++ b/sonar-db/src/main/java/org/sonar/db/version/v50/ReplaceIssueFiltersProjectKeyByUuid.java @@ -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); diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/measures/CoreMetrics.java b/sonar-plugin-api/src/main/java/org/sonar/api/measures/CoreMetrics.java index 4effd8ea1b0..9fcc693cc81 100644 --- a/sonar-plugin-api/src/main/java/org/sonar/api/measures/CoreMetrics.java +++ b/sonar-plugin-api/src/main/java/org/sonar/api/measures/CoreMetrics.java @@ -19,13 +19,11 @@ */ 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 { * * } * - * + * * @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() { - @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); } } diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/resources/CoreMetricsTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/resources/CoreMetricsTest.java index 854cef24431..6387ce003d0 100644 --- a/sonar-plugin-api/src/test/java/org/sonar/api/resources/CoreMetricsTest.java +++ b/sonar-plugin-api/src/test/java/org/sonar/api/resources/CoreMetricsTest.java @@ -20,18 +20,39 @@ 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 metrics = CoreMetrics.getMetrics(); + List 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"); } } -- 2.39.5