From 50b12df3787d87958fcef7fbf8c00598b141f1ee Mon Sep 17 00:00:00 2001 From: Duarte Meneses Date: Fri, 30 Sep 2022 12:23:26 -0500 Subject: SONAR-17352 Refactor component keys to not include branch suffix --- .../java/org/sonar/server/batch/IssuesAction.java | 5 +- .../sonar/server/component/ComponentFinder.java | 32 +++- .../org/sonar/server/component/ws/ShowAction.java | 8 + .../server/component/ws/SuggestionsAction.java | 2 +- .../org/sonar/server/component/ws/TreeAction.java | 31 ++-- .../server/developers/ws/SearchEventsAction.java | 48 +++--- .../server/duplication/ws/DuplicationsParser.java | 15 +- .../server/duplication/ws/ShowResponseBuilder.java | 5 +- .../org/sonar/server/hotspot/ws/SearchAction.java | 27 ++- .../sonar/server/issue/ws/SearchResponseData.java | 6 +- .../server/issue/ws/SearchResponseFormat.java | 13 +- .../server/issue/ws/SearchResponseLoader.java | 7 +- .../sonar/server/measure/ws/ComponentAction.java | 5 +- .../server/measure/ws/ComponentTreeAction.java | 31 +++- .../sonar/server/measure/ws/ComponentTreeData.java | 12 ++ .../org/sonar/server/setting/ws/ValuesAction.java | 18 +- .../org/sonar/server/ui/ws/ComponentAction.java | 19 ++- .../server/component/ComponentFinderTest.java | 31 +++- .../server/component/ComponentUpdaterTest.java | 2 +- .../sonar/server/component/ws/TreeActionTest.java | 15 +- .../duplication/ws/DuplicationsParserTest.java | 3 +- .../server/duplication/ws/ShowActionTest.java | 3 +- .../sonar/server/favorite/ws/RemoveActionTest.java | 12 -- .../sonar/server/hotspot/ws/SearchActionTest.java | 41 +++-- .../issue/ws/SearchActionComponentsTest.java | 14 +- .../sonar/server/issue/ws/SearchActionTest.java | 35 ++-- .../SearchResponseFormatFormatOperationTest.java | 82 +++++----- .../server/measure/ws/ComponentTreeActionTest.java | 2 +- .../setting/TestProjectConfigurationLoader.java | 11 +- .../org/sonar/server/setting/ws/SetActionTest.java | 2 +- .../sonar/server/setting/ws/ValuesActionTest.java | 181 ++++++++++----------- 31 files changed, 388 insertions(+), 330 deletions(-) (limited to 'server/sonar-webserver-webapi') diff --git a/server/sonar-webserver-webapi/src/main/java/org/sonar/server/batch/IssuesAction.java b/server/sonar-webserver-webapi/src/main/java/org/sonar/server/batch/IssuesAction.java index 8062598b869..7e87e861928 100644 --- a/server/sonar-webserver-webapi/src/main/java/org/sonar/server/batch/IssuesAction.java +++ b/server/sonar-webserver-webapi/src/main/java/org/sonar/server/batch/IssuesAction.java @@ -179,9 +179,6 @@ public class IssuesAction implements BatchWsAction { private ComponentDto loadComponent(DbSession dbSession, Request request) { String componentKey = request.mandatoryParam(PARAM_KEY); String branch = request.param(PARAM_BRANCH); - if (branch != null) { - return componentFinder.getByKeyAndBranch(dbSession, componentKey, branch); - } - return componentFinder.getByKey(dbSession, componentKey); + return componentFinder.getByKeyAndOptionalBranchOrPullRequest(dbSession, componentKey, branch, null); } } diff --git a/server/sonar-webserver-webapi/src/main/java/org/sonar/server/component/ComponentFinder.java b/server/sonar-webserver-webapi/src/main/java/org/sonar/server/component/ComponentFinder.java index b3daf2cb87d..b61e817fccf 100644 --- a/server/sonar-webserver-webapi/src/main/java/org/sonar/server/component/ComponentFinder.java +++ b/server/sonar-webserver-webapi/src/main/java/org/sonar/server/component/ComponentFinder.java @@ -58,7 +58,7 @@ public class ComponentFinder { checkByUuidOrKey(componentUuid, componentKey, parameterNames); if (componentUuid != null) { - return getByUuid(dbSession, checkParamNotEmpty(componentUuid, parameterNames.getUuidParam())); + return getByUuidFromMainBranch(dbSession, checkParamNotEmpty(componentUuid, parameterNames.getUuidParam())); } return getByKey(dbSession, checkParamNotEmpty(componentKey, parameterNames.getKeyParam())); @@ -100,6 +100,11 @@ public class ComponentFinder { return value; } + public BranchDto getBranchByUuid(DbSession dbSession, String branchUuid) { + return dbClient.branchDao().selectByUuid(dbSession, branchUuid) + .orElseThrow(() -> new NotFoundException(String.format("Branch uuid '%s' not found", branchUuid))); + } + public BranchDto getBranchOrPullRequest(DbSession dbSession, ComponentDto project, @Nullable String branchKey, @Nullable String pullRequestKey) { return getBranchOrPullRequest(dbSession, project.uuid(), project.getKey(), branchKey, pullRequestKey); } @@ -137,11 +142,14 @@ public class ComponentFinder { return checkComponent(dbClient.componentDao().selectByKey(dbSession, key), "%s key '%s' not found", label, key); } - public ComponentDto getByUuid(DbSession dbSession, String uuid) { - return getByUuid(dbSession, uuid, LABEL_COMPONENT); + /** + * This method only returns components in main branches. + */ + public ComponentDto getByUuidFromMainBranch(DbSession dbSession, String uuid) { + return getByUuidFromMainBranch(dbSession, uuid, LABEL_COMPONENT); } - private ComponentDto getByUuid(DbSession dbSession, String uuid, String label) { + private ComponentDto getByUuidFromMainBranch(DbSession dbSession, String uuid, String label) { return checkComponent(dbClient.componentDao().selectByUuid(dbSession, uuid), "%s id '%s' not found", label, uuid); } @@ -155,7 +163,7 @@ public class ComponentFinder { public ComponentDto getRootComponentByUuidOrKey(DbSession dbSession, @Nullable String projectUuid, @Nullable String projectKey) { ComponentDto project; if (projectUuid != null) { - project = getByUuid(dbSession, projectUuid, LABEL_PROJECT); + project = getByUuidFromMainBranch(dbSession, projectUuid, LABEL_PROJECT); } else { project = getByKey(dbSession, projectKey, LABEL_PROJECT); } @@ -204,14 +212,22 @@ public class ComponentFinder { checkArgument(branch == null || pullRequest == null, "Either branch or pull request can be provided, not both"); if (branch != null) { return getByKeyAndBranch(dbSession, key, branch); - } - if (pullRequest != null) { + } else if (pullRequest != null) { return getByKeyAndPullRequest(dbSession, key, pullRequest); } - return getByKey(dbSession, key); } + public Optional getOptionalByKeyAndOptionalBranchOrPullRequest(DbSession dbSession, String key, @Nullable String branch, @Nullable String pullRequest) { + checkArgument(branch == null || pullRequest == null, "Either branch or pull request can be provided, not both"); + if (branch != null) { + return dbClient.componentDao().selectByKeyAndBranch(dbSession, key, branch); + } else if (pullRequest != null) { + return dbClient.componentDao().selectByKeyAndPullRequest(dbSession, key, pullRequest); + } + return dbClient.componentDao().selectByKey(dbSession, key); + } + public enum ParamNames { PROJECT_ID_AND_KEY("projectId", "projectKey"), PROJECT_UUID_AND_KEY("projectUuid", "projectKey"), diff --git a/server/sonar-webserver-webapi/src/main/java/org/sonar/server/component/ws/ShowAction.java b/server/sonar-webserver-webapi/src/main/java/org/sonar/server/component/ws/ShowAction.java index a4e4746278b..ca42f019916 100644 --- a/server/sonar-webserver-webapi/src/main/java/org/sonar/server/component/ws/ShowAction.java +++ b/server/sonar-webserver-webapi/src/main/java/org/sonar/server/component/ws/ShowAction.java @@ -33,6 +33,7 @@ import org.sonar.api.server.ws.WebService; import org.sonar.api.web.UserRole; import org.sonar.db.DbClient; import org.sonar.db.DbSession; +import org.sonar.db.component.BranchDto; import org.sonar.db.component.ComponentDto; import org.sonar.db.component.SnapshotDto; import org.sonar.db.project.ProjectDto; @@ -152,6 +153,13 @@ public class ShowAction implements ComponentsWsAction { Optional parentProject = dbClient.projectDao().selectByUuid(dbSession, ofNullable(component.getMainBranchProjectUuid()).orElse(component.branchUuid())); boolean needIssueSync = needIssueSync(dbSession, component, parentProject.orElse(null)); + if (component.getCopyComponentUuid() != null) { + String branch = dbClient.branchDao().selectByUuid(dbSession, component.getCopyComponentUuid()) + .map(BranchDto::getKey) + .orElse(null); + componentDtoToWsComponent(component, parentProject.orElse(null), lastAnalysis, branch, null) + .setNeedIssueSync(needIssueSync); + } return componentDtoToWsComponent(component, parentProject.orElse(null), lastAnalysis, request.branch, request.pullRequest) .setNeedIssueSync(needIssueSync); } diff --git a/server/sonar-webserver-webapi/src/main/java/org/sonar/server/component/ws/SuggestionsAction.java b/server/sonar-webserver-webapi/src/main/java/org/sonar/server/component/ws/SuggestionsAction.java index 400e85f2557..bd5c813bf02 100644 --- a/server/sonar-webserver-webapi/src/main/java/org/sonar/server/component/ws/SuggestionsAction.java +++ b/server/sonar-webserver-webapi/src/main/java/org/sonar/server/component/ws/SuggestionsAction.java @@ -89,7 +89,7 @@ public class SuggestionsAction implements ComponentsWsAction { private final UserSession userSession; private final ResourceTypes resourceTypes; - private DbClient dbClient; + private final DbClient dbClient; public SuggestionsAction(DbClient dbClient, ComponentIndex index, FavoriteFinder favoriteFinder, UserSession userSession, ResourceTypes resourceTypes) { this.dbClient = dbClient; diff --git a/server/sonar-webserver-webapi/src/main/java/org/sonar/server/component/ws/TreeAction.java b/server/sonar-webserver-webapi/src/main/java/org/sonar/server/component/ws/TreeAction.java index 246af12da7b..16635cf1c3c 100644 --- a/server/sonar-webserver-webapi/src/main/java/org/sonar/server/component/ws/TreeAction.java +++ b/server/sonar-webserver-webapi/src/main/java/org/sonar/server/component/ws/TreeAction.java @@ -31,6 +31,7 @@ import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; +import java.util.stream.Collectors; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import org.sonar.api.resources.Qualifiers; @@ -45,6 +46,7 @@ import org.sonar.core.i18n.I18n; import org.sonar.core.util.stream.MoreCollectors; import org.sonar.db.DbClient; import org.sonar.db.DbSession; +import org.sonar.db.component.BranchDto; import org.sonar.db.component.ComponentDto; import org.sonar.db.component.ComponentTreeQuery; import org.sonar.db.component.ComponentTreeQuery.Strategy; @@ -67,8 +69,8 @@ import static org.sonar.server.component.ws.ComponentDtoToWsComponent.projectOrA import static org.sonar.server.ws.KeyExamples.KEY_BRANCH_EXAMPLE_001; import static org.sonar.server.ws.KeyExamples.KEY_PROJECT_EXAMPLE_001; import static org.sonar.server.ws.KeyExamples.KEY_PULL_REQUEST_EXAMPLE_001; -import static org.sonar.server.ws.WsParameterBuilder.createQualifiersParameter; import static org.sonar.server.ws.WsParameterBuilder.QualifierParameterContext.newQualifierParameterContext; +import static org.sonar.server.ws.WsParameterBuilder.createQualifiersParameter; import static org.sonar.server.ws.WsUtils.writeProtobuf; import static org.sonarqube.ws.client.component.ComponentsWsParameters.ACTION_TREE; import static org.sonarqube.ws.client.component.ComponentsWsParameters.PARAM_BRANCH; @@ -113,8 +115,8 @@ public class TreeAction implements ComponentsWsAction { public void define(WebService.NewController context) { WebService.NewAction action = context.createAction(ACTION_TREE) .setDescription(format("Navigate through components based on the chosen strategy.
" + - "Requires the following permission: 'Browse' on the specified project.
" + - "When limiting search with the %s parameter, directories are not returned.", + "Requires the following permission: 'Browse' on the specified project.
" + + "When limiting search with the %s parameter, directories are not returned.", Param.TEXT_QUERY)) .setSince("5.4") .setResponseExample(getClass().getResource("tree-example.json")) @@ -226,29 +228,38 @@ public class TreeAction implements ComponentsWsAction { .setTotal(paging.total()) .build(); - response.setBaseComponent(toWsComponent(dbSession, baseComponent, referenceComponentsByUuid, request)); + Map branchKeyByReferenceUuid = dbClient.branchDao().selectByUuids(dbSession, referenceComponentsByUuid.keySet()) + .stream() + .collect(Collectors.toMap(BranchDto::getUuid, BranchDto::getBranchKey)); + + response.setBaseComponent(toWsComponent(dbSession, baseComponent, referenceComponentsByUuid, branchKeyByReferenceUuid, request)); for (ComponentDto dto : components) { - response.addComponents(toWsComponent(dbSession, dto, referenceComponentsByUuid, request)); + response.addComponents(toWsComponent(dbSession, dto, referenceComponentsByUuid, branchKeyByReferenceUuid, request)); } return response.build(); } private Components.Component.Builder toWsComponent(DbSession dbSession, ComponentDto component, - Map referenceComponentsByUuid, Request request) { + Map referenceComponentsByUuid, Map branchKeyByReferenceUuid, Request request) { + + ComponentDto referenceComponent = referenceComponentsByUuid.get(component.getCopyComponentUuid()); Components.Component.Builder wsComponent; - if (component.getMainBranchProjectUuid() == null && component.isRootProject() && - PROJECT_OR_APP_QUALIFIERS.contains(component.qualifier())) { + if (component.getMainBranchProjectUuid() == null && component.isRootProject() && PROJECT_OR_APP_QUALIFIERS.contains(component.qualifier())) { ProjectDto projectDto = componentFinder.getProjectOrApplicationByKey(dbSession, component.getKey()); wsComponent = projectOrAppToWsComponent(projectDto, null); } else { Optional parentProject = dbClient.projectDao().selectByUuid(dbSession, ofNullable(component.getMainBranchProjectUuid()).orElse(component.branchUuid())); - wsComponent = componentDtoToWsComponent(component, parentProject.orElse(null), null, request.branch, request.pullRequest); + + if (referenceComponent != null) { + wsComponent = componentDtoToWsComponent(component, parentProject.orElse(null), null, branchKeyByReferenceUuid.get(referenceComponent.uuid()), null); + } else { + wsComponent = componentDtoToWsComponent(component, parentProject.orElse(null), null, request.branch, request.pullRequest); + } } - ComponentDto referenceComponent = referenceComponentsByUuid.get(component.getCopyComponentUuid()); if (referenceComponent != null) { wsComponent.setRefId(referenceComponent.uuid()); wsComponent.setRefKey(referenceComponent.getKey()); diff --git a/server/sonar-webserver-webapi/src/main/java/org/sonar/server/developers/ws/SearchEventsAction.java b/server/sonar-webserver-webapi/src/main/java/org/sonar/server/developers/ws/SearchEventsAction.java index ee557d8bcc4..acafbc18aa8 100644 --- a/server/sonar-webserver-webapi/src/main/java/org/sonar/server/developers/ws/SearchEventsAction.java +++ b/server/sonar-webserver-webapi/src/main/java/org/sonar/server/developers/ws/SearchEventsAction.java @@ -23,6 +23,7 @@ import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.Date; import java.util.HashMap; +import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.function.Predicate; @@ -37,9 +38,9 @@ import org.sonar.api.web.UserRole; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.component.BranchDto; -import org.sonar.db.component.ComponentDto; import org.sonar.db.component.SnapshotDto; import org.sonar.db.event.EventDto; +import org.sonar.db.project.ProjectDto; import org.sonar.server.issue.index.IssueIndex; import org.sonar.server.issue.index.IssueIndexSyncProgressChecker; import org.sonar.server.issue.index.ProjectStatistics; @@ -77,8 +78,7 @@ public class SearchEventsAction implements DevelopersWsAction { private final IssueIndex issueIndex; private final IssueIndexSyncProgressChecker issueIndexSyncProgressChecker; - public SearchEventsAction(DbClient dbClient, UserSession userSession, Server server, IssueIndex issueIndex, - IssueIndexSyncProgressChecker issueIndexSyncProgressChecker) { + public SearchEventsAction(DbClient dbClient, UserSession userSession, Server server, IssueIndex issueIndex, IssueIndexSyncProgressChecker issueIndexSyncProgressChecker) { this.dbClient = dbClient; this.userSession = userSession; this.server = server; @@ -132,8 +132,8 @@ public class SearchEventsAction implements DevelopersWsAction { } try (DbSession dbSession = dbClient.openSession(false)) { - List authorizedProjects = searchProjects(dbSession, projectKeys); - Map componentsByUuid = authorizedProjects.stream().collect(uniqueIndex(ComponentDto::uuid)); + List authorizedProjects = searchProjects(dbSession, projectKeys); + Map projectsByUuid = authorizedProjects.stream().collect(uniqueIndex(ProjectDto::getUuid)); List uuidFromPairs = componentUuidFromPairs(fromDates, projectKeys, authorizedProjects); List analyses = dbClient.snapshotDao().selectFinishedByComponentUuidsAndFromDates(dbSession, componentUuids(uuidFromPairs), fromDates(uuidFromPairs)); @@ -145,12 +145,12 @@ public class SearchEventsAction implements DevelopersWsAction { Map branchesByUuids = dbClient.branchDao().selectByUuids(dbSession, projectUuids).stream().collect(uniqueIndex(BranchDto::getUuid)); return Stream.concat( - computeQualityGateChangeEvents(dbSession, componentsByUuid, branchesByUuids, analyses), - computeNewIssuesEvents(componentsByUuid, branchesByUuids, uuidFromPairs)); + computeQualityGateChangeEvents(dbSession, projectsByUuid, branchesByUuids, analyses), + computeNewIssuesEvents(projectsByUuid, branchesByUuids, uuidFromPairs)); } } - private Stream computeQualityGateChangeEvents(DbSession dbSession, Map projectsByUuid, + private Stream computeQualityGateChangeEvents(DbSession dbSession, Map projectsByUuid, Map branchesByUuids, List analyses) { Map eventsByComponentUuid = new HashMap<>(); @@ -167,20 +167,20 @@ public class SearchEventsAction implements DevelopersWsAction { .filter(branchPredicate) .map(e -> { BranchDto branch = branchesByUuids.get(e.getComponentUuid()); - ComponentDto project = projectsByUuid.get(branch.getProjectUuid()); + ProjectDto project = projectsByUuid.get(branch.getProjectUuid()); checkState(project != null, "Found event '%s', for a component that we did not search for", e.getUuid()); return Event.newBuilder() .setCategory(EventCategory.fromLabel(e.getCategory()).name()) .setProject(project.getKey()) - .setMessage(branch.isMain() ? format("Quality Gate status of project '%s' changed to '%s'", project.name(), e.getName()) - : format("Quality Gate status of project '%s' on branch '%s' changed to '%s'", project.name(), branch.getKey(), e.getName())) + .setMessage(branch.isMain() ? format("Quality Gate status of project '%s' changed to '%s'", project.getName(), e.getName()) + : format("Quality Gate status of project '%s' on branch '%s' changed to '%s'", project.getName(), branch.getKey(), e.getName())) .setLink(computeDashboardLink(project, branch)) .setDate(formatDateTime(e.getDate())) .build(); }); } - private Stream computeNewIssuesEvents(Map projectsByUuid, Map branchesByUuids, + private Stream computeNewIssuesEvents(Map projectsByUuid, Map branchesByUuids, List uuidFromPairs) { Map fromsByProjectUuid = uuidFromPairs.stream().collect(Collectors.toMap( UuidFromPair::getComponentUuid, @@ -190,46 +190,46 @@ public class SearchEventsAction implements DevelopersWsAction { .stream() .map(e -> { BranchDto branch = branchesByUuids.get(e.getProjectUuid()); - ComponentDto project = projectsByUuid.get(branch.getProjectUuid()); + ProjectDto project = projectsByUuid.get(branch.getProjectUuid()); long issueCount = e.getIssueCount(); long lastIssueDate = e.getLastIssueDate(); String branchType = branch.getBranchType().equals(PULL_REQUEST) ? "pull request" : "branch"; return Event.newBuilder() .setCategory("NEW_ISSUES") .setMessage(format("You have %s new %s on project '%s'", issueCount, issueCount == 1 ? "issue" : "issues", - project.name()) + (branch.isMain() ? "" : format(" on %s '%s'", branchType, branch.getKey()))) - .setLink(computeIssuesSearchLink(project, branch, fromsByProjectUuid.get(project.uuid()), userSession.getLogin())) + project.getName()) + (branch.isMain() ? "" : format(" on %s '%s'", branchType, branch.getKey()))) + .setLink(computeIssuesSearchLink(project, branch, fromsByProjectUuid.get(project.getUuid()), userSession.getLogin())) .setProject(project.getKey()) .setDate(formatDateTime(lastIssueDate)) .build(); }); } - private List searchProjects(DbSession dbSession, List projectKeys) { - List projects = dbClient.componentDao().selectByKeys(dbSession, projectKeys); - return userSession.keepAuthorizedComponents(UserRole.USER, projects); + private List searchProjects(DbSession dbSession, List projectKeys) { + List projects = dbClient.projectDao().selectProjectsByKeys(dbSession, new HashSet<>(projectKeys)); + return userSession.keepAuthorizedProjects(UserRole.USER, projects); } - private String computeIssuesSearchLink(ComponentDto component, BranchDto branch, long functionalFromDate, String login) { + private String computeIssuesSearchLink(ProjectDto project, BranchDto branch, long functionalFromDate, String login) { String branchParam = branch.getBranchType().equals(PULL_REQUEST) ? "pullRequest" : "branch"; String link = format("%s/project/issues?id=%s&createdAfter=%s&assignees=%s&resolved=false", - server.getPublicRootUrl(), encode(component.getKey()), encode(formatDateTime(functionalFromDate)), encode(login)); + server.getPublicRootUrl(), encode(project.getKey()), encode(formatDateTime(functionalFromDate)), encode(login)); link += branch.isMain() ? "" : format("&%s=%s", branchParam, encode(branch.getKey())); return link; } - private String computeDashboardLink(ComponentDto component, BranchDto branch) { - String link = server.getPublicRootUrl() + "/dashboard?id=" + encode(component.getKey()); + private String computeDashboardLink(ProjectDto project, BranchDto branch) { + String link = server.getPublicRootUrl() + "/dashboard?id=" + encode(project.getKey()); link += branch.isMain() ? "" : format("&branch=%s", encode(branch.getKey())); return link; } - private static List componentUuidFromPairs(List fromDates, List projectKeys, List authorizedProjects) { + private static List componentUuidFromPairs(List fromDates, List projectKeys, List authorizedProjects) { checkRequest(projectKeys.size() == fromDates.size(), "The number of components (%s) and from dates (%s) must be the same.", projectKeys.size(), fromDates.size()); Map fromDatesByProjectKey = IntStream.range(0, projectKeys.size()).boxed() .collect(uniqueIndex(projectKeys::get, fromDates::get)); return authorizedProjects.stream() - .map(dto -> new UuidFromPair(dto.uuid(), fromDatesByProjectKey.get(dto.getKey()))) + .map(dto -> new UuidFromPair(dto.getUuid(), fromDatesByProjectKey.get(dto.getKey()))) .collect(toList(authorizedProjects.size())); } diff --git a/server/sonar-webserver-webapi/src/main/java/org/sonar/server/duplication/ws/DuplicationsParser.java b/server/sonar-webserver-webapi/src/main/java/org/sonar/server/duplication/ws/DuplicationsParser.java index 01adf616c0b..57db08dae40 100644 --- a/server/sonar-webserver-webapi/src/main/java/org/sonar/server/duplication/ws/DuplicationsParser.java +++ b/server/sonar-webserver-webapi/src/main/java/org/sonar/server/duplication/ws/DuplicationsParser.java @@ -39,14 +39,15 @@ import org.sonar.api.server.ServerSide; import org.sonar.db.DbSession; import org.sonar.db.component.ComponentDao; import org.sonar.db.component.ComponentDto; +import org.sonar.server.component.ComponentFinder; @ServerSide public class DuplicationsParser { private static final BlockComparator BLOCK_COMPARATOR = new BlockComparator(); - private final ComponentDao componentDao; + private final ComponentFinder componentFinder; - public DuplicationsParser(ComponentDao componentDao) { - this.componentDao = componentDao; + public DuplicationsParser(ComponentFinder componentFinder) { + this.componentFinder = componentFinder; } public List parse(DbSession session, ComponentDto component, @Nullable String branch, @Nullable String pullRequest, @Nullable String duplicationsData) { @@ -113,13 +114,7 @@ public class DuplicationsParser { @CheckForNull private ComponentDto loadComponent(DbSession session, String componentKey, @Nullable String branch, @Nullable String pullRequest) { - if (branch != null) { - return componentDao.selectByKeyAndBranch(session, componentKey, branch).orElse(null); - } else if (pullRequest != null) { - return componentDao.selectByKeyAndPullRequest(session, componentKey, pullRequest).orElse(null); - } else { - return componentDao.selectByKey(session, componentKey).orElse(null); - } + return componentFinder.getOptionalByKeyAndOptionalBranchOrPullRequest(session, componentKey, branch, pullRequest).orElse(null); } private static String convertToKey(String dbKey) { diff --git a/server/sonar-webserver-webapi/src/main/java/org/sonar/server/duplication/ws/ShowResponseBuilder.java b/server/sonar-webserver-webapi/src/main/java/org/sonar/server/duplication/ws/ShowResponseBuilder.java index 899372371a5..037b7fc34c0 100644 --- a/server/sonar-webserver-webapi/src/main/java/org/sonar/server/duplication/ws/ShowResponseBuilder.java +++ b/server/sonar-webserver-webapi/src/main/java/org/sonar/server/duplication/ws/ShowResponseBuilder.java @@ -108,9 +108,8 @@ public class ShowResponseBuilder { private static Duplications.File toWsFile(String componentKey, @Nullable String branch, @Nullable String pullRequest) { Duplications.File.Builder wsFile = Duplications.File.newBuilder(); - String keyWithoutBranch = ComponentDto.removeBranchAndPullRequestFromKey(componentKey); - wsFile.setKey(keyWithoutBranch); - wsFile.setName(StringUtils.substringAfterLast(keyWithoutBranch, ":")); + wsFile.setKey(componentKey); + wsFile.setName(StringUtils.substringAfterLast(componentKey, ":")); ofNullable(branch).ifPresent(wsFile::setBranch); ofNullable(pullRequest).ifPresent(wsFile::setPullRequest); return wsFile.build(); diff --git a/server/sonar-webserver-webapi/src/main/java/org/sonar/server/hotspot/ws/SearchAction.java b/server/sonar-webserver-webapi/src/main/java/org/sonar/server/hotspot/ws/SearchAction.java index f30266a6636..ac108f7654d 100644 --- a/server/sonar-webserver-webapi/src/main/java/org/sonar/server/hotspot/ws/SearchAction.java +++ b/server/sonar-webserver-webapi/src/main/java/org/sonar/server/hotspot/ws/SearchAction.java @@ -56,6 +56,7 @@ import org.sonar.db.issue.IssueDto; import org.sonar.db.project.ProjectDto; import org.sonar.db.protobuf.DbIssues; import org.sonar.db.rule.RuleDto; +import org.sonar.server.component.ComponentFinder; import org.sonar.server.es.SearchOptions; import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.issue.TextRangeResponseFormatter; @@ -130,9 +131,10 @@ public class SearchAction implements HotspotsWsAction { private final HotspotWsResponseFormatter responseFormatter; private final TextRangeResponseFormatter textRangeFormatter; private final System2 system2; + private final ComponentFinder componentFinder; public SearchAction(DbClient dbClient, UserSession userSession, IssueIndex issueIndex, IssueIndexSyncProgressChecker issueIndexSyncProgressChecker, - HotspotWsResponseFormatter responseFormatter, TextRangeResponseFormatter textRangeFormatter, System2 system2) { + HotspotWsResponseFormatter responseFormatter, TextRangeResponseFormatter textRangeFormatter, System2 system2, ComponentFinder componentFinder) { this.dbClient = dbClient; this.userSession = userSession; this.issueIndex = issueIndex; @@ -140,6 +142,7 @@ public class SearchAction implements HotspotsWsAction { this.responseFormatter = responseFormatter; this.textRangeFormatter = textRangeFormatter; this.system2 = system2; + this.componentFinder = componentFinder; } private static Set setFromList(@Nullable List list) { @@ -318,23 +321,18 @@ public class SearchAction implements HotspotsWsAction { private Optional getAndValidateProjectOrApplication(DbSession dbSession, WsRequest wsRequest) { return wsRequest.getProjectKey().map(projectKey -> { - ComponentDto project = getProject(dbSession, projectKey, wsRequest.getBranch().orElse(null), wsRequest.getPullRequest().orElse(null)) - .filter(t -> Scopes.PROJECT.equals(t.scope()) && SUPPORTED_QUALIFIERS.contains(t.qualifier())) - .filter(ComponentDto::isEnabled) - .orElseThrow(() -> new NotFoundException(format("Project '%s' not found", projectKey))); + ComponentDto project = getProject(dbSession, projectKey, wsRequest.getBranch().orElse(null), wsRequest.getPullRequest().orElse(null)); + if (!Scopes.PROJECT.equals(project.scope()) || !SUPPORTED_QUALIFIERS.contains(project.qualifier()) || !project.isEnabled()) { + throw new NotFoundException(format("Project '%s' not found", projectKey)); + } userSession.checkComponentPermission(USER, project); userSession.checkChildProjectsPermission(USER, project); return project; }); } - private Optional getProject(DbSession dbSession, String projectKey, @Nullable String branch, @Nullable String pullRequest) { - if (branch != null) { - return dbClient.componentDao().selectByKeyAndBranch(dbSession, projectKey, branch); - } else if (pullRequest != null) { - return dbClient.componentDao().selectByKeyAndPullRequest(dbSession, projectKey, pullRequest); - } - return dbClient.componentDao().selectByKey(dbSession, projectKey); + private ComponentDto getProject(DbSession dbSession, String projectKey, @Nullable String branch, @Nullable String pullRequest) { + return componentFinder.getByKeyAndOptionalBranchOrPullRequest(dbSession, projectKey, branch, pullRequest); } private SearchResponseData searchHotspots(WsRequest wsRequest, DbSession dbSession, @Nullable ComponentDto project) { @@ -527,7 +525,7 @@ public class SearchAction implements HotspotsWsAction { List componentDtos = dbClient.componentDao().selectByUuids(dbSession, aggregatedComponentUuids); searchResponseData.addComponents(componentDtos); - Set branchUuids = componentDtos.stream().map(ComponentDto::branchUuid).collect(Collectors.toSet()); + Set branchUuids = componentDtos.stream().map(c -> c.getCopyComponentUuid() != null ? c.getCopyComponentUuid() : c.branchUuid()).collect(Collectors.toSet()); List branchDtos = dbClient.branchDao().selectByUuids(dbSession, branchUuids); searchResponseData.addBranches(branchDtos); } @@ -638,7 +636,8 @@ public class SearchAction implements HotspotsWsAction { Hotspots.Component.Builder builder = Hotspots.Component.newBuilder(); for (ComponentDto component : components) { - BranchDto branchDto = searchResponseData.getBranch(component.branchUuid()); + String branchUuid = component.getCopyComponentUuid() != null ? component.getCopyComponentUuid() : component.branchUuid(); + BranchDto branchDto = searchResponseData.getBranch(branchUuid); if (branchDto == null) { throw new IllegalStateException("Could not find a branch for a component " + component.getKey() + " with uuid " + component.uuid()); } diff --git a/server/sonar-webserver-webapi/src/main/java/org/sonar/server/issue/ws/SearchResponseData.java b/server/sonar-webserver-webapi/src/main/java/org/sonar/server/issue/ws/SearchResponseData.java index 335aca838a5..938b6629a38 100644 --- a/server/sonar-webserver-webapi/src/main/java/org/sonar/server/issue/ws/SearchResponseData.java +++ b/server/sonar-webserver-webapi/src/main/java/org/sonar/server/issue/ws/SearchResponseData.java @@ -54,7 +54,7 @@ public class SearchResponseData { private final ListMultimap actionsByIssueKey = ArrayListMultimap.create(); private final ListMultimap transitionsByIssueKey = ArrayListMultimap.create(); private final Set updatableComments = new HashSet<>(); - private final Map branchesByBranchUuid = new HashMap<>(); + private final Map branchesByUuid = new HashMap<>(); public SearchResponseData(IssueDto issue) { checkNotNull(issue); @@ -143,12 +143,12 @@ public class SearchResponseData { public void addBranches(List branchDtos) { for (BranchDto branch : branchDtos) { - branchesByBranchUuid.put(branch.getUuid(), branch); + branchesByUuid.put(branch.getUuid(), branch); } } public BranchDto getBranch(String branchUuid) { - return branchesByBranchUuid.get(branchUuid); + return branchesByUuid.get(branchUuid); } void addActions(String issueKey, Iterable actions) { diff --git a/server/sonar-webserver-webapi/src/main/java/org/sonar/server/issue/ws/SearchResponseFormat.java b/server/sonar-webserver-webapi/src/main/java/org/sonar/server/issue/ws/SearchResponseFormat.java index 702f183ffaf..541788dfe08 100644 --- a/server/sonar-webserver-webapi/src/main/java/org/sonar/server/issue/ws/SearchResponseFormat.java +++ b/server/sonar-webserver-webapi/src/main/java/org/sonar/server/issue/ws/SearchResponseFormat.java @@ -316,16 +316,21 @@ public class SearchResponseFormat { } private static void setBranchOrPr(ComponentDto componentDto, Component.Builder builder, SearchResponseData data) { - BranchDto branchDto = data.getBranch(componentDto.branchUuid()); + String branchUuid = componentDto.getCopyComponentUuid() != null ? componentDto.getCopyComponentUuid() : componentDto.branchUuid(); + BranchDto branchDto = data.getBranch(branchUuid); if (branchDto.isMain()) { return; } - builder.setBranch(branchDto.getBranchKey()); - builder.setPullRequest(branchDto.getPullRequestKey()); + if (branchDto.getBranchType() == BranchType.BRANCH) { + builder.setBranch(branchDto.getKey()); + } else if (branchDto.getBranchType() == BranchType.PULL_REQUEST) { + builder.setPullRequest(branchDto.getKey()); + } } private static void setBranchOrPr(ComponentDto componentDto, Issue.Builder builder, SearchResponseData data) { - BranchDto branchDto = data.getBranch(componentDto.branchUuid()); + String branchUuid = componentDto.getCopyComponentUuid() != null ? componentDto.getCopyComponentUuid() : componentDto.branchUuid(); + BranchDto branchDto = data.getBranch(branchUuid); if (branchDto.isMain()) { return; } diff --git a/server/sonar-webserver-webapi/src/main/java/org/sonar/server/issue/ws/SearchResponseLoader.java b/server/sonar-webserver-webapi/src/main/java/org/sonar/server/issue/ws/SearchResponseLoader.java index 953ec69799c..cca95b3d833 100644 --- a/server/sonar-webserver-webapi/src/main/java/org/sonar/server/issue/ws/SearchResponseLoader.java +++ b/server/sonar-webserver-webapi/src/main/java/org/sonar/server/issue/ws/SearchResponseLoader.java @@ -155,7 +155,9 @@ public class SearchResponseLoader { } private void loadBranches(DbSession dbSession, SearchResponseData result) { - Set branchUuids = result.getComponents().stream().map(ComponentDto::branchUuid).collect(Collectors.toSet()); + Set branchUuids = result.getComponents().stream() + .map(c -> c.getCopyComponentUuid() != null ? c.getCopyComponentUuid() : c.branchUuid()) + .collect(Collectors.toSet()); List branchDtos = dbClient.branchDao().selectByUuids(dbSession, branchUuids); result.addBranches(branchDtos); } @@ -178,7 +180,7 @@ public class SearchResponseLoader { result.addRules(preloadedRules); Set ruleUuidsToLoad = collector.getRuleUuids(); preloadedRules.stream().map(RuleDto::getUuid).collect(toList(preloadedRules.size())) - .forEach(ruleUuidsToLoad::remove); + .forEach(ruleUuidsToLoad::remove); List rules = dbClient.ruleDao().selectByUuids(dbSession, ruleUuidsToLoad); updateNamesOfAdHocRules(rules); @@ -191,7 +193,6 @@ public class SearchResponseLoader { .forEach(r -> r.setName(r.getAdHocName())); } - private void loadComments(Collector collector, DbSession dbSession, Set fields, SearchResponseData result) { if (fields.contains(COMMENTS)) { List comments = dbClient.issueChangeDao().selectByTypeAndIssueKeys(dbSession, collector.getIssueKeys(), IssueChangeDto.TYPE_COMMENT); diff --git a/server/sonar-webserver-webapi/src/main/java/org/sonar/server/measure/ws/ComponentAction.java b/server/sonar-webserver-webapi/src/main/java/org/sonar/server/measure/ws/ComponentAction.java index b645521e72d..bdbbeaeb817 100644 --- a/server/sonar-webserver-webapi/src/main/java/org/sonar/server/measure/ws/ComponentAction.java +++ b/server/sonar-webserver-webapi/src/main/java/org/sonar/server/measure/ws/ComponentAction.java @@ -243,12 +243,13 @@ public class ComponentAction implements MeasuresWsAction { private static ComponentWsResponse buildResponse(ComponentRequest request, ComponentDto component, Optional refComponent, Map measuresByMetric, Collection metrics, Optional period) { ComponentWsResponse.Builder response = ComponentWsResponse.newBuilder(); + boolean isMainBranch = component.getMainBranchProjectUuid() == null; if (refComponent.isPresent()) { response.setComponent(componentDtoToWsComponent(component, measuresByMetric, singletonMap(refComponent.get().uuid(), - refComponent.get()), request.getBranch(), request.getPullRequest())); + refComponent.get()), isMainBranch ? null : request.getBranch(), request.getPullRequest())); } else { - response.setComponent(componentDtoToWsComponent(component, measuresByMetric, emptyMap(), request.getBranch(), request.getPullRequest())); + response.setComponent(componentDtoToWsComponent(component, measuresByMetric, emptyMap(), isMainBranch ? null : request.getBranch(), request.getPullRequest())); } List additionalFields = request.getAdditionalFields(); diff --git a/server/sonar-webserver-webapi/src/main/java/org/sonar/server/measure/ws/ComponentTreeAction.java b/server/sonar-webserver-webapi/src/main/java/org/sonar/server/measure/ws/ComponentTreeAction.java index 03a61ca8782..6d822a5add5 100644 --- a/server/sonar-webserver-webapi/src/main/java/org/sonar/server/measure/ws/ComponentTreeAction.java +++ b/server/sonar-webserver-webapi/src/main/java/org/sonar/server/measure/ws/ComponentTreeAction.java @@ -40,6 +40,7 @@ import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.function.Function; +import java.util.stream.Collectors; import java.util.stream.Stream; import javax.annotation.CheckForNull; import javax.annotation.Nonnull; @@ -58,6 +59,7 @@ import org.sonar.core.i18n.I18n; import org.sonar.core.util.stream.MoreCollectors; import org.sonar.db.DbClient; import org.sonar.db.DbSession; +import org.sonar.db.component.BranchDto; import org.sonar.db.component.ComponentDto; import org.sonar.db.component.ComponentTreeQuery; import org.sonar.db.component.ComponentTreeQuery.Strategy; @@ -294,10 +296,18 @@ public class ComponentTreeAction implements MeasuresWsAction { data.getReferenceComponentsByUuid(), request.getBranch(), request.getPullRequest())); for (ComponentDto componentDto : data.getComponents()) { - response.addComponents(toWsComponent( - componentDto, - data.getMeasuresByComponentUuidAndMetric().row(componentDto.uuid()), - data.getReferenceComponentsByUuid(), request.getBranch(), request.getPullRequest())); + if (componentDto.getCopyComponentUuid() != null) { + String branch = data.getBranchByReferenceUuid().get(componentDto.getCopyComponentUuid()); + response.addComponents(toWsComponent( + componentDto, + data.getMeasuresByComponentUuidAndMetric().row(componentDto.uuid()), + data.getReferenceComponentsByUuid(), branch, null)); + } else { + response.addComponents(toWsComponent( + componentDto, + data.getMeasuresByComponentUuidAndMetric().row(componentDto.uuid()), + data.getReferenceComponentsByUuid(), request.getBranch(), request.getPullRequest())); + } } if (areMetricsInResponse(request)) { @@ -440,18 +450,26 @@ public class ComponentTreeAction implements MeasuresWsAction { int componentCount = components.size(); components = paginateComponents(components, wsRequest); + Map referencesByUuid = searchReferenceComponentsById(dbSession, components); + Map branchByReferenceUuid = searchReferenceBranchKeys(dbSession, referencesByUuid.keySet()); + return ComponentTreeData.builder() .setBaseComponent(baseComponent) .setComponentsFromDb(components) .setComponentCount(componentCount) + .setBranchByReferenceUuid(branchByReferenceUuid) .setMeasuresByComponentUuidAndMetric(measuresByComponentUuidAndMetric) .setMetrics(metrics) .setPeriod(snapshotToWsPeriods(baseSnapshot.get()).orElse(null)) - .setReferenceComponentsByUuid(searchReferenceComponentsById(dbSession, components)) + .setReferenceComponentsByUuid(referencesByUuid) .build(); } } + private Map searchReferenceBranchKeys(DbSession dbSession, Set referenceUuids) { + return dbClient.branchDao().selectByUuids(dbSession, referenceUuids).stream().collect(Collectors.toMap(BranchDto::getUuid, BranchDto::getBranchKey)); + } + private static boolean isPR(@Nullable String pullRequest) { return pullRequest != null; } @@ -460,9 +478,6 @@ public class ComponentTreeAction implements MeasuresWsAction { String componentKey = request.getComponent(); String branch = request.getBranch(); String pullRequest = request.getPullRequest(); - if (branch == null && pullRequest == null) { - return componentFinder.getByKey(dbSession, componentKey); - } return componentFinder.getByKeyAndOptionalBranchOrPullRequest(dbSession, componentKey, branch, pullRequest); } diff --git a/server/sonar-webserver-webapi/src/main/java/org/sonar/server/measure/ws/ComponentTreeData.java b/server/sonar-webserver-webapi/src/main/java/org/sonar/server/measure/ws/ComponentTreeData.java index 45fa18570d4..151c322bddf 100644 --- a/server/sonar-webserver-webapi/src/main/java/org/sonar/server/measure/ws/ComponentTreeData.java +++ b/server/sonar-webserver-webapi/src/main/java/org/sonar/server/measure/ws/ComponentTreeData.java @@ -38,6 +38,7 @@ class ComponentTreeData { private final List components; private final int componentCount; private final Map referenceComponentsByUuid; + private final Map branchByReferenceUuid; private final List metrics; private final Measures.Period period; private final Table measuresByComponentUuidAndMetric; @@ -47,11 +48,16 @@ class ComponentTreeData { this.components = builder.componentsFromDb; this.componentCount = builder.componentCount; this.referenceComponentsByUuid = builder.referenceComponentsByUuid; + this.branchByReferenceUuid = builder.branchByReferenceUuid; this.metrics = builder.metrics; this.measuresByComponentUuidAndMetric = builder.measuresByComponentUuidAndMetric; this.period = builder.period; } + public Map getBranchByReferenceUuid() { + return branchByReferenceUuid; + } + public ComponentDto getBaseComponent() { return baseComponent; } @@ -93,6 +99,7 @@ class ComponentTreeData { private ComponentDto baseComponent; private List componentsFromDb; private Map referenceComponentsByUuid; + private Map branchByReferenceUuid; private int componentCount; private List metrics; private Measures.Period period; @@ -102,6 +109,11 @@ class ComponentTreeData { // private constructor } + public Builder setBranchByReferenceUuid(Map branchByReferenceUuid) { + this.branchByReferenceUuid = branchByReferenceUuid; + return this; + } + public Builder setBaseComponent(ComponentDto baseComponent) { this.baseComponent = baseComponent; return this; diff --git a/server/sonar-webserver-webapi/src/main/java/org/sonar/server/setting/ws/ValuesAction.java b/server/sonar-webserver-webapi/src/main/java/org/sonar/server/setting/ws/ValuesAction.java index 12deba7ab25..6048974fec2 100644 --- a/server/sonar-webserver-webapi/src/main/java/org/sonar/server/setting/ws/ValuesAction.java +++ b/server/sonar-webserver-webapi/src/main/java/org/sonar/server/setting/ws/ValuesAction.java @@ -49,7 +49,6 @@ import org.sonar.db.component.ComponentDto; import org.sonar.db.permission.GlobalPermission; import org.sonar.db.property.PropertyDto; import org.sonar.server.component.ComponentFinder; -import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.user.UserSession; import org.sonarqube.ws.Settings; import org.sonarqube.ws.Settings.ValuesWsResponse; @@ -124,7 +123,8 @@ public class ValuesAction implements SettingsWsAction { try (DbSession dbSession = dbClient.openSession(true)) { ValuesRequest valuesRequest = ValuesRequest.from(request); Optional component = loadComponent(dbSession, valuesRequest); - BranchDto branchDto = loadBranch(dbSession, component); + // TODO can portfolios fail here? + BranchDto branchDto = component.map(c -> componentFinder.getBranchByUuid(dbSession, c.branchUuid())).orElse(null); Set keys = loadKeys(valuesRequest); Map keysToDisplayMap = getKeysToDisplayMap(keys); @@ -133,14 +133,6 @@ public class ValuesAction implements SettingsWsAction { } } - private BranchDto loadBranch(DbSession dbSession, Optional component) { - if (component.isEmpty()) { - return null; - } - return dbClient.branchDao().selectByUuid(dbSession, component.get().branchUuid()) - .orElseThrow(() -> new NotFoundException("Could not find a branch for component uuid " + component.get().branchUuid())); - } - private Set loadKeys(ValuesRequest valuesRequest) { List keys = valuesRequest.getKeys(); Set result; @@ -159,6 +151,7 @@ public class ValuesAction implements SettingsWsAction { return Optional.empty(); } ComponentDto component = componentFinder.getByKey(dbSession, componentKey); + if (!userSession.hasComponentPermission(USER, component) && !userSession.hasComponentPermission(UserRole.SCAN, component) && !userSession.hasPermission(GlobalPermission.SCAN)) { @@ -174,7 +167,7 @@ public class ValuesAction implements SettingsWsAction { settings.addAll(loadGlobalSettings(dbSession, keys)); String branch = getBranchKeySafely(branchDto); if (component.isPresent() && branch != null && component.get().getMainBranchProjectUuid() != null) { - ComponentDto project = dbClient.componentDao().selectOrFailByUuid(dbSession, component.get().getMainBranchProjectUuid()); + ComponentDto project = componentFinder.getByUuidFromMainBranch(dbSession, component.get().getMainBranchProjectUuid()); settings.addAll(loadComponentSettings(dbSession, keys, project).values()); } component.ifPresent(componentDto -> settings.addAll(loadComponentSettings(dbSession, keys, componentDto).values())); @@ -183,8 +176,9 @@ public class ValuesAction implements SettingsWsAction { .collect(Collectors.toList()); } + @CheckForNull private String getBranchKeySafely(@Nullable BranchDto branchDto) { - if(branchDto != null) { + if (branchDto != null) { return branchDto.isMain() ? null : branchDto.getBranchKey(); } return null; diff --git a/server/sonar-webserver-webapi/src/main/java/org/sonar/server/ui/ws/ComponentAction.java b/server/sonar-webserver-webapi/src/main/java/org/sonar/server/ui/ws/ComponentAction.java index ce3b0d9ad6e..bb9746add89 100644 --- a/server/sonar-webserver-webapi/src/main/java/org/sonar/server/ui/ws/ComponentAction.java +++ b/server/sonar-webserver-webapi/src/main/java/org/sonar/server/ui/ws/ComponentAction.java @@ -27,6 +27,7 @@ import java.util.Optional; import java.util.Set; import java.util.function.Predicate; import java.util.stream.Collectors; +import javax.annotation.CheckForNull; import javax.annotation.Nullable; import org.sonar.api.config.Configuration; import org.sonar.api.resources.Qualifiers; @@ -43,7 +44,6 @@ import org.sonar.api.web.UserRole; import org.sonar.api.web.page.Page; import org.sonar.db.DbClient; import org.sonar.db.DbSession; -import org.sonar.db.component.BranchDto; import org.sonar.db.component.ComponentDto; import org.sonar.db.component.SnapshotDto; import org.sonar.db.measure.LiveMeasureDto; @@ -53,7 +53,6 @@ import org.sonar.db.property.PropertyQuery; import org.sonar.db.qualityprofile.QProfileDto; import org.sonar.server.component.ComponentFinder; import org.sonar.server.exceptions.BadRequestException; -import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.project.Visibility; import org.sonar.server.qualitygate.QualityGateFinder; import org.sonar.server.qualityprofile.QPMeasureData; @@ -153,20 +152,18 @@ public class ComponentAction implements NavigationWsAction { checkComponentNotAModuleAndNotADirectory(component); ComponentDto rootProjectOrBranch = getRootProjectOrBranch(component, session); ComponentDto rootProject = rootProjectOrBranch.getMainBranchProjectUuid() == null ? rootProjectOrBranch - : componentFinder.getByUuid(session, rootProjectOrBranch.getMainBranchProjectUuid()); + : componentFinder.getByUuidFromMainBranch(session, rootProjectOrBranch.getMainBranchProjectUuid()); if (!userSession.hasComponentPermission(USER, component) && !userSession.hasComponentPermission(ADMIN, component) && !userSession.isSystemAdministrator()) { throw insufficientPrivilegesException(); } Optional analysis = dbClient.snapshotDao().selectLastAnalysisByRootComponentUuid(session, component.branchUuid()); - BranchDto branchDto = dbClient.branchDao().selectByUuid(session, component.branchUuid()) - .orElseThrow(() -> new NotFoundException(format("Could not find a branch for component uuid " + component.uuid()))); try (JsonWriter json = response.newJsonWriter()) { json.beginObject(); boolean isFavourite = isFavourite(session, rootProject, component); - String branchKey = branchDto.isMain() ? null : branchDto.getBranchKey(); + String branchKey = getBranchKey(session, component); writeComponent(json, component, analysis.orElse(null), isFavourite, branchKey); writeProfiles(json, session, component); writeQualityGate(json, session, rootProject); @@ -181,6 +178,14 @@ public class ComponentAction implements NavigationWsAction { } } + @CheckForNull + private String getBranchKey(DbSession session, ComponentDto component) { + // TODO portfolios may have no branch, so we shouldn't faul? + return dbClient.branchDao().selectByUuid(session, component.branchUuid()) + .map(b -> b.isMain() ? null : b.getBranchKey()) + .orElse(null); + } + private static void checkComponentNotAModuleAndNotADirectory(ComponentDto component) { BadRequestException.checkRequest(!MODULE_OR_DIR_QUALIFIERS.contains(component.qualifier()), "Operation not supported for module or directory components"); } @@ -209,7 +214,7 @@ public class ComponentAction implements NavigationWsAction { .endObject(); } - private void writeComponent(JsonWriter json, ComponentDto component, @Nullable SnapshotDto analysis, boolean isFavourite, String branchKey) { + private void writeComponent(JsonWriter json, ComponentDto component, @Nullable SnapshotDto analysis, boolean isFavourite, @Nullable String branchKey) { json.prop("key", component.getKey()) .prop("id", component.uuid()) .prop("name", component.name()) diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/component/ComponentFinderTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/component/ComponentFinderTest.java index c4905efc0b5..0a5376d0d4a 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/component/ComponentFinderTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/component/ComponentFinderTest.java @@ -103,7 +103,7 @@ public class ComponentFinderTest { ComponentDto project = db.components().insertComponent(newPrivateProjectDto()); db.components().insertComponent(newFileDto(project, null, "file-uuid").setEnabled(false)); - assertThatThrownBy(() -> underTest.getByUuid(dbSession, "file-uuid")) + assertThatThrownBy(() -> underTest.getByUuidFromMainBranch(dbSession, "file-uuid")) .isInstanceOf(NotFoundException.class) .hasMessage("Component id 'file-uuid' not found"); } @@ -114,7 +114,7 @@ public class ComponentFinderTest { ComponentDto branch = db.components().insertProjectBranch(project); String branchUuid = branch.uuid(); - assertThatThrownBy(() -> underTest.getByUuid(dbSession, branchUuid)) + assertThatThrownBy(() -> underTest.getByUuidFromMainBranch(dbSession, branchUuid)) .isInstanceOf(NotFoundException.class) .hasMessage(format("Component id '%s' not found", branchUuid)); } @@ -175,6 +175,33 @@ public class ComponentFinderTest { assertThat(underTest.getByKeyAndOptionalBranchOrPullRequest(dbSession, directory.getKey(), null, "pr-123").uuid()).isEqualTo(directory.uuid()); } + @Test + public void get_optional_by_key_and_optional_branch_or_pull_request() { + ComponentDto project = db.components().insertPublicProject(); + ComponentDto pr = db.components().insertProjectBranch(project, b -> b.setKey("pr").setBranchType(PULL_REQUEST)); + ComponentDto branch = db.components().insertProjectBranch(project, b -> b.setKey("branch")); + ComponentDto branchFile = db.components().insertComponent(newFileDto(branch)); + + + assertThat(underTest.getOptionalByKeyAndOptionalBranchOrPullRequest(dbSession, project.getKey(), null, null)).isPresent(); + assertThat(underTest.getOptionalByKeyAndOptionalBranchOrPullRequest(dbSession, project.getKey(), null, null).get().uuid()) + .isEqualTo(project.uuid()); + + assertThat(underTest.getOptionalByKeyAndOptionalBranchOrPullRequest(dbSession, branch.getKey(), "branch", null)).isPresent(); + assertThat(underTest.getOptionalByKeyAndOptionalBranchOrPullRequest(dbSession, branch.getKey(), "branch", null).get().uuid()) + .isEqualTo(branch.uuid()); + assertThat(underTest.getOptionalByKeyAndOptionalBranchOrPullRequest(dbSession, branchFile.getKey(), "branch", null)).isPresent(); + assertThat(underTest.getOptionalByKeyAndOptionalBranchOrPullRequest(dbSession, branchFile.getKey(), "branch", null).get().uuid()) + .isEqualTo(branchFile.uuid()); + + assertThat(underTest.getOptionalByKeyAndOptionalBranchOrPullRequest(dbSession, pr.getKey(), null, "pr")).isPresent(); + assertThat(underTest.getOptionalByKeyAndOptionalBranchOrPullRequest(dbSession, pr.getKey(), null, "pr").get().uuid()) + .isEqualTo(pr.uuid()); + + assertThat(underTest.getOptionalByKeyAndOptionalBranchOrPullRequest(dbSession, "unknown", null, null)).isEmpty(); + + } + @Test public void fail_when_pull_request_branch_provided() { ComponentDto project = db.components().insertPublicProject(); diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/component/ComponentUpdaterTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/component/ComponentUpdaterTest.java index fee559a446e..b761e96a01f 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/component/ComponentUpdaterTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/component/ComponentUpdaterTest.java @@ -92,7 +92,7 @@ public class ComponentUpdaterTest { assertThat(loaded.moduleUuidPath()).isEqualTo("." + loaded.uuid() + "."); assertThat(loaded.isPrivate()).isEqualTo(project.isPrivate()); assertThat(loaded.getCreatedAt()).isNotNull(); - assertThat(db.getDbClient().componentDao().selectOrFailByKey(db.getSession(), DEFAULT_PROJECT_KEY)).isNotNull(); + assertThat(db.getDbClient().componentDao().selectByKey(db.getSession(), DEFAULT_PROJECT_KEY)).isPresent(); assertThat(projectIndexers.hasBeenCalled(loaded.uuid(), ProjectIndexer.Cause.PROJECT_CREATION)).isTrue(); diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/component/ws/TreeActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/component/ws/TreeActionTest.java index 2bdb91b0310..88859bd69bb 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/component/ws/TreeActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/component/ws/TreeActionTest.java @@ -280,7 +280,7 @@ public class TreeActionTest { ComponentDto project = db.components().insertPrivateProject(p -> p.setKey("project-key")); ComponentDto projectBranch = db.components().insertProjectBranch(project, b -> b.setKey(projectBranchName)); ComponentDto techProjectBranch = db.components().insertComponent(newProjectCopy(projectBranch, applicationBranch) - .setKey(applicationBranch.getKey() + appBranchName + projectBranch.getKey())); + .setKey(applicationBranch.getKey() + project.getKey())); logInWithBrowsePermission(application); TreeWsResponse result = ws.newRequest() @@ -377,19 +377,6 @@ public class TreeActionTest { tuple(file.getKey(), pullRequestId)); } - @Test - public void fail_when_using_branch_key() { - ComponentDto project = db.components().insertPrivateProject(); - userSession.addProjectPermission(UserRole.USER, project); - ComponentDto branch = db.components().insertProjectBranch(project); - - TestRequest request = ws.newRequest() - .setParam(PARAM_COMPONENT, branch.getKey()); - assertThatThrownBy(() -> request.executeProtobuf(Components.ShowWsResponse.class)) - .isInstanceOf(NotFoundException.class) - .hasMessage(format("Component key '%s' not found", branch.getKey())); - } - @Test public void fail_when_not_enough_privileges() { ComponentDto project = db.components().insertComponent(newPrivateProjectDto("project-uuid")); diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/duplication/ws/DuplicationsParserTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/duplication/ws/DuplicationsParserTest.java index ebaa21cf718..f71292b5740 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/duplication/ws/DuplicationsParserTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/duplication/ws/DuplicationsParserTest.java @@ -28,6 +28,7 @@ import org.junit.Test; import org.sonar.db.DbTester; import org.sonar.db.component.BranchType; import org.sonar.db.component.ComponentDto; +import org.sonar.server.component.ComponentFinder; import static java.lang.String.format; import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; @@ -39,7 +40,7 @@ public class DuplicationsParserTest { @Rule public DbTester db = DbTester.create(); - private DuplicationsParser parser = new DuplicationsParser(db.getDbClient().componentDao()); + private final DuplicationsParser parser = new DuplicationsParser(new ComponentFinder(db.getDbClient(), null)); @Test public void empty_list_when_no_data() { diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/duplication/ws/ShowActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/duplication/ws/ShowActionTest.java index 2c0af116c21..a92670456cd 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/duplication/ws/ShowActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/duplication/ws/ShowActionTest.java @@ -57,7 +57,8 @@ public class ShowActionTest { @Rule public DbTester db = DbTester.create(); - private final DuplicationsParser parser = new DuplicationsParser(db.getDbClient().componentDao()); + private final TestComponentFinder componentFinder = TestComponentFinder.from(db); + private final DuplicationsParser parser = new DuplicationsParser(componentFinder); private final ShowResponseBuilder showResponseBuilder = new ShowResponseBuilder(db.getDbClient()); private final WsActionTester ws = new WsActionTester(new ShowAction(db.getDbClient(), parser, showResponseBuilder, userSessionRule, TestComponentFinder.from(db))); diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/favorite/ws/RemoveActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/favorite/ws/RemoveActionTest.java index 54d1083cc3a..d8a5b32a352 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/favorite/ws/RemoveActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/favorite/ws/RemoveActionTest.java @@ -105,18 +105,6 @@ public class RemoveActionTest { .isInstanceOf(UnauthorizedException.class); } - @Test - public void fail_when_using_branch_db_key() { - ComponentDto project = db.components().insertPrivateProject(); - userSession.logIn().addProjectPermission(UserRole.USER, project); - ComponentDto branch = db.components().insertProjectBranch(project); - String branchKey = branch.getKey(); - - assertThatThrownBy(() -> call(branchKey)) - .isInstanceOf(NotFoundException.class) - .hasMessage(format("Component key '%s' not found", branchKey)); - } - @Test public void definition() { WebService.Action definition = ws.getDef(); diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/hotspot/ws/SearchActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/hotspot/ws/SearchActionTest.java index 06be33aaaa5..4942128a7ad 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/hotspot/ws/SearchActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/hotspot/ws/SearchActionTest.java @@ -57,6 +57,8 @@ import org.sonar.db.protobuf.DbCommons; import org.sonar.db.protobuf.DbIssues; import org.sonar.db.rule.RuleDto; import org.sonar.db.rule.RuleTesting; +import org.sonar.server.component.ComponentFinder; +import org.sonar.server.component.TestComponentFinder; import org.sonar.server.es.EsTester; import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.exceptions.NotFoundException; @@ -153,8 +155,9 @@ public class SearchActionTest { private final PermissionIndexer permissionIndexer = new PermissionIndexer(dbClient, es.client(), issueIndexer); private final HotspotWsResponseFormatter responseFormatter = new HotspotWsResponseFormatter(); private final IssueIndexSyncProgressChecker issueIndexSyncProgressChecker = mock(IssueIndexSyncProgressChecker.class); + private final ComponentFinder componentFinder = TestComponentFinder.from(dbTester); private final SearchAction underTest = new SearchAction(dbClient, userSessionRule, issueIndex, - issueIndexSyncProgressChecker, responseFormatter, new TextRangeResponseFormatter(), system2); + issueIndexSyncProgressChecker, responseFormatter, new TextRangeResponseFormatter(), system2, componentFinder); private final WsActionTester actionTester = new WsActionTester(underTest); @Test @@ -333,7 +336,7 @@ public class SearchActionTest { assertThatThrownBy(request::execute) .isInstanceOf(NotFoundException.class) - .hasMessage("Project '%s' not found", key); + .hasMessage("Component key '%s' not found", key); } @Test @@ -638,7 +641,7 @@ public class SearchActionTest { @Test public void returns_hotspots_of_specified_application_branch() { ComponentDto application = dbTester.components().insertPublicApplication(); - ComponentDto applicationBranch = dbTester.components().insertProjectBranch(application); + ComponentDto applicationBranch = dbTester.components().insertProjectBranch(application, b -> b.setKey("appBranch")); ComponentDto project1 = dbTester.components().insertPublicProject(); ComponentDto project2 = dbTester.components().insertPublicProject(); dbTester.components().insertComponent(ComponentTesting.newProjectCopy(project1, application)); @@ -667,7 +670,7 @@ public class SearchActionTest { .extracting(Component::getKey) .containsOnly(project1.getKey(), file1.getKey()); - SearchWsResponse responseApplicationBranch = newRequest(applicationBranch) + SearchWsResponse responseApplicationBranch = newRequest(application, null, null, "appBranch", null) .executeProtobuf(SearchWsResponse.class); assertThat(responseApplicationBranch.getHotspotsList()) @@ -818,7 +821,7 @@ public class SearchActionTest { .collect(toList()); indexIssues(); - SearchWsResponse response = newRequest(project, null, null) + SearchWsResponse response = newRequest(project) .executeProtobuf(SearchWsResponse.class); assertThat(response.getHotspotsList()) @@ -837,7 +840,7 @@ public class SearchActionTest { .collect(toList()); indexIssues(); - SearchWsResponse response = newRequest(project, STATUS_REVIEWED, null) + SearchWsResponse response = newRequest(project, STATUS_REVIEWED, null, null, null) .executeProtobuf(SearchWsResponse.class); assertThat(response.getHotspotsList()) @@ -856,7 +859,7 @@ public class SearchActionTest { .collect(toList()); indexIssues(); - SearchWsResponse response = newRequest(project, STATUS_REVIEWED, RESOLUTION_SAFE) + SearchWsResponse response = newRequest(project, STATUS_REVIEWED, RESOLUTION_SAFE, null, null) .executeProtobuf(SearchWsResponse.class); assertThat(response.getHotspotsList()) @@ -875,7 +878,7 @@ public class SearchActionTest { .collect(toList()); indexIssues(); - SearchWsResponse response = newRequest(project, STATUS_REVIEWED, RESOLUTION_FIXED) + SearchWsResponse response = newRequest(project, STATUS_REVIEWED, RESOLUTION_FIXED, null, null) .executeProtobuf(SearchWsResponse.class); assertThat(response.getHotspotsList()) @@ -897,7 +900,7 @@ public class SearchActionTest { IssueDto badlyClosedHotspot = insertHotspot(rule, project, file, t -> t.setStatus(STATUS_CLOSED).setResolution(null)); indexIssues(); - SearchWsResponse response = newRequest(project, STATUS_TO_REVIEW, null) + SearchWsResponse response = newRequest(project, STATUS_TO_REVIEW, null, null, null) .executeProtobuf(SearchWsResponse.class); assertThat(response.getHotspotsList()) @@ -1136,7 +1139,7 @@ public class SearchActionTest { IssueDto projectHotspot = insertHotspot(pullRequest, pullRequest, rule); indexIssues(); - SearchWsResponse response = newRequest(pullRequest, r -> r.setParam(PARAM_PULL_REQUEST, "pullRequestKey")) + SearchWsResponse response = newRequest(pullRequest, r -> r.setParam(PARAM_PULL_REQUEST, pullRequestKey)) .executeProtobuf(SearchWsResponse.class); assertThat(response.getHotspotsList()) @@ -2020,21 +2023,29 @@ public class SearchActionTest { } private TestRequest newRequest(ComponentDto project) { - return newRequest(project, null, null); + return newRequest(project, null, null, null, null); } private TestRequest newRequest(ComponentDto project, Consumer consumer) { - return newRequest(project, null, null, consumer); + return newRequest(project, null, + null, null, null, consumer); } - private TestRequest newRequest(ComponentDto project, @Nullable String status, @Nullable String resolution) { - return newRequest(project, status, resolution, t -> { + private TestRequest newRequest(ComponentDto project, @Nullable String status, @Nullable String resolution, @Nullable String branch, @Nullable String pullRequest) { + return newRequest(project, status, resolution, branch, pullRequest, t -> { }); } - private TestRequest newRequest(ComponentDto project, @Nullable String status, @Nullable String resolution, Consumer consumer) { + private TestRequest newRequest(ComponentDto project, @Nullable String status, @Nullable String resolution, + @Nullable String branch, @Nullable String pullRequest, Consumer consumer) { TestRequest res = actionTester.newRequest() .setParam(PARAM_PROJECT_KEY, project.getKey()); + if (branch != null) { + res.setParam(PARAM_BRANCH, branch); + } + if (pullRequest != null) { + res.setParam(PARAM_PULL_REQUEST, pullRequest); + } if (status != null) { res.setParam(PARAM_STATUS, status); } diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/ws/SearchActionComponentsTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/ws/SearchActionComponentsTest.java index 8b937abf8bf..b77b308559e 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/ws/SearchActionComponentsTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/ws/SearchActionComponentsTest.java @@ -366,12 +366,14 @@ public class SearchActionComponentsTest { ComponentDto application = db.components().insertPrivateProject(c -> c.setQualifier(APP).setKey("app")); String appBranch1 = "app-branch1"; String appBranch2 = "app-branch2"; + String proj1branch1 = "proj1branch1"; + String proj1branch2 = "proj1branch2"; ComponentDto applicationBranch1 = db.components().insertProjectBranch(application, a -> a.setKey(appBranch1)); ComponentDto applicationBranch2 = db.components().insertProjectBranch(application, a -> a.setKey(appBranch2)); ComponentDto project1 = db.components().insertPrivateProject(p -> p.setKey("prj1")); - ComponentDto project1Branch1 = db.components().insertProjectBranch(project1); + ComponentDto project1Branch1 = db.components().insertProjectBranch(project1, b -> b.setKey(proj1branch1)); ComponentDto fileOnProject1Branch1 = db.components().insertComponent(newFileDto(project1Branch1)); - ComponentDto project1Branch2 = db.components().insertProjectBranch(project1); + ComponentDto project1Branch2 = db.components().insertProjectBranch(project1, b -> b.setKey(proj1branch2)); ComponentDto project2 = db.components().insertPrivateProject(p -> p.setKey("prj2")); db.components().insertComponents(newProjectCopy(project1Branch1, applicationBranch1)); db.components().insertComponents(newProjectCopy(project2, applicationBranch1)); @@ -397,8 +399,8 @@ public class SearchActionComponentsTest { .executeProtobuf(SearchWsResponse.class).getIssuesList()) .extracting(Issue::getKey, Issue::getComponent, Issue::getProject, Issue::getBranch, Issue::hasBranch) .containsExactlyInAnyOrder( - tuple(issueOnProject1Branch1.getKey(), project1Branch1.getKey(), project1Branch1.getKey(), appBranch1, true), - tuple(issueOnFileOnProject1Branch1.getKey(), fileOnProject1Branch1.getKey(), project1Branch1.getKey(), appBranch1, true), + tuple(issueOnProject1Branch1.getKey(), project1Branch1.getKey(), project1Branch1.getKey(), proj1branch1, true), + tuple(issueOnFileOnProject1Branch1.getKey(), fileOnProject1Branch1.getKey(), project1Branch1.getKey(), proj1branch1, true), tuple(issueOnProject2.getKey(), project2.getKey(), project2.getKey(), "", false)); // Issues on project1Branch1 @@ -409,8 +411,8 @@ public class SearchActionComponentsTest { .executeProtobuf(SearchWsResponse.class).getIssuesList()) .extracting(Issue::getKey, Issue::getComponent, Issue::getBranch) .containsExactlyInAnyOrder( - tuple(issueOnProject1Branch1.getKey(), project1Branch1.getKey(), appBranch1), - tuple(issueOnFileOnProject1Branch1.getKey(), fileOnProject1Branch1.getKey(), appBranch1)); + tuple(issueOnProject1Branch1.getKey(), project1Branch1.getKey(), proj1branch1), + tuple(issueOnFileOnProject1Branch1.getKey(), fileOnProject1Branch1.getKey(), proj1branch1)); } @Test diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/ws/SearchActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/ws/SearchActionTest.java index 54fb534fbf8..49cfd31ec09 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/ws/SearchActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/ws/SearchActionTest.java @@ -451,7 +451,7 @@ public class SearchActionTest { UserDto simon = db.users().insertUser(u -> u.setLogin("simon").setName("Simon").setEmail("simon@email.com")); UserDto fabrice = db.users().insertUser(u -> u.setLogin("fabrice").setName("Fabrice").setEmail("fabrice@email.com")); - ComponentDto project = db.components().insertComponent(ComponentTesting.newPublicProjectDto("PROJECT_ID").setKey("PROJECT_KEY").setLanguage("java")); + ComponentDto project = db.components().insertPublicProject("PROJECT_ID", c -> c.setKey("PROJECT_KEY").setLanguage("java")); grantPermissionToAnyone(project, ISSUE_ADMIN); indexPermissions(); ComponentDto file = db.components().insertComponent(newFileDto(project, null, "FILE_ID").setKey("FILE_KEY").setLanguage("js")); @@ -475,7 +475,7 @@ public class SearchActionTest { @Test public void search_by_rule_key() { RuleDto rule = newIssueRule(); - ComponentDto project = db.components().insertComponent(ComponentTesting.newPublicProjectDto("PROJECT_ID").setKey("PROJECT_KEY").setLanguage("java")); + ComponentDto project = db.components().insertPublicProject("PROJECT_ID", c -> c.setKey("PROJECT_KEY").setLanguage("java")); ComponentDto file = db.components().insertComponent(newFileDto(project, null, "FILE_ID").setKey("FILE_KEY").setLanguage("java")); db.issues().insertIssue(rule, project, file); @@ -496,7 +496,7 @@ public class SearchActionTest { @Test public void search_by_non_existing_rule_key() { RuleDto rule = newIssueRule(); - ComponentDto project = db.components().insertComponent(ComponentTesting.newPublicProjectDto("PROJECT_ID").setKey("PROJECT_KEY").setLanguage("java")); + ComponentDto project = db.components().insertPublicProject("PROJECT_ID", c -> c.setKey("PROJECT_KEY").setLanguage("java")); ComponentDto file = db.components().insertComponent(newFileDto(project, null, "FILE_ID").setKey("FILE_KEY").setLanguage("java")); db.issues().insertIssue(rule, project, file); @@ -517,7 +517,7 @@ public class SearchActionTest { @Test public void issue_on_removed_file() { RuleDto rule = newIssueRule(); - ComponentDto project = db.components().insertComponent(ComponentTesting.newPublicProjectDto("PROJECT_ID").setKey("PROJECT_KEY")); + ComponentDto project = db.components().insertPublicProject("PROJECT_ID", c -> c.setKey("PROJECT_KEY").setKey("PROJECT_KEY")); indexPermissions(); ComponentDto removedFile = db.components().insertComponent(newFileDto(project, null).setUuid("REMOVED_FILE_ID") .setKey("REMOVED_FILE_KEY") @@ -542,7 +542,7 @@ public class SearchActionTest { @Test public void apply_paging_with_one_component() { RuleDto rule = newIssueRule(); - ComponentDto project = db.components().insertComponent(ComponentTesting.newPublicProjectDto("PROJECT_ID").setKey("PROJECT_KEY")); + ComponentDto project = db.components().insertPublicProject("PROJECT_ID", c -> c.setKey("PROJECT_KEY").setKey("PROJECT_KEY")); indexPermissions(); ComponentDto file = db.components().insertComponent(newFileDto(project, null, "FILE_ID").setKey("FILE_KEY")); for (int i = 0; i < SearchOptions.MAX_PAGE_SIZE + 1; i++) { @@ -558,7 +558,7 @@ public class SearchActionTest { @Test public void components_contains_sub_projects() { - ComponentDto project = db.components().insertComponent(ComponentTesting.newPublicProjectDto("PROJECT_ID").setKey("ProjectHavingModule")); + ComponentDto project = db.components().insertPublicProject("PROJECT_ID", c -> c.setKey("PROJECT_KEY").setKey("ProjectHavingModule")); indexPermissions(); ComponentDto module = db.components().insertComponent(ComponentTesting.newModuleDto(project).setKey("ModuleHavingFile")); ComponentDto file = db.components().insertComponent(newFileDto(module, null, "BCDE").setKey("FileLinkedToModule")); @@ -575,7 +575,7 @@ public class SearchActionTest { public void filter_by_assigned_to_me() { UserDto john = db.users().insertUser(u -> u.setLogin("john").setName("John").setEmail("john@email.com")); UserDto alice = db.users().insertUser(u -> u.setLogin("alice").setName("Alice").setEmail("alice@email.com")); - ComponentDto project = db.components().insertComponent(ComponentTesting.newPublicProjectDto("PROJECT_ID").setKey("PROJECT_KEY")); + ComponentDto project = db.components().insertPublicProject(c -> c.setUuid("PROJECT_ID").setKey("PROJECT_KEY").setBranchUuid("PROJECT_ID")); indexPermissions(); ComponentDto file = db.components().insertComponent(newFileDto(project, null, "FILE_ID").setKey("FILE_KEY")); RuleDto rule = newIssueRule(); @@ -621,7 +621,7 @@ public class SearchActionTest { public void filter_by_new_code_period() { UserDto john = db.users().insertUser(u -> u.setLogin("john").setName("John").setEmail("john@email.com")); UserDto alice = db.users().insertUser(u -> u.setLogin("alice").setName("Alice").setEmail("alice@email.com")); - ComponentDto project = db.components().insertComponent(ComponentTesting.newPublicProjectDto("PROJECT_ID").setKey("PROJECT_KEY")); + ComponentDto project = db.components().insertPublicProject("PROJECT_ID", c -> c.setKey("PROJECT_KEY")); SnapshotDto snapshotDto = db.components().insertSnapshot(project, s -> s.setLast(true).setPeriodDate(parseDateTime("2014-09-05T00:00:00+0100").getTime())); indexPermissions(); @@ -692,7 +692,7 @@ public class SearchActionTest { public void filter_by_leak_period_without_a_period() { UserDto john = db.users().insertUser(u -> u.setLogin("john").setName("John").setEmail("john@email.com")); UserDto alice = db.users().insertUser(u -> u.setLogin("alice").setName("Alice").setEmail("alice@email.com")); - ComponentDto project = db.components().insertComponent(ComponentTesting.newPublicProjectDto("PROJECT_ID").setKey("PROJECT_KEY")); + ComponentDto project = db.components().insertPublicProject("PROJECT_ID", c -> c.setKey("PROJECT_KEY")); SnapshotDto snapshotDto = db.components().insertSnapshot(project); indexPermissions(); ComponentDto file = db.components().insertComponent(newFileDto(project, null, "FILE_ID").setKey("FILE_KEY")); @@ -743,7 +743,7 @@ public class SearchActionTest { public void filter_by_leak_period_has_no_effect_on_prs() { UserDto john = db.users().insertUser(u -> u.setLogin("john").setName("John").setEmail("john@email.com")); UserDto alice = db.users().insertUser(u -> u.setLogin("alice").setName("Alice").setEmail("alice@email.com")); - ComponentDto project = db.components().insertPublicProject(c -> c.setUuid("PROJECT_ID").setKey("PROJECT_KEY")); + ComponentDto project = db.components().insertPublicProject("PROJECT_ID", c -> c.setKey("PROJECT_KEY")); ComponentDto pr = db.components().insertProjectBranch(project, b -> b.setBranchType(BranchType.PULL_REQUEST).setKey("pr")); SnapshotDto snapshotDto = db.components().insertSnapshot(pr); indexPermissions(); @@ -798,7 +798,7 @@ public class SearchActionTest { public void return_empty_when_login_is_unknown() { UserDto john = db.users().insertUser(u -> u.setLogin("john").setName("John").setEmail("john@email.com")); UserDto alice = db.users().insertUser(u -> u.setLogin("alice").setName("Alice").setEmail("alice@email.com")); - ComponentDto project = db.components().insertComponent(ComponentTesting.newPublicProjectDto("PROJECT_ID").setKey("PROJECT_KEY")); + ComponentDto project = db.components().insertPublicProject("PROJECT_ID", c -> c.setKey("PROJECT_KEY")); indexPermissions(); ComponentDto file = db.components().insertComponent(newFileDto(project, null, "FILE_ID").setKey("FILE_KEY")); RuleDto rule = newIssueRule(); @@ -847,7 +847,7 @@ public class SearchActionTest { userSession.logIn(poy); UserDto alice = db.users().insertUser(u -> u.setLogin("alice").setName("Alice").setEmail("alice@email.com")); UserDto john = db.users().insertUser(u -> u.setLogin("john").setName("John").setEmail("john@email.com")); - ComponentDto project = db.components().insertComponent(ComponentTesting.newPublicProjectDto("PROJECT_ID").setKey("PROJECT_KEY")); + ComponentDto project = db.components().insertPublicProject("PROJECT_ID", c -> c.setKey("PROJECT_KEY")); indexPermissions(); ComponentDto file = db.components().insertComponent(newFileDto(project, null, "FILE_ID").setKey("FILE_KEY")); RuleDto rule = newIssueRule(); @@ -908,7 +908,7 @@ public class SearchActionTest { @Test public void filter_by_test_scope() { - ComponentDto project = db.components().insertComponent(ComponentTesting.newPublicProjectDto("PROJECT_ID").setKey("PROJECT_KEY")); + ComponentDto project = db.components().insertPublicProject("PROJECT_ID", c -> c.setKey("PROJECT_KEY")); indexPermissions(); ComponentDto mainCodeFile = db.components().insertComponent( newFileDto(project, null, "FILE_ID").setKey("FILE_KEY")); @@ -949,7 +949,7 @@ public class SearchActionTest { @Test public void filter_by_main_scope() { - ComponentDto project = db.components().insertComponent(ComponentTesting.newPublicProjectDto("PROJECT_ID").setKey("PROJECT_KEY")); + ComponentDto project = db.components().insertPublicProject("PROJECT_ID", c -> c.setKey("PROJECT_KEY")); indexPermissions(); ComponentDto mainCodeFile = db.components().insertComponent( newFileDto(project, null, "FILE_ID").setKey("FILE_KEY")); @@ -993,7 +993,7 @@ public class SearchActionTest { @Test public void filter_by_scope_always_returns_all_scope_facet_values() { - ComponentDto project = db.components().insertComponent(ComponentTesting.newPublicProjectDto("PROJECT_ID").setKey("PROJECT_KEY")); + ComponentDto project = db.components().insertPublicProject("PROJECT_ID", c -> c.setKey("PROJECT_KEY")); indexPermissions(); ComponentDto mainCodeFile = db.components().insertComponent( newFileDto(project, null, "FILE_ID").setKey("FILE_KEY")); @@ -1028,7 +1028,7 @@ public class SearchActionTest { @Test public void sort_by_updated_at() { RuleDto rule = newIssueRule(); - ComponentDto project = db.components().insertComponent(ComponentTesting.newPublicProjectDto("PROJECT_ID").setKey("PROJECT_KEY")); + ComponentDto project = db.components().insertPublicProject("PROJECT_ID", c -> c.setKey("PROJECT_KEY")); indexPermissions(); ComponentDto file = db.components().insertComponent(newFileDto(project, null, "FILE_ID").setKey("FILE_KEY")); dbClient.issueDao().insert(session, newDto(rule, file, project) @@ -1693,7 +1693,7 @@ public class SearchActionTest { @Test public void paging() { RuleDto rule = newIssueRule(); - ComponentDto project = db.components().insertComponent(ComponentTesting.newPublicProjectDto("PROJECT_ID").setKey("PROJECT_KEY")); + ComponentDto project = db.components().insertPublicProject("PROJECT_ID", c -> c.setKey("PROJECT_KEY")); indexPermissions(); ComponentDto file = db.components().insertComponent(newFileDto(project, null, "FILE_ID").setKey("FILE_KEY")); for (int i = 0; i < 12; i++) { @@ -1712,7 +1712,6 @@ public class SearchActionTest { @Test public void paging_with_page_size_to_minus_one() { - TestRequest requestWithNegativePageSize = ws.newRequest() .setParam(WebService.Param.PAGE, "1") .setParam(WebService.Param.PAGE_SIZE, "-1"); diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/ws/SearchResponseFormatFormatOperationTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/ws/SearchResponseFormatFormatOperationTest.java index 2aefccfc0fa..002afa20449 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/ws/SearchResponseFormatFormatOperationTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/ws/SearchResponseFormatFormatOperationTest.java @@ -25,16 +25,20 @@ import java.util.Date; import java.util.List; import java.util.Set; import org.junit.Before; +import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; -import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import org.sonar.api.resources.Languages; import org.sonar.api.utils.Duration; import org.sonar.api.utils.Durations; +import org.sonar.db.DbTester; +import org.sonar.db.component.BranchDto; +import org.sonar.db.component.BranchType; import org.sonar.db.component.ComponentDto; import org.sonar.db.issue.IssueChangeDto; import org.sonar.db.issue.IssueDto; +import org.sonar.db.project.ProjectDto; import org.sonar.db.rule.RuleDto; import org.sonar.db.user.UserDto; import org.sonar.server.issue.TextRangeResponseFormatter; @@ -49,14 +53,13 @@ import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.api.resources.Qualifiers.UNIT_TEST_FILE; import static org.sonar.api.rule.RuleKey.EXTERNAL_RULE_REPO_PREFIX; import static org.sonar.api.rules.RuleType.CODE_SMELL; import static org.sonar.api.rules.RuleType.SECURITY_HOTSPOT; import static org.sonar.api.utils.DateUtils.formatDateTime; -import static org.sonar.db.component.ComponentDto.BRANCH_KEY_SEPARATOR; -import static org.sonar.db.component.ComponentDto.PULL_REQUEST_SEPARATOR; import static org.sonar.db.component.ComponentTesting.newPrivateProjectDto; import static org.sonar.db.issue.IssueTesting.newIssue; import static org.sonar.db.issue.IssueTesting.newIssuechangeDto; @@ -67,33 +70,23 @@ import static org.sonar.server.issue.index.IssueScope.TEST; @RunWith(MockitoJUnitRunner.class) public class SearchResponseFormatFormatOperationTest { - - private SearchResponseFormat searchResponseFormat; - + @Rule + public DbTester db = DbTester.create(); private final Durations durations = new Durations(); - @Mock - private Languages languages; - @Mock - private TextRangeResponseFormatter textRangeResponseFormatter; - @Mock - private UserResponseFormatter userResponseFormatter; - @Mock - private Common.User user; + private final Languages languages = mock(Languages.class); + private final TextRangeResponseFormatter textRangeResponseFormatter = mock(TextRangeResponseFormatter.class); + private final UserResponseFormatter userResponseFormatter = mock(UserResponseFormatter.class); + private final Common.User user = mock(Common.User.class); + private final SearchResponseFormat searchResponseFormat = new SearchResponseFormat(durations, languages, textRangeResponseFormatter, userResponseFormatter); private SearchResponseData searchResponseData; private IssueDto issueDto; private ComponentDto componentDto; private UserDto userDto; - @Before public void setUp() { - searchResponseFormat = new SearchResponseFormat(durations, languages, textRangeResponseFormatter, userResponseFormatter); - searchResponseData = newSearchResponseData(); - issueDto = searchResponseData.getIssues().get(0); - componentDto = searchResponseData.getComponents().iterator().next(); - userDto = searchResponseData.getUsers().get(0); - when(userResponseFormatter.formatUser(any(Common.User.Builder.class), eq(userDto))).thenReturn(user); + searchResponseData = newSearchResponseDataMainBranch(); } @Test @@ -168,21 +161,16 @@ public class SearchResponseFormatFormatOperationTest { @Test public void formatOperation_should_add_branch_on_issue() { String branchName = randomAlphanumeric(5); - componentDto.setKey(randomAlphanumeric(5) + BRANCH_KEY_SEPARATOR + branchName); - + searchResponseData = newSearchResponseDataBranch(branchName); Operation result = searchResponseFormat.formatOperation(searchResponseData); - assertThat(result.getIssue().getBranch()).isEqualTo(branchName); } @Test public void formatOperation_should_add_pullrequest_on_issue() { - String pullRequestKey = randomAlphanumeric(5); - componentDto.setKey(randomAlphanumeric(5) + PULL_REQUEST_SEPARATOR + pullRequestKey); - + searchResponseData = newSearchResponseDataPr("pr1"); Operation result = searchResponseFormat.formatOperation(searchResponseData); - - assertThat(result.getIssue().getPullRequest()).isEqualTo(pullRequestKey); + assertThat(result.getIssue().getPullRequest()).isEqualTo("pr1"); } @Test @@ -280,16 +268,31 @@ public class SearchResponseFormatFormatOperationTest { assertThat(result.getIssue().hasSeverity()).isFalse(); } - private static SearchResponseData newSearchResponseData() { - RuleDto ruleDto = newRule(); + private SearchResponseData newSearchResponseDataMainBranch() { + ComponentDto projectDto = db.components().insertPublicProject(); + BranchDto branchDto = db.getDbClient().branchDao().selectByUuid(db.getSession(), projectDto.uuid()).get(); + return newSearchResponseData(projectDto, branchDto); + } - String projectUuid = "project_uuid_" + randomAlphanumeric(5); - ComponentDto projectDto = newPrivateProjectDto(); - projectDto.setBranchUuid(projectUuid); + private SearchResponseData newSearchResponseDataBranch(String name) { + ProjectDto projectDto = db.components().insertPublicProjectDto(); + BranchDto branch = db.components().insertProjectBranch(projectDto, b -> b.setKey(name)); + ComponentDto branchComponent = db.components().getComponentDto(branch); + return newSearchResponseData(branchComponent, branch); + } - UserDto userDto = newUserDto(); + private SearchResponseData newSearchResponseDataPr(String name) { + ProjectDto projectDto = db.components().insertPublicProjectDto(); + BranchDto branch = db.components().insertProjectBranch(projectDto, b -> b.setKey(name).setBranchType(BranchType.PULL_REQUEST)); + ComponentDto branchComponent = db.components().getComponentDto(branch); + return newSearchResponseData(branchComponent, branch); + } - IssueDto issueDto = newIssue(ruleDto, projectUuid, "project_key_" + randomAlphanumeric(5), projectDto) + private SearchResponseData newSearchResponseData(ComponentDto component, BranchDto branch) { + RuleDto ruleDto = newRule(); + userDto = newUserDto(); + componentDto = component; + issueDto = newIssue(ruleDto, component.branchUuid(), component.getKey(), component) .setType(CODE_SMELL) .setRuleDescriptionContextKey("context_key_" + randomAlphanumeric(5)) .setAssigneeUuid(userDto.getUuid()) @@ -299,10 +302,13 @@ public class SearchResponseFormatFormatOperationTest { .setIssueCloseDate(new Date(currentTimeMillis())); SearchResponseData searchResponseData = new SearchResponseData(issueDto); - searchResponseData.addComponents(List.of(projectDto)); + searchResponseData.addComponents(List.of(component)); searchResponseData.addRules(List.of(ruleDto)); searchResponseData.addUsers(List.of(userDto)); + searchResponseData.addBranches(List.of(branch)); + + when(userResponseFormatter.formatUser(any(Common.User.Builder.class), eq(userDto))).thenReturn(user); + return searchResponseData; } - } diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/measure/ws/ComponentTreeActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/measure/ws/ComponentTreeActionTest.java index 0a9738731fa..b2e489198fc 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/measure/ws/ComponentTreeActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/measure/ws/ComponentTreeActionTest.java @@ -745,7 +745,7 @@ public class ComponentTreeActionTest { .containsExactlyInAnyOrder(applicationBranch.getKey(), branchName); assertThat(result.getComponentsList()) .extracting(Component::getKey, Component::getBranch, Component::getRefKey) - .containsExactlyInAnyOrder(tuple(techProjectBranch.getKey(), branchName, project.getKey())); + .containsExactlyInAnyOrder(tuple(techProjectBranch.getKey(), "project-branch", project.getKey())); } @Test diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/setting/TestProjectConfigurationLoader.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/setting/TestProjectConfigurationLoader.java index 99f68726f7e..980b52eab32 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/setting/TestProjectConfigurationLoader.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/setting/TestProjectConfigurationLoader.java @@ -19,9 +19,6 @@ */ package org.sonar.server.setting; -import java.util.HashMap; -import java.util.Map; -import java.util.Set; import org.sonar.api.config.Configuration; import org.sonar.db.DbSession; import org.sonar.db.component.ComponentDto; @@ -35,11 +32,7 @@ public class TestProjectConfigurationLoader implements ProjectConfigurationLoade } @Override - public Map loadProjectConfigurations(DbSession dbSession, Set projects) { - Map map = new HashMap<>(); - for (ComponentDto project : projects) { - map.put(project.uuid(), config); - } - return map; + public Configuration loadProjectConfiguration(DbSession dbSession, ComponentDto project) { + return config; } } diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/setting/ws/SetActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/setting/ws/SetActionTest.java index 3588b546471..fa0793b972b 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/setting/ws/SetActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/setting/ws/SetActionTest.java @@ -320,7 +320,7 @@ public class SetActionTest { project.getKey()); assertThat(dbClient.propertiesDao().selectGlobalProperties(dbSession)).hasSize(3); - assertThat(dbClient.propertiesDao().selectProjectProperties(dbSession, project.getKey())).hasSize(5); + assertThat(dbClient.propertiesDao().selectComponentProperties(dbSession, project.uuid())).hasSize(5); assertGlobalSetting("my.key", "1"); assertGlobalSetting("my.key.1.firstField", "oldFirstValue"); assertGlobalSetting("my.key.1.secondField", "oldSecondValue"); diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/setting/ws/ValuesActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/setting/ws/ValuesActionTest.java index e6b399e4295..51210fe4b8e 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/setting/ws/ValuesActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/setting/ws/ValuesActionTest.java @@ -32,17 +32,14 @@ import org.sonar.api.PropertyType; import org.sonar.api.config.PropertyDefinition; import org.sonar.api.config.PropertyDefinitions; import org.sonar.api.config.PropertyFieldDefinition; -import org.sonar.api.config.internal.MapSettings; import org.sonar.api.server.ws.WebService; import org.sonar.api.utils.System2; import org.sonar.api.web.UserRole; import org.sonar.db.DbClient; import org.sonar.db.DbTester; -import org.sonar.db.component.ComponentDbTester; import org.sonar.db.component.ComponentDto; import org.sonar.db.component.ComponentTesting; import org.sonar.db.permission.GlobalPermission; -import org.sonar.db.property.PropertyDbTester; import org.sonar.process.ProcessProperties; import org.sonar.server.component.TestComponentFinder; import org.sonar.server.exceptions.ForbiddenException; @@ -75,23 +72,22 @@ import static org.sonarqube.ws.Settings.Setting.ParentValueOneOfCase.PARENTVALUE public class ValuesActionTest { - private static Joiner COMMA_JOINER = Joiner.on(","); + private static final Joiner COMMA_JOINER = Joiner.on(","); @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @Rule public DbTester db = DbTester.create(System2.INSTANCE); - private DbClient dbClient = db.getDbClient(); - private PropertyDbTester propertyDb = new PropertyDbTester(db); - private ComponentDbTester componentDb = new ComponentDbTester(db); - private PropertyDefinitions definitions = new PropertyDefinitions(System2.INSTANCE); - private SettingsWsSupport support = new SettingsWsSupport(userSession); + private final DbClient dbClient = db.getDbClient(); + private final PropertyDefinitions definitions = new PropertyDefinitions(System2.INSTANCE); + private final SettingsWsSupport support = new SettingsWsSupport(userSession); + private final WsActionTester wsActionTester = new WsActionTester(new ValuesAction(dbClient, TestComponentFinder.from(db), userSession, definitions, support)); private ComponentDto project; @Before public void setUp() { - project = componentDb.insertComponent(ComponentTesting.newPrivateProjectDto()); + project = db.components().insertPrivateProject(); } @Test @@ -100,7 +96,7 @@ public class ValuesActionTest { definitions.addComponent(PropertyDefinition .builder("foo") .build()); - propertyDb.insertProperties(null, null, null, null, newGlobalPropertyDto().setKey("foo").setValue("one")); + db.properties().insertProperties(null, null, null, null, newGlobalPropertyDto().setKey("foo").setValue("one")); ValuesWsResponse result = executeRequestForGlobalProperties("foo"); @@ -123,7 +119,7 @@ public class ValuesActionTest { definitions.addComponent(PropertyDefinition.builder("global") .multiValues(true) .build()); - propertyDb.insertProperties(null, null, null, null, newGlobalPropertyDto().setKey("global").setValue("three,four")); + db.properties().insertProperties(null, null, null, null, newGlobalPropertyDto().setKey("global").setValue("three,four")); ValuesWsResponse result = executeRequestForGlobalProperties("default", "global"); assertThat(result.getSettingsList()).hasSize(2); @@ -141,7 +137,7 @@ public class ValuesActionTest { public void return_multi_value_with_coma() { logIn(); definitions.addComponent(PropertyDefinition.builder("global").multiValues(true).build()); - propertyDb.insertProperties(null, null, null, null, newGlobalPropertyDto().setKey("global").setValue("three,four%2Cfive")); + db.properties().insertProperties(null, null, null, null, newGlobalPropertyDto().setKey("global").setValue("three,four%2Cfive")); ValuesWsResponse result = executeRequestForGlobalProperties("global"); @@ -161,7 +157,7 @@ public class ValuesActionTest { PropertyFieldDefinition.build("key").name("Key").build(), PropertyFieldDefinition.build("size").name("Size").build())) .build()); - propertyDb.insertPropertySet("foo", null, ImmutableMap.of("key", "key1", "size", "size1"), ImmutableMap.of("key", "key2")); + db.properties().insertPropertySet("foo", null, ImmutableMap.of("key", "key1", "size", "size1"), ImmutableMap.of("key", "key2")); ValuesWsResponse result = executeRequestForGlobalProperties("foo"); @@ -182,7 +178,7 @@ public class ValuesActionTest { PropertyFieldDefinition.build("key").name("Key").build(), PropertyFieldDefinition.build("size").name("Size").build())) .build()); - propertyDb.insertPropertySet("foo", project, ImmutableMap.of("key", "key1", "size", "size1"), ImmutableMap.of("key", "key2")); + db.properties().insertPropertySet("foo", project, ImmutableMap.of("key", "key1", "size", "size1"), ImmutableMap.of("key", "key2")); ValuesWsResponse result = executeRequestForProjectProperties("foo"); @@ -210,7 +206,7 @@ public class ValuesActionTest { public void return_global_values() { logIn(); definitions.addComponent(PropertyDefinition.builder("property").defaultValue("default").build()); - propertyDb.insertProperties(null, null, null, + db.properties().insertProperties(null, null, null, // The property is overriding default value null, newGlobalPropertyDto().setKey("property").setValue("one")); @@ -225,9 +221,9 @@ public class ValuesActionTest { logInAsProjectUser(); definitions.addComponent( PropertyDefinition.builder("property").defaultValue("default").onQualifiers(PROJECT).build()); - propertyDb.insertProperties(null, null, null, + db.properties().insertProperties(null, null, null, null, newGlobalPropertyDto().setKey("property").setValue("one")); - propertyDb.insertProperties(null, project.getKey(), project.name(), project.qualifier(), + db.properties().insertProperties(null, project.getKey(), project.name(), project.qualifier(), // The property is overriding global value newComponentPropertyDto(project).setKey("property").setValue("two")); @@ -244,9 +240,9 @@ public class ValuesActionTest { PropertyDefinition.builder("global").build(), PropertyDefinition.builder("global.default").defaultValue("default").build(), PropertyDefinition.builder("project").onQualifiers(PROJECT).build())); - propertyDb.insertProperties(null, null, null, + db.properties().insertProperties(null, null, null, null, newGlobalPropertyDto().setKey("global").setValue("one")); - propertyDb.insertProperties(null, project.getKey(), project.name(), project.qualifier(), + db.properties().insertProperties(null, project.getKey(), project.name(), project.qualifier(), newComponentPropertyDto(project).setKey("project").setValue("two")); ValuesWsResponse result = executeRequestForProjectProperties(); @@ -260,7 +256,7 @@ public class ValuesActionTest { logInAsProjectUser(); definitions.addComponent(PropertyDefinition.builder("property").defaultValue("default").onQualifiers(PROJECT).build()); // The property is not defined on project - propertyDb.insertProperties(null, null, null, null, + db.properties().insertProperties(null, null, null, null, newGlobalPropertyDto().setKey("property").setValue("one")); ValuesWsResponse result = executeRequestForProjectProperties("property"); @@ -272,7 +268,7 @@ public class ValuesActionTest { @Test public void return_values_even_if_no_property_definition() { logIn(); - propertyDb.insertProperties(null, null, null, null, + db.properties().insertProperties(null, null, null, null, newGlobalPropertyDto().setKey("globalPropertyWithoutDefinition").setValue("value")); ValuesWsResponse result = executeRequestForGlobalProperties("globalPropertyWithoutDefinition"); @@ -286,7 +282,7 @@ public class ValuesActionTest { @Test public void return_values_of_component_even_if_no_property_definition() { logInAsProjectUser(); - propertyDb.insertProperties(null, project.getKey(), project.name(), project.qualifier(), + db.properties().insertProperties(null, project.getKey(), project.name(), project.qualifier(), newComponentPropertyDto(project).setKey("property").setValue("foo")); ValuesWsResponse response = executeRequestForComponentProperties(project, "property"); @@ -313,7 +309,7 @@ public class ValuesActionTest { .builder("foo") .defaultValue("default") .build()); - propertyDb.insertProperties(null, null, null, null, + db.properties().insertProperties(null, null, null, null, newGlobalPropertyDto().setKey("bar").setValue("")); ValuesWsResponse result = executeRequestForGlobalProperties("unknown"); @@ -324,11 +320,11 @@ public class ValuesActionTest { @Test public void return_module_values() { logInAsProjectUser(); - ComponentDto module = componentDb.insertComponent(newModuleDto(project)); + ComponentDto module = db.components().insertComponent(newModuleDto(project)); definitions.addComponent(PropertyDefinition.builder("property").defaultValue("default").onQualifiers(PROJECT, MODULE).build()); - propertyDb.insertProperties(null, null, null, null, + db.properties().insertProperties(null, null, null, null, newGlobalPropertyDto().setKey("property").setValue("one")); - propertyDb.insertProperties(null, module.getKey(), module.name(), module.qualifier(), + db.properties().insertProperties(null, module.getKey(), module.name(), module.qualifier(), // The property is overriding global value newComponentPropertyDto(module).setKey("property").setValue("two")); @@ -341,17 +337,17 @@ public class ValuesActionTest { @Test public void return_inherited_values_on_module() { logInAsProjectUser(); - ComponentDto module = componentDb.insertComponent(newModuleDto(project)); + ComponentDto module = db.components().insertComponent(newModuleDto(project)); definitions.addComponents(asList( PropertyDefinition.builder("defaultProperty").defaultValue("default").onQualifiers(PROJECT, MODULE).build(), PropertyDefinition.builder("globalProperty").onQualifiers(PROJECT, MODULE).build(), PropertyDefinition.builder("projectProperty").onQualifiers(PROJECT, MODULE).build(), PropertyDefinition.builder("moduleProperty").onQualifiers(PROJECT, MODULE).build())); - propertyDb.insertProperties(null, null, null, null, + db.properties().insertProperties(null, null, null, null, newGlobalPropertyDto().setKey("globalProperty").setValue("global")); - propertyDb.insertProperties(null, project.getKey(), project.name(), project.qualifier(), + db.properties().insertProperties(null, project.getKey(), project.name(), project.qualifier(), newComponentPropertyDto(project).setKey("projectProperty").setValue("project")); - propertyDb.insertProperties(null, module.getKey(), module.name(), module.qualifier(), + db.properties().insertProperties(null, module.getKey(), module.name(), module.qualifier(), newComponentPropertyDto(module).setKey("moduleProperty").setValue("module")); ValuesWsResponse result = executeRequestForComponentProperties(module, "defaultProperty", "globalProperty", "projectProperty", "moduleProperty"); @@ -369,7 +365,7 @@ public class ValuesActionTest { definitions.addComponents(asList( PropertyDefinition.builder("defaultProperty").defaultValue("default").build(), PropertyDefinition.builder("globalProperty").build())); - propertyDb.insertProperties(null, null, null, null, + db.properties().insertProperties(null, null, null, null, newGlobalPropertyDto().setKey("globalProperty").setValue("global")); ValuesWsResponse result = executeRequestForGlobalProperties("defaultProperty", "globalProperty"); @@ -382,15 +378,15 @@ public class ValuesActionTest { @Test public void return_parent_value() { logInAsProjectUser(); - ComponentDto module = componentDb.insertComponent(newModuleDto(project)); - ComponentDto subModule = componentDb.insertComponent(newModuleDto(module)); + ComponentDto module = db.components().insertComponent(newModuleDto(project)); + ComponentDto subModule = db.components().insertComponent(newModuleDto(module)); definitions.addComponents(asList( PropertyDefinition.builder("foo").defaultValue("default").onQualifiers(PROJECT, MODULE).build())); - propertyDb.insertProperties(null, null, null, null, + db.properties().insertProperties(null, null, null, null, newGlobalPropertyDto().setKey("foo").setValue("global")); - propertyDb.insertProperties(null, project.getKey(), project.name(), project.qualifier(), + db.properties().insertProperties(null, project.getKey(), project.name(), project.qualifier(), newComponentPropertyDto(project).setKey("foo").setValue("project")); - propertyDb.insertProperties(null, module.getKey(), module.name(), module.qualifier(), + db.properties().insertProperties(null, module.getKey(), module.name(), module.qualifier(), newComponentPropertyDto(module).setKey("foo").setValue("module")); assertParentValue(executeRequestForComponentProperties(subModule, "foo").getSettings(0), "module"); @@ -402,15 +398,15 @@ public class ValuesActionTest { @Test public void return_parent_values() { logInAsProjectUser(); - ComponentDto module = componentDb.insertComponent(newModuleDto(project)); - ComponentDto subModule = componentDb.insertComponent(newModuleDto(module)); + ComponentDto module = db.components().insertComponent(newModuleDto(project)); + ComponentDto subModule = db.components().insertComponent(newModuleDto(module)); definitions.addComponents(asList( PropertyDefinition.builder("foo").defaultValue("default1,default2").multiValues(true).onQualifiers(PROJECT, MODULE).build())); - propertyDb.insertProperties(null, null, null, null, + db.properties().insertProperties(null, null, null, null, newGlobalPropertyDto().setKey("foo").setValue("global1,global2")); - propertyDb.insertProperties(null, project.getKey(), project.name(), project.qualifier(), + db.properties().insertProperties(null, project.getKey(), project.name(), project.qualifier(), newComponentPropertyDto(project).setKey("foo").setValue("project1,project2")); - propertyDb.insertProperties(null, module.getKey(), module.name(), module.qualifier(), + db.properties().insertProperties(null, module.getKey(), module.name(), module.qualifier(), newComponentPropertyDto(module).setKey("foo").setValue("module1,module2")); assertParentValues(executeRequestForComponentProperties(subModule, "foo").getSettings(0), "module1", "module2"); @@ -422,8 +418,8 @@ public class ValuesActionTest { @Test public void return_parent_field_values() { logInAsProjectUser(); - ComponentDto module = componentDb.insertComponent(newModuleDto(project)); - ComponentDto subModule = componentDb.insertComponent(newModuleDto(module)); + ComponentDto module = db.components().insertComponent(newModuleDto(project)); + ComponentDto subModule = db.components().insertComponent(newModuleDto(module)); definitions.addComponent(PropertyDefinition .builder("foo") .onQualifiers(PROJECT, MODULE) @@ -432,9 +428,9 @@ public class ValuesActionTest { PropertyFieldDefinition.build("key").name("Key").build(), PropertyFieldDefinition.build("size").name("Size").build())) .build()); - propertyDb.insertPropertySet("foo", null, ImmutableMap.of("key", "keyG1", "size", "sizeG1")); - propertyDb.insertPropertySet("foo", project, ImmutableMap.of("key", "keyP1", "size", "sizeP1")); - propertyDb.insertPropertySet("foo", module, ImmutableMap.of("key", "keyM1", "size", "sizeM1")); + db.properties().insertPropertySet("foo", null, ImmutableMap.of("key", "keyG1", "size", "sizeG1")); + db.properties().insertPropertySet("foo", project, ImmutableMap.of("key", "keyP1", "size", "sizeP1")); + db.properties().insertPropertySet("foo", module, ImmutableMap.of("key", "keyM1", "size", "sizeM1")); assertParentFieldValues(executeRequestForComponentProperties(subModule, "foo").getSettings(0), ImmutableMap.of("key", "keyM1", "size", "sizeM1")); assertParentFieldValues(executeRequestForComponentProperties(module, "foo").getSettings(0), ImmutableMap.of("key", "keyP1", "size", "sizeP1")); @@ -445,8 +441,8 @@ public class ValuesActionTest { @Test public void return_no_parent_value() { logInAsProjectUser(); - ComponentDto module = componentDb.insertComponent(newModuleDto(project)); - ComponentDto subModule = componentDb.insertComponent(newModuleDto(module)); + ComponentDto module = db.components().insertComponent(newModuleDto(project)); + ComponentDto subModule = db.components().insertComponent(newModuleDto(module)); definitions.addComponents(asList( PropertyDefinition.builder("simple").onQualifiers(PROJECT, MODULE).build(), PropertyDefinition.builder("multi").multiValues(true).onQualifiers(PROJECT, MODULE).build(), @@ -457,10 +453,10 @@ public class ValuesActionTest { PropertyFieldDefinition.build("key").name("Key").build(), PropertyFieldDefinition.build("size").name("Size").build())) .build())); - propertyDb.insertProperties(null, module.getKey(), module.name(), module.qualifier(), + db.properties().insertProperties(null, module.getKey(), module.name(), module.qualifier(), newComponentPropertyDto(module).setKey("simple").setValue("module"), newComponentPropertyDto(module).setKey("multi").setValue("module1,module2")); - propertyDb.insertPropertySet("set", module, ImmutableMap.of("key", "keyM1", "size", "sizeM1")); + db.properties().insertPropertySet("set", module, ImmutableMap.of("key", "keyM1", "size", "sizeM1")); assertParentValue(executeRequestForComponentProperties(subModule, "simple").getSettings(0), null); assertParentValues(executeRequestForComponentProperties(subModule, "multi").getSettings(0)); @@ -470,10 +466,10 @@ public class ValuesActionTest { @Test public void return_parent_value_when_no_definition() { logInAsProjectUser(); - ComponentDto module = componentDb.insertComponent(newModuleDto(project)); - propertyDb.insertProperties(null, null, null, null, + ComponentDto module = db.components().insertComponent(newModuleDto(project)); + db.properties().insertProperties(null, null, null, null, newGlobalPropertyDto().setKey("foo").setValue("global")); - propertyDb.insertProperties(null, project.getKey(), project.name(), project.qualifier(), + db.properties().insertProperties(null, project.getKey(), project.name(), project.qualifier(), newComponentPropertyDto(project).setKey("foo").setValue("project")); assertParentValue(executeRequestForComponentProperties(module, "foo").getSettings(0), "project"); @@ -488,7 +484,7 @@ public class ValuesActionTest { .builder("foo") .deprecatedKey("deprecated") .build()); - propertyDb.insertProperties(null, null, null, null, + db.properties().insertProperties(null, null, null, null, newGlobalPropertyDto().setKey("foo").setValue("one")); ValuesWsResponse result = executeRequestForGlobalProperties("deprecated"); @@ -504,7 +500,7 @@ public class ValuesActionTest { definitions.addComponents(asList( PropertyDefinition.builder("foo").build(), PropertyDefinition.builder("secret.secured").build())); - propertyDb.insertProperties(null, null, null, null, + db.properties().insertProperties(null, null, null, null, newGlobalPropertyDto().setKey("foo").setValue("one"), newGlobalPropertyDto().setKey("secret.secured").setValue("password")); @@ -522,7 +518,7 @@ public class ValuesActionTest { PropertyFieldDefinition.build("key").name("Key").build(), PropertyFieldDefinition.build("secret.secured").name("Secured").build())) .build()); - propertyDb.insertPropertySet("foo", null, ImmutableMap.of("key", "key1", "secret.secured", "123456")); + db.properties().insertPropertySet("foo", null, ImmutableMap.of("key", "key1", "secret.secured", "123456")); ValuesWsResponse result = executeRequestForGlobalProperties(); @@ -535,7 +531,7 @@ public class ValuesActionTest { definitions.addComponents(asList( PropertyDefinition.builder("foo").build(), PropertyDefinition.builder("secret.secured").build())); - propertyDb.insertProperties(null, null, null, null, + db.properties().insertProperties(null, null, null, null, newGlobalPropertyDto().setKey("foo").setValue("one"), newGlobalPropertyDto().setKey("secret.secured").setValue("password")); @@ -554,9 +550,9 @@ public class ValuesActionTest { PropertyDefinition.builder("foo").onQualifiers(PROJECT).build(), PropertyDefinition.builder("global.secret.secured").build(), PropertyDefinition.builder("secret.secured").onQualifiers(PROJECT).build())); - propertyDb.insertProperties(null, null, null, null, + db.properties().insertProperties(null, null, null, null, newGlobalPropertyDto().setKey("global.secret.secured").setValue("very secret")); - propertyDb.insertProperties(null, project.getKey(), project.name(), project.qualifier(), + db.properties().insertProperties(null, project.getKey(), project.name(), project.qualifier(), newComponentPropertyDto(project).setKey("foo").setValue("one"), newComponentPropertyDto(project).setKey("secret.secured").setValue("password")); @@ -571,7 +567,7 @@ public class ValuesActionTest { userSession .addProjectPermission(USER, project) .addProjectPermission(SCAN_EXECUTION, project); - propertyDb.insertProperties(null, project.getKey(), project.name(), project.qualifier(), + db.properties().insertProperties(null, project.getKey(), project.name(), project.qualifier(), newComponentPropertyDto(project).setKey("not-defined.secured").setValue("123")); ValuesWsResponse result = executeRequestForProjectProperties("not-defined.secured"); @@ -585,7 +581,7 @@ public class ValuesActionTest { definitions.addComponents(asList( PropertyDefinition.builder("foo").build(), PropertyDefinition.builder("secret.secured").build())); - propertyDb.insertProperties(null, null, null, null, + db.properties().insertProperties(null, null, null, null, newGlobalPropertyDto().setKey("foo").setValue("one"), newGlobalPropertyDto().setKey("secret.secured").setValue("password")); @@ -602,9 +598,9 @@ public class ValuesActionTest { PropertyDefinition.builder("foo").onQualifiers(PROJECT).build(), PropertyDefinition.builder("global.secret.secured").build(), PropertyDefinition.builder("secret.secured").onQualifiers(PROJECT).build())); - propertyDb.insertProperties(null, null, null, null, + db.properties().insertProperties(null, null, null, null, newGlobalPropertyDto().setKey("global.secret.secured").setValue("very secret")); - propertyDb.insertProperties(null, project.getKey(), project.name(), project.qualifier(), + db.properties().insertProperties(null, project.getKey(), project.name(), project.qualifier(), newComponentPropertyDto(project).setKey("foo").setValue("one"), newComponentPropertyDto(project).setKey("secret.secured").setValue("password")); @@ -619,7 +615,7 @@ public class ValuesActionTest { @Test public void return_secured_settings_even_if_not_defined_when_project_admin() { logInAsProjectAdmin(); - propertyDb.insertProperties(null, project.getKey(), project.name(), project.qualifier(), + db.properties().insertProperties(null, project.getKey(), project.name(), project.qualifier(), newComponentPropertyDto(project).setKey("not-defined.secured").setValue("123")); ValuesWsResponse result = executeRequestForProjectProperties("not-defined.secured"); @@ -638,7 +634,7 @@ public class ValuesActionTest { PropertyFieldDefinition.build("key").name("Key").build(), PropertyFieldDefinition.build("secret.secured").name("Secured").build())) .build()); - propertyDb.insertPropertySet("foo", null, ImmutableMap.of("key", "key1", "secret.secured", "123456")); + db.properties().insertPropertySet("foo", null, ImmutableMap.of("key", "key1", "secret.secured", "123456")); ValuesWsResponse result = executeRequestForGlobalProperties(); @@ -657,7 +653,7 @@ public class ValuesActionTest { PropertyFieldDefinition.build(anyAdminOnlySettingKey).name("Value admin only").build())) .build()); ImmutableMap keyValuePairs = ImmutableMap.of(anyAdminOnlySettingKey, "test_val"); - propertyDb.insertPropertySet(anyAdminOnlySettingKey, null, keyValuePairs); + db.properties().insertPropertySet(anyAdminOnlySettingKey, null, keyValuePairs); ValuesWsResponse result = executeRequestForGlobalProperties(); @@ -676,7 +672,7 @@ public class ValuesActionTest { PropertyFieldDefinition.build(anyAdminOnlySettingKey).name("Value admin only").build())) .build()); ImmutableMap keyValuePairs = ImmutableMap.of(anyAdminOnlySettingKey, "test_val"); - propertyDb.insertPropertySet(anyAdminOnlySettingKey, null, keyValuePairs); + db.properties().insertPropertySet(anyAdminOnlySettingKey, null, keyValuePairs); ValuesWsResponse result = executeRequestForGlobalProperties(); @@ -689,7 +685,7 @@ public class ValuesActionTest { definitions.addComponents(asList( PropertyDefinition.builder("foo").build(), PropertyDefinition.builder("secret.secured").build())); - propertyDb.insertProperties(null, null, null, null, + db.properties().insertProperties(null, null, null, null, newGlobalPropertyDto().setKey("foo").setValue("one"), newGlobalPropertyDto().setKey("secret.secured").setValue("password")); @@ -705,7 +701,7 @@ public class ValuesActionTest { definitions.addComponents(asList( PropertyDefinition.builder("foo").onQualifiers(PROJECT).build(), PropertyDefinition.builder("secret.secured").onQualifiers(PROJECT).build())); - propertyDb.insertProperties(null, project.getKey(), project.name(), project.qualifier(), + db.properties().insertProperties(null, project.getKey(), project.name(), project.qualifier(), newComponentPropertyDto(project).setKey("foo").setValue("one"), newComponentPropertyDto(project).setKey("secret.secured").setValue("password")); @@ -719,7 +715,7 @@ public class ValuesActionTest { public void return_additional_settings_specific_for_scanner_when_no_keys() { logInAsAdmin(); definitions.addComponent(PropertyDefinition.builder("secret.secured").build()); - propertyDb.insertProperties(null, null, null, null, + db.properties().insertProperties(null, null, null, null, newGlobalPropertyDto().setKey("sonar.core.id").setValue("ID"), newGlobalPropertyDto().setKey("sonar.core.startTime").setValue("2017-01-01")); @@ -734,7 +730,7 @@ public class ValuesActionTest { definitions.addComponent(PropertyDefinition .builder("foo") .build()); - propertyDb.insertProperties(null, null, null, null, + db.properties().insertProperties(null, null, null, null, newGlobalPropertyDto().setKey("foo").setValue("fi±∞…")); ValuesWsResponse result = executeRequestForGlobalProperties("foo"); @@ -760,7 +756,7 @@ public class ValuesActionTest { .builder("foo") .deprecatedKey("deprecated") .build()); - propertyDb.insertProperties(null, null, null, null, + db.properties().insertProperties(null, null, null, null, newGlobalPropertyDto().setKey("foo").setValue("one")); assertThatThrownBy(() -> { @@ -773,7 +769,7 @@ public class ValuesActionTest { @Test public void fail_when_component_not_found() { assertThatThrownBy(() -> { - newTester().newRequest() + wsActionTester.newRequest() .setParam("keys", "foo") .setParam("component", "unknown") .execute(); @@ -793,7 +789,7 @@ public class ValuesActionTest { .builder("sonar.autogenerated") .multiValues(true) .build()); - propertyDb.insertProperties(null, null, null, null, + db.properties().insertProperties(null, null, null, null, newGlobalPropertyDto().setKey("sonar.autogenerated").setValue("val1,val2,val3")); definitions.addComponent(PropertyDefinition .builder("sonar.demo") @@ -801,22 +797,22 @@ public class ValuesActionTest { .fields(PropertyFieldDefinition.build("text").name("Text").build(), PropertyFieldDefinition.build("boolean").name("Boolean").build()) .build()); - propertyDb.insertPropertySet("sonar.demo", null, ImmutableMap.of("text", "foo", "boolean", "true"), ImmutableMap.of("text", "bar", "boolean", "false")); + db.properties().insertPropertySet("sonar.demo", null, ImmutableMap.of("text", "foo", "boolean", "true"), ImmutableMap.of("text", "bar", "boolean", "false")); definitions.addComponent(PropertyDefinition .builder("email.smtp_port.secured") .defaultValue("25") .build()); - propertyDb.insertProperties(null, null, null, null, + db.properties().insertProperties(null, null, null, null, newGlobalPropertyDto().setKey("email.smtp_port.secured").setValue("25")); - String result = newTester().newRequest() + String result = wsActionTester.newRequest() .setParam("keys", "sonar.test.jira,sonar.autogenerated,sonar.demo,email.smtp_port.secured") .setMediaType(JSON) .execute() .getInput(); - JsonAssert.assertJson(newTester().getDef().responseExampleAsString()).isSimilarTo(result); + JsonAssert.assertJson(wsActionTester.getDef().responseExampleAsString()).isSimilarTo(result); } @Test @@ -826,7 +822,7 @@ public class ValuesActionTest { String settingKey = ProcessProperties.Property.JDBC_URL.getKey(); assertThatThrownBy(() -> { - newTester().newRequest() + wsActionTester.newRequest() .setParam("keys", settingKey) .setParam("component", project.getKey()) .execute(); @@ -837,7 +833,7 @@ public class ValuesActionTest { @Test public void test_ws_definition() { - WebService.Action action = newTester().getDef(); + WebService.Action action = wsActionTester.getDef(); assertThat(action).isNotNull(); assertThat(action.isInternal()).isFalse(); assertThat(action.isPost()).isFalse(); @@ -850,30 +846,29 @@ public class ValuesActionTest { PropertyDefinition securedDef = PropertyDefinition.builder("my.password.secured").build(); PropertyDefinition standardDef = PropertyDefinition.builder("my.property").build(); definitions.addComponents(asList(securedDef, standardDef)); - propertyDb.insertProperties(null, null, null, null, + db.properties().insertProperties(null, null, null, null, newGlobalPropertyDto().setKey(securedDef.key()).setValue("securedValue"), newGlobalPropertyDto().setKey(standardDef.key()).setValue("standardValue")); // anonymous - WsActionTester tester = newTester(); - ValuesWsResponse response = executeRequest(tester, null, securedDef.key(), standardDef.key()); + ValuesWsResponse response = executeRequest(null, securedDef.key(), standardDef.key()); assertThat(response.getSettingsList()).extracting(Settings.Setting::getKey).containsExactly("my.property"); // only scan global permission userSession.logIn() .addPermission(GlobalPermission.SCAN); - response = executeRequest(tester, null, securedDef.key(), standardDef.key()); + response = executeRequest(null, securedDef.key(), standardDef.key()); assertThat(response.getSetSecuredSettingsList()).contains("my.password.secured"); // global administrator userSession.logIn() .addPermission(GlobalPermission.ADMINISTER); - response = executeRequest(tester, null, securedDef.key(), standardDef.key()); + response = executeRequest(null, securedDef.key(), standardDef.key()); assertThat(response.getSetSecuredSettingsList()).contains("my.password.secured"); // system administrator userSession.logIn().setSystemAdministrator(); - response = executeRequest(tester, null, securedDef.key(), standardDef.key()); + response = executeRequest(null, securedDef.key(), standardDef.key()); assertThat(response.getSetSecuredSettingsList()).contains("my.password.secured"); } @@ -890,11 +885,7 @@ public class ValuesActionTest { } private ValuesWsResponse executeRequest(@Nullable String componentKey, String... keys) { - return executeRequest(newTester(), componentKey, keys); - } - - private ValuesWsResponse executeRequest(WsActionTester tester, @Nullable String componentKey, String... keys) { - TestRequest request = tester.newRequest(); + TestRequest request = wsActionTester.newRequest(); if (keys.length > 0) { request.setParam("keys", COMMA_JOINER.join(keys)); } @@ -965,10 +956,4 @@ public class ValuesActionTest { } } } - - private WsActionTester newTester() { - MapSettings settings = new MapSettings(); - return new WsActionTester(new ValuesAction(dbClient, TestComponentFinder.from(db), userSession, definitions, support)); - } - } -- cgit v1.2.3