]> source.dussan.org Git - sonarqube.git/commitdiff
SONAR-17352 Refactor component keys to not include branch suffix
authorLukasz Jarocki <lukasz.jarocki@sonarsource.com>
Fri, 30 Sep 2022 08:14:56 +0000 (10:14 +0200)
committersonartech <sonartech@sonarsource.com>
Wed, 12 Oct 2022 20:03:44 +0000 (20:03 +0000)
32 files changed:
server/sonar-db-dao/src/main/java/org/sonar/db/component/BranchDto.java
server/sonar-db-dao/src/main/java/org/sonar/db/component/ComponentDto.java
server/sonar-db-dao/src/test/java/org/sonar/db/component/ComponentKeyUpdaterDaoTest.java
server/sonar-webserver-es/src/main/java/org/sonar/server/issue/index/IssueQueryFactory.java
server/sonar-webserver-webapi/src/main/java/org/sonar/server/component/ws/AppAction.java
server/sonar-webserver-webapi/src/main/java/org/sonar/server/component/ws/ComponentDtoToWsComponent.java
server/sonar-webserver-webapi/src/main/java/org/sonar/server/component/ws/ComponentViewerJsonWriter.java
server/sonar-webserver-webapi/src/main/java/org/sonar/server/component/ws/ShowAction.java
server/sonar-webserver-webapi/src/main/java/org/sonar/server/component/ws/TreeAction.java
server/sonar-webserver-webapi/src/main/java/org/sonar/server/duplication/ws/ShowAction.java
server/sonar-webserver-webapi/src/main/java/org/sonar/server/hotspot/ws/HotspotWsResponseFormatter.java
server/sonar-webserver-webapi/src/main/java/org/sonar/server/hotspot/ws/SearchAction.java
server/sonar-webserver-webapi/src/main/java/org/sonar/server/issue/ws/SearchResponseData.java
server/sonar-webserver-webapi/src/main/java/org/sonar/server/issue/ws/SearchResponseFormat.java
server/sonar-webserver-webapi/src/main/java/org/sonar/server/issue/ws/SearchResponseLoader.java
server/sonar-webserver-webapi/src/main/java/org/sonar/server/measure/ws/ComponentAction.java
server/sonar-webserver-webapi/src/main/java/org/sonar/server/measure/ws/ComponentDtoToWsComponent.java
server/sonar-webserver-webapi/src/main/java/org/sonar/server/measure/ws/ComponentTreeAction.java
server/sonar-webserver-webapi/src/main/java/org/sonar/server/source/ws/IssueSnippetsAction.java
server/sonar-webserver-webapi/src/test/java/org/sonar/server/ce/ws/ActivityActionTest.java
server/sonar-webserver-webapi/src/test/java/org/sonar/server/component/ws/AppActionTest.java
server/sonar-webserver-webapi/src/test/java/org/sonar/server/component/ws/ShowActionTest.java
server/sonar-webserver-webapi/src/test/java/org/sonar/server/developers/ws/SearchEventsActionNewIssuesTest.java
server/sonar-webserver-webapi/src/test/java/org/sonar/server/duplication/ws/DuplicationsParserTest.java
server/sonar-webserver-webapi/src/test/java/org/sonar/server/duplication/ws/ShowActionTest.java
server/sonar-webserver-webapi/src/test/java/org/sonar/server/duplication/ws/ShowResponseBuilderTest.java
server/sonar-webserver-webapi/src/test/java/org/sonar/server/hotspot/ws/SearchActionTest.java
server/sonar-webserver-webapi/src/test/java/org/sonar/server/hotspot/ws/ShowActionTest.java
server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/ws/SearchActionComponentsTest.java
server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/ws/SearchResponseFormatFormatOperationTest.java
server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualitygate/ws/ProjectStatusActionTest.java
server/sonar-webserver-webapi/src/test/java/org/sonar/server/source/ws/LinesActionTest.java

index 755b6f8a274998c3c462a280381499c4c87a7501..35d5e85fef7fd5566c25f331f4f4f88734087583 100644 (file)
@@ -200,6 +200,16 @@ public class BranchDto {
     return this;
   }
 
+  @CheckForNull
+  public String getBranchKey() {
+    return branchType == BranchType.BRANCH ? kee : null;
+  }
+
+  @CheckForNull
+  public String getPullRequestKey() {
+    return branchType == BranchType.PULL_REQUEST ? kee : null;
+  }
+
   @Override
   public boolean equals(Object o) {
     if (this == o) {
index cb17c2a859e6d0facc2023b3da6925bfbaa6f7e9..0ace5776a854e1661a1d0122097db409f4a067ac 100644 (file)
@@ -193,15 +193,6 @@ public class ComponentDto {
     return split.size() == 2 ? split.get(1) : null;
   }
 
-  /**
-   * @return the pull request id. It will be null when the component is not on a pull request
-   */
-  @CheckForNull
-  public String getPullRequest() {
-    List<String> split = PULL_REQUEST_SPLITTER.splitToList(kee);
-    return split.size() == 2 ? split.get(1) : null;
-  }
-
   public String scope() {
     return scope;
   }
index e77ed5dd4e9b5bd792a2740fa31dc7865176bcab..89992ed1c3faacf984fee2cc6602c605f769395f 100644 (file)
@@ -23,6 +23,7 @@ import com.google.common.base.Strings;
 import java.util.List;
 import java.util.Map;
 import java.util.function.Predicate;
+import org.apache.commons.lang.RandomStringUtils;
 import org.assertj.core.groups.Tuple;
 import org.junit.Rule;
 import org.junit.Test;
@@ -186,7 +187,8 @@ public class ComponentKeyUpdaterDaoTest {
   @Test
   public void updateKey_updates_pull_requests_too() {
     ComponentDto project = db.components().insertPublicProject();
-    ComponentDto pullRequest = db.components().insertProjectBranch(project, b -> b.setBranchType(PULL_REQUEST));
+    String pullRequestKey1 = RandomStringUtils.randomAlphanumeric(100);
+    ComponentDto pullRequest = db.components().insertProjectBranch(project, b -> b.setBranchType(PULL_REQUEST).setKey(pullRequestKey1));
     db.components().insertComponent(newFileDto(pullRequest));
     db.components().insertComponent(newFileDto(pullRequest));
     int branchComponentCount = 3;
@@ -198,7 +200,7 @@ public class ComponentKeyUpdaterDaoTest {
     assertThat(dbClient.componentDao().selectAllComponentsFromProjectKey(dbSession, oldBranchKey)).hasSize(branchComponentCount);
 
     String newProjectKey = "newKey";
-    String newBranchKey = ComponentDto.generatePullRequestKey(newProjectKey, pullRequest.getPullRequest());
+    String newBranchKey = ComponentDto.generatePullRequestKey(newProjectKey, pullRequestKey1);
     underTest.updateKey(dbSession, project.uuid(), newProjectKey);
 
     assertThat(dbClient.componentDao().selectAllComponentsFromProjectKey(dbSession, oldProjectKey)).isEmpty();
index e1f6d21285edcbef848879388072108305cd1410..22d72c4b9210c07debd96ad7f27accc6454f1eb6 100644 (file)
@@ -50,6 +50,7 @@ import org.sonar.api.utils.log.Loggers;
 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.SnapshotDto;
 import org.sonar.db.rule.RuleDto;
@@ -284,11 +285,12 @@ public class IssueQueryFactory {
       .count() <= 1;
   }
 
-  private void addComponentParameters(IssueQuery.Builder builder, DbSession session, boolean onComponentOnly, List<ComponentDto> components, SearchRequest request) {
+  private void addComponentParameters(IssueQuery.Builder builder, DbSession session, boolean onComponentOnly, List<ComponentDto> components,
+    SearchRequest request) {
     builder.onComponentOnly(onComponentOnly);
     if (onComponentOnly) {
       builder.componentUuids(components.stream().map(ComponentDto::uuid).collect(toList()));
-      setBranch(builder, components.get(0), request.getBranch(), request.getPullRequest());
+      setBranch(builder, components.get(0), request.getBranch(), request.getPullRequest(), session);
       return;
     }
 
@@ -296,7 +298,7 @@ public class IssueQueryFactory {
     if (projectKeys != null) {
       List<ComponentDto> projects = getComponentsFromKeys(session, projectKeys, request.getBranch(), request.getPullRequest());
       builder.projectUuids(projects.stream().map(IssueQueryFactory::toProjectUuid).collect(toList()));
-      setBranch(builder, projects.get(0), request.getBranch(), request.getPullRequest());
+      setBranch(builder, projects.get(0), request.getBranch(), request.getPullRequest(), session);
     }
     builder.directories(request.getDirectories());
     builder.files(request.getFiles());
@@ -316,7 +318,7 @@ public class IssueQueryFactory {
     Set<String> qualifiers = components.stream().map(ComponentDto::qualifier).collect(toHashSet());
     checkArgument(qualifiers.size() == 1, "All components must have the same qualifier, found %s", String.join(",", qualifiers));
 
-    setBranch(builder, components.get(0), request.getBranch(), request.getPullRequest());
+    setBranch(builder, components.get(0), request.getBranch(), request.getPullRequest(), dbSession);
     String qualifier = qualifiers.iterator().next();
     switch (qualifier) {
       case Qualifiers.VIEW:
@@ -345,6 +347,12 @@ public class IssueQueryFactory {
     }
   }
 
+  private BranchDto findComponentBranch(DbSession dbSession, ComponentDto componentDto) {
+    Optional<BranchDto> optionalBranch = dbClient.branchDao().selectByUuid(dbSession, componentDto.branchUuid());
+    checkArgument(optionalBranch.isPresent(), "All components must belong to a branch. This error may indicate corrupted data.");
+    return optionalBranch.get();
+  }
+
   private void addProjectUuidsForApplication(IssueQuery.Builder builder, DbSession session, SearchRequest request) {
     List<String> projectKeys = request.getProjects();
     if (projectKeys != null) {
@@ -446,11 +454,14 @@ public class IssueQueryFactory {
     return mainBranchProjectUuid == null ? componentDto.branchUuid() : mainBranchProjectUuid;
   }
 
-  private static void setBranch(IssueQuery.Builder builder, ComponentDto component, @Nullable String branch, @Nullable String pullRequest) {
+  private void setBranch(IssueQuery.Builder builder, ComponentDto component, @Nullable String branch, @Nullable String pullRequest,
+    DbSession session) {
+    BranchDto branchDto = findComponentBranch(session, component);
+    String componentBranch = branchDto.isMain() ? null : branchDto.getBranchKey();
     builder.branchUuid(branch == null && pullRequest == null ? null : component.branchUuid());
     builder.mainBranch(UNKNOWN_COMPONENT.equals(component)
       || (branch == null && pullRequest == null)
-      || (branch != null && !branch.equals(component.getBranch()))
-      || (pullRequest != null && !pullRequest.equals(component.getPullRequest())));
+      || (branch != null && !branch.equals(componentBranch))
+      || (pullRequest != null && !pullRequest.equals(branchDto.getPullRequestKey())));
   }
 }
index 534de8210c99375d7bb81bdd9d776ab5b88278ef..81a0a19503c1f7e51d5401f5ab8012b27a861735 100644 (file)
@@ -88,7 +88,7 @@ public class AppAction implements ComponentsWsAction {
     try (DbSession session = dbClient.openSession(false)) {
       ComponentDto component = loadComponent(session, request);
       userSession.checkComponentPermission(UserRole.USER, component);
-      writeJsonResponse(response, session, component);
+      writeJsonResponse(response, session, component, request);
     }
   }
 
@@ -100,10 +100,11 @@ public class AppAction implements ComponentsWsAction {
     return componentFinder.getByKeyAndOptionalBranchOrPullRequest(dbSession, componentKey, branch, pullRequest);
   }
 
-  private void writeJsonResponse(Response response, DbSession session, ComponentDto component) {
+  private void writeJsonResponse(Response response, DbSession session, ComponentDto component, Request request) {
     try (JsonWriter json = response.newJsonWriter()) {
       json.beginObject();
-      componentViewerJsonWriter.writeComponent(json, component, userSession, session);
+      componentViewerJsonWriter.writeComponent(json, component, userSession, session, request.param(PARAM_BRANCH),
+        request.param(PARAM_PULL_REQUEST));
       appendPermissions(json, userSession);
       componentViewerJsonWriter.writeMeasures(json, component, session);
       json.endObject();
index 2af10c6671269d3faaaacb42d810d66f4f4728bc..5c3120d2c559d2997447763abdf3b480af90db59 100644 (file)
@@ -66,13 +66,13 @@ class ComponentDtoToWsComponent {
   }
 
   public static Components.Component.Builder componentDtoToWsComponent(ComponentDto dto, @Nullable ProjectDto parentProjectDto,
-    @Nullable SnapshotDto lastAnalysis) {
+    @Nullable SnapshotDto lastAnalysis, @Nullable String branch, @Nullable String pullRequest) {
     Components.Component.Builder wsComponent = Components.Component.newBuilder()
       .setKey(dto.getKey())
       .setName(dto.name())
       .setQualifier(dto.qualifier());
-    ofNullable(emptyToNull(dto.getBranch())).ifPresent(wsComponent::setBranch);
-    ofNullable(emptyToNull(dto.getPullRequest())).ifPresent(wsComponent::setPullRequest);
+    ofNullable(emptyToNull(branch)).ifPresent(wsComponent::setBranch);
+    ofNullable(emptyToNull(pullRequest)).ifPresent(wsComponent::setPullRequest);
     ofNullable(emptyToNull(dto.path())).ifPresent(wsComponent::setPath);
     ofNullable(emptyToNull(dto.description())).ifPresent(wsComponent::setDescription);
     ofNullable(emptyToNull(dto.language())).ifPresent(wsComponent::setLanguage);
index dd3cc2629b0acbe5eed01c7fdd0deda18acf3a15..95a95cad00c5c3123b151b8d530f8a278c7e9dbe 100644 (file)
@@ -62,7 +62,7 @@ public class ComponentViewerJsonWriter {
     this.dbClient = dbClient;
   }
 
-  public void writeComponentWithoutFav(JsonWriter json, ComponentDto component, DbSession session) {
+  public void writeComponentWithoutFav(JsonWriter json, ComponentDto component, DbSession session, @Nullable String branch, @Nullable String pullRequest) {
     json.prop("key", component.getKey());
     json.prop("uuid", component.uuid());
     json.prop("path", component.path());
@@ -74,18 +74,17 @@ public class ComponentViewerJsonWriter {
 
     json.prop("project", project.getKey());
     json.prop("projectName", project.longName());
-    String branch = project.getBranch();
     if (branch != null) {
       json.prop("branch", branch);
     }
-    String pullRequest = project.getPullRequest();
     if (pullRequest != null) {
       json.prop("pullRequest", pullRequest);
     }
   }
 
-  public void writeComponent(JsonWriter json, ComponentDto component, UserSession userSession, DbSession session) {
-    writeComponentWithoutFav(json, component, session);
+  public void writeComponent(JsonWriter json, ComponentDto component, UserSession userSession, DbSession session, @Nullable String branch,
+    @Nullable String pullRequest) {
+    writeComponentWithoutFav(json, component, session, branch, pullRequest);
 
     List<PropertyDto> propertyDtos = dbClient.propertiesDao().selectByQuery(PropertyQuery.builder()
       .setKey("favourite")
index 86f340835e058692015bc12b2cfcb6e38eb20334..a4e4746278ba41b417cdca352d5a54edb093b7da 100644 (file)
@@ -112,7 +112,7 @@ public class ShowAction implements ComponentsWsAction {
       userSession.checkComponentPermission(UserRole.USER, component);
       Optional<SnapshotDto> lastAnalysis = dbClient.snapshotDao().selectLastAnalysisByComponentUuid(dbSession, component.branchUuid());
       List<ComponentDto> ancestors = dbClient.componentDao().selectAncestors(dbSession, component);
-      return buildResponse(dbSession, component, ancestors, lastAnalysis.orElse(null));
+      return buildResponse(dbSession, component, ancestors, lastAnalysis.orElse(null), request);
     }
   }
 
@@ -125,22 +125,23 @@ public class ShowAction implements ComponentsWsAction {
   }
 
   private ShowWsResponse buildResponse(DbSession dbSession, ComponentDto component, List<ComponentDto> orderedAncestors,
-    @Nullable SnapshotDto lastAnalysis) {
+    @Nullable SnapshotDto lastAnalysis, Request request) {
     ShowWsResponse.Builder response = ShowWsResponse.newBuilder();
-    response.setComponent(toWsComponent(dbSession, component, lastAnalysis));
-    addAncestorsToResponse(dbSession, response, orderedAncestors, lastAnalysis);
+    response.setComponent(toWsComponent(dbSession, component, lastAnalysis, request));
+    addAncestorsToResponse(dbSession, response, orderedAncestors, lastAnalysis, request);
     return response.build();
   }
 
   private void addAncestorsToResponse(DbSession dbSession, ShowWsResponse.Builder response, List<ComponentDto> orderedAncestors,
-    @Nullable SnapshotDto lastAnalysis) {
+    @Nullable SnapshotDto lastAnalysis, Request request) {
     // ancestors are ordered from root to leaf, whereas it's the opposite in WS response
     int size = orderedAncestors.size() - 1;
     IntStream.rangeClosed(0, size).forEach(
-      index -> response.addAncestors(toWsComponent(dbSession, orderedAncestors.get(size - index), lastAnalysis)));
+      index -> response.addAncestors(toWsComponent(dbSession, orderedAncestors.get(size - index), lastAnalysis, request)));
   }
 
-  private Components.Component.Builder toWsComponent(DbSession dbSession, ComponentDto component, @Nullable SnapshotDto lastAnalysis) {
+  private Components.Component.Builder toWsComponent(DbSession dbSession, ComponentDto component, @Nullable SnapshotDto lastAnalysis,
+    Request request) {
     if (isProjectOrApp(component)) {
       ProjectDto project = dbClient.projectDao().selectProjectOrAppByKey(dbSession, component.getKey())
         .orElseThrow(() -> new IllegalStateException("Project is in invalid state."));
@@ -151,7 +152,7 @@ public class ShowAction implements ComponentsWsAction {
       Optional<ProjectDto> parentProject = dbClient.projectDao().selectByUuid(dbSession,
         ofNullable(component.getMainBranchProjectUuid()).orElse(component.branchUuid()));
       boolean needIssueSync = needIssueSync(dbSession, component, parentProject.orElse(null));
-      return componentDtoToWsComponent(component, parentProject.orElse(null), lastAnalysis)
+      return componentDtoToWsComponent(component, parentProject.orElse(null), lastAnalysis, request.branch, request.pullRequest)
         .setNeedIssueSync(needIssueSync);
     }
   }
index 5fd5e5de2a1917a2da38484335659d15b5280dbf..246af12da7b61137c467df34f1c266eaf8573080 100644 (file)
@@ -184,9 +184,8 @@ public class TreeAction implements ComponentsWsAction {
       components = paginateComponents(components, treeRequest);
 
       Map<String, ComponentDto> referenceComponentsByUuid = searchReferenceComponentsByUuid(dbSession, components);
-
-      return buildResponse(dbSession, baseComponent, components, referenceComponentsByUuid,
-        Paging.forPageIndex(treeRequest.getPage()).withPageSize(treeRequest.getPageSize()).andTotal(total));
+      Paging paging = Paging.forPageIndex(treeRequest.getPage()).withPageSize(treeRequest.getPageSize()).andTotal(total);
+      return buildResponse(dbSession, baseComponent, components, referenceComponentsByUuid, paging, treeRequest);
     }
   }
 
@@ -219,7 +218,7 @@ public class TreeAction implements ComponentsWsAction {
   }
 
   private TreeWsResponse buildResponse(DbSession dbSession, ComponentDto baseComponent, List<ComponentDto> components,
-    Map<String, ComponentDto> referenceComponentsByUuid, Paging paging) {
+    Map<String, ComponentDto> referenceComponentsByUuid, Paging paging, Request request) {
     TreeWsResponse.Builder response = TreeWsResponse.newBuilder();
     response.getPagingBuilder()
       .setPageIndex(paging.pageIndex())
@@ -227,16 +226,16 @@ public class TreeAction implements ComponentsWsAction {
       .setTotal(paging.total())
       .build();
 
-    response.setBaseComponent(toWsComponent(dbSession, baseComponent, referenceComponentsByUuid));
+    response.setBaseComponent(toWsComponent(dbSession, baseComponent, referenceComponentsByUuid, request));
     for (ComponentDto dto : components) {
-      response.addComponents(toWsComponent(dbSession, dto, referenceComponentsByUuid));
+      response.addComponents(toWsComponent(dbSession, dto, referenceComponentsByUuid, request));
     }
 
     return response.build();
   }
 
   private Components.Component.Builder toWsComponent(DbSession dbSession, ComponentDto component,
-    Map<String, ComponentDto> referenceComponentsByUuid) {
+    Map<String, ComponentDto> referenceComponentsByUuid, Request request) {
 
     Components.Component.Builder wsComponent;
     if (component.getMainBranchProjectUuid() == null && component.isRootProject() &&
@@ -246,7 +245,7 @@ public class TreeAction implements ComponentsWsAction {
     } else {
       Optional<ProjectDto> parentProject = dbClient.projectDao().selectByUuid(dbSession,
         ofNullable(component.getMainBranchProjectUuid()).orElse(component.branchUuid()));
-      wsComponent = componentDtoToWsComponent(component, parentProject.orElse(null), null);
+      wsComponent = componentDtoToWsComponent(component, parentProject.orElse(null), null, request.branch, request.pullRequest);
     }
 
     ComponentDto referenceComponent = referenceComponentsByUuid.get(component.getCopyComponentUuid());
index 4369241197e0fe655daa2535b0abc988e9aacf6f..094f8fe49a60f575c034aac38e59bb0b12400572 100644 (file)
@@ -20,6 +20,7 @@
 package org.sonar.server.duplication.ws;
 
 import java.util.List;
+import java.util.Optional;
 import javax.annotation.CheckForNull;
 import org.sonar.api.measures.CoreMetrics;
 import org.sonar.api.server.ws.Change;
@@ -29,6 +30,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.measure.LiveMeasureDto;
 import org.sonar.server.component.ComponentFinder;
@@ -96,15 +98,24 @@ public class ShowAction implements DuplicationsWsAction {
   public void handle(Request request, Response response) {
     try (DbSession dbSession = dbClient.openSession(false)) {
       ComponentDto component = loadComponent(dbSession, request);
+      BranchDto branchDto = loadBranch(dbSession, component);
+      String branch = branchDto.isMain() ? null : branchDto.getBranchKey();
+      String pullRequest = branchDto.getPullRequestKey();
       userSession.checkComponentPermission(UserRole.CODEVIEWER, component);
       String duplications = findDataFromComponent(dbSession, component);
-      String branch = component.getBranch();
-      String pullRequest = component.getPullRequest();
       List<DuplicationsParser.Block> blocks = parser.parse(dbSession, component, branch, pullRequest, duplications);
       writeProtobuf(responseBuilder.build(dbSession, blocks, branch, pullRequest), request, response);
     }
   }
 
+  private BranchDto loadBranch(DbSession dbSession, ComponentDto component) {
+    Optional<BranchDto> branchDto = dbClient.branchDao().selectByUuid(dbSession, component.branchUuid());
+    if (branchDto.isEmpty()) {
+      throw new IllegalStateException("Could not find a branch for component with " + component.uuid());
+    }
+    return branchDto.get();
+  }
+
   private ComponentDto loadComponent(DbSession dbSession, Request request) {
     String key = request.mandatoryParam(PARAM_KEY);
     String branch = request.param(PARAM_BRANCH);
index 5c3490d17d0ec1f772228ca8f956d47176369f32..2171dfeabb02a914f6e2461228fa7d1d68b49192 100644 (file)
@@ -20,6 +20,7 @@
 package org.sonar.server.hotspot.ws;
 
 import javax.annotation.Nullable;
+import org.sonar.db.component.BranchDto;
 import org.sonar.db.component.ComponentDto;
 import org.sonarqube.ws.Hotspots;
 
@@ -31,7 +32,7 @@ public class HotspotWsResponseFormatter {
     // nothing to do here
   }
 
-  Hotspots.Component formatComponent(Hotspots.Component.Builder builder, ComponentDto component, @Nullable String branch, @Nullable String pr) {
+  Hotspots.Component formatComponent(Hotspots.Component.Builder builder, ComponentDto component, @Nullable String branch, @Nullable String pullRequest) {
     builder
       .clear()
       .setKey(component.getKey())
@@ -39,9 +40,16 @@ public class HotspotWsResponseFormatter {
       .setName(component.name())
       .setLongName(component.longName());
     ofNullable(branch).ifPresent(builder::setBranch);
-    ofNullable(pr).ifPresent(builder::setPullRequest);
+    ofNullable(pullRequest).ifPresent(builder::setPullRequest);
     ofNullable(component.path()).ifPresent(builder::setPath);
     return builder.build();
   }
 
+  Hotspots.Component formatComponent(Hotspots.Component.Builder builder, ComponentDto component, BranchDto branchDto) {
+    if (branchDto.isMain()) {
+      return formatComponent(builder, component, null, null);
+    }
+    return formatComponent(builder, component, branchDto.getBranchKey(), branchDto.getPullRequestKey());
+  }
+
 }
index b913d82127b89375d3e605617e53864f7a10577b..f30266a6636b350b6af4a2ce3726fcfa983d1b3f 100644 (file)
@@ -32,7 +32,6 @@ import java.util.Optional;
 import java.util.Set;
 import java.util.stream.Collectors;
 import java.util.stream.Stream;
-import javax.annotation.CheckForNull;
 import javax.annotation.Nullable;
 import org.apache.lucene.search.TotalHits;
 import org.elasticsearch.action.search.SearchResponse;
@@ -57,7 +56,6 @@ 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;
@@ -348,7 +346,7 @@ public class SearchAction implements HotspotsWsAction {
     List<IssueDto> hotspots = toIssueDtos(dbSession, issueKeys);
 
     Paging paging = forPageIndex(wsRequest.getPage()).withPageSize(wsRequest.getIndex()).andTotal((int) getTotalHits(result).value);
-    return new SearchResponseData(paging, hotspots, wsRequest.getBranch().orElse(null), wsRequest.getPullRequest().orElse(null));
+    return new SearchResponseData(paging, hotspots);
   }
 
   private static TotalHits getTotalHits(SearchResponse response) {
@@ -505,8 +503,7 @@ public class SearchAction implements HotspotsWsAction {
     Map<String, IssueQuery.PeriodStart> leakByProjects = snapshots
       .stream()
       .filter(s -> isNullOrEmpty(s.getPeriodMode()) || !s.getPeriodMode().equals(REFERENCE_BRANCH.name()))
-      .collect(uniqueIndex(SnapshotDto::getComponentUuid, s ->
-        new IssueQuery.PeriodStart(longToDate(s.getPeriodDate() == null ? now : s.getPeriodDate()), false)));
+      .collect(uniqueIndex(SnapshotDto::getComponentUuid, s -> new IssueQuery.PeriodStart(longToDate(s.getPeriodDate() == null ? now : s.getPeriodDate()), false)));
 
     builder.createdAfterByProjectUuids(leakByProjects);
     builder.newCodeOnReferenceByProjectUuids(newCodeReferenceByProjects);
@@ -527,7 +524,12 @@ public class SearchAction implements HotspotsWsAction {
       .collect(Collectors.toSet());
 
     if (!aggregatedComponentUuids.isEmpty()) {
-      searchResponseData.addComponents(dbClient.componentDao().selectByUuids(dbSession, aggregatedComponentUuids));
+      List<ComponentDto> componentDtos = dbClient.componentDao().selectByUuids(dbSession, aggregatedComponentUuids);
+      searchResponseData.addComponents(componentDtos);
+
+      Set<String> branchUuids = componentDtos.stream().map(ComponentDto::branchUuid).collect(Collectors.toSet());
+      List<BranchDto> branchDtos = dbClient.branchDao().selectByUuids(dbSession, branchUuids);
+      searchResponseData.addBranches(branchDtos);
     }
   }
 
@@ -636,7 +638,11 @@ public class SearchAction implements HotspotsWsAction {
 
     Hotspots.Component.Builder builder = Hotspots.Component.newBuilder();
     for (ComponentDto component : components) {
-      responseBuilder.addComponents(responseFormatter.formatComponent(builder, component, searchResponseData.getBranch(), searchResponseData.getPullRequest()));
+      BranchDto branchDto = searchResponseData.getBranch(component.branchUuid());
+      if (branchDto == null) {
+        throw new IllegalStateException("Could not find a branch for a component " + component.getKey() + " with uuid " + component.uuid());
+      }
+      responseBuilder.addComponents(responseFormatter.formatComponent(builder, component, branchDto));
     }
   }
 
@@ -774,26 +780,13 @@ public class SearchAction implements HotspotsWsAction {
   private static final class SearchResponseData {
     private final Paging paging;
     private final List<IssueDto> orderedHotspots;
-    private final String branch;
-    private final String pullRequest;
     private final Map<String, ComponentDto> componentsByUuid = new HashMap<>();
     private final Map<RuleKey, RuleDto> rulesByRuleKey = new HashMap<>();
+    private final Map<String, BranchDto> branchesByBranchUuid = new HashMap<>();
 
-    private SearchResponseData(Paging paging, List<IssueDto> orderedHotspots, @Nullable String branch, @Nullable String pullRequest) {
+    private SearchResponseData(Paging paging, List<IssueDto> orderedHotspots) {
       this.paging = paging;
       this.orderedHotspots = orderedHotspots;
-      this.branch = branch;
-      this.pullRequest = pullRequest;
-    }
-
-    @CheckForNull
-    public String getBranch() {
-      return branch;
-    }
-
-    @CheckForNull
-    public String getPullRequest() {
-      return pullRequest;
     }
 
     boolean isEmpty() {
@@ -814,6 +807,16 @@ public class SearchAction implements HotspotsWsAction {
       }
     }
 
+    public void addBranches(List<BranchDto> branchDtos) {
+      for (BranchDto branch : branchDtos) {
+        branchesByBranchUuid.put(branch.getUuid(), branch);
+      }
+    }
+
+    public BranchDto getBranch(String branchUuid) {
+      return branchesByBranchUuid.get(branchUuid);
+    }
+
     Collection<ComponentDto> getComponents() {
       return componentsByUuid.values();
     }
index 3b4ab79c2db3205b7096aa7f93200c910e66c0d7..335aca838a5b860a05570369a3a443c35d8163da 100644 (file)
@@ -30,6 +30,7 @@ import java.util.Map;
 import java.util.Set;
 import javax.annotation.CheckForNull;
 import javax.annotation.Nullable;
+import org.sonar.db.component.BranchDto;
 import org.sonar.db.component.ComponentDto;
 import org.sonar.db.issue.IssueChangeDto;
 import org.sonar.db.issue.IssueDto;
@@ -53,6 +54,7 @@ public class SearchResponseData {
   private final ListMultimap<String, String> actionsByIssueKey = ArrayListMultimap.create();
   private final ListMultimap<String, Transition> transitionsByIssueKey = ArrayListMultimap.create();
   private final Set<String> updatableComments = new HashSet<>();
+  private final Map<String, BranchDto> branchesByBranchUuid = new HashMap<>();
 
   public SearchResponseData(IssueDto issue) {
     checkNotNull(issue);
@@ -139,6 +141,16 @@ public class SearchResponseData {
     }
   }
 
+  public void addBranches(List<BranchDto> branchDtos) {
+    for (BranchDto branch : branchDtos) {
+      branchesByBranchUuid.put(branch.getUuid(), branch);
+    }
+  }
+
+  public BranchDto getBranch(String branchUuid) {
+    return branchesByBranchUuid.get(branchUuid);
+  }
+
   void addActions(String issueKey, Iterable<String> actions) {
     actionsByIssueKey.putAll(issueKey, actions);
   }
index f62a2077ecb48e2b26a24b9a9820f342f7c61028..702f183ffafbb0ed4d854251ca1e0495ae650497 100644 (file)
@@ -35,6 +35,8 @@ import org.sonar.api.utils.DateUtils;
 import org.sonar.api.utils.Duration;
 import org.sonar.api.utils.Durations;
 import org.sonar.api.utils.Paging;
+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;
@@ -161,8 +163,7 @@ public class SearchResponseFormat {
 
     ComponentDto component = data.getComponentByUuid(dto.getComponentUuid());
     issueBuilder.setComponent(component.getKey());
-    ofNullable(component.getBranch()).ifPresent(issueBuilder::setBranch);
-    ofNullable(component.getPullRequest()).ifPresent(issueBuilder::setPullRequest);
+    setBranchOrPr(component, issueBuilder, data);
     ComponentDto project = data.getComponentByUuid(dto.getProjectUuid());
     if (project != null) {
       issueBuilder.setProject(project.getKey());
@@ -306,8 +307,7 @@ public class SearchResponseFormat {
         .setName(nullToEmpty(dto.name()))
         .setLongName(nullToEmpty(dto.longName()))
         .setEnabled(dto.isEnabled());
-      ofNullable(dto.getBranch()).ifPresent(builder::setBranch);
-      ofNullable(dto.getPullRequest()).ifPresent(builder::setPullRequest);
+      setBranchOrPr(dto, builder, data);
       ofNullable(emptyToNull(dto.path())).ifPresent(builder::setPath);
 
       result.add(builder.build());
@@ -315,6 +315,27 @@ public class SearchResponseFormat {
     return result;
   }
 
+  private static void setBranchOrPr(ComponentDto componentDto, Component.Builder builder, SearchResponseData data) {
+    BranchDto branchDto = data.getBranch(componentDto.branchUuid());
+    if (branchDto.isMain()) {
+      return;
+    }
+    builder.setBranch(branchDto.getBranchKey());
+    builder.setPullRequest(branchDto.getPullRequestKey());
+  }
+
+  private static void setBranchOrPr(ComponentDto componentDto, Issue.Builder builder, SearchResponseData data) {
+    BranchDto branchDto = data.getBranch(componentDto.branchUuid());
+    if (branchDto.isMain()) {
+      return;
+    }
+    if (branchDto.getBranchType() == BranchType.BRANCH) {
+      builder.setBranch(branchDto.getKey());
+    } else if (branchDto.getBranchType() == BranchType.PULL_REQUEST) {
+      builder.setPullRequest(branchDto.getKey());
+    }
+  }
+
   private Users.Builder formatUsers(SearchResponseData data) {
     Users.Builder wsUsers = Users.newBuilder();
     List<UserDto> users = data.getUsers();
index 3eab766fcd1eb1ea4b5562dba6c8efa986a42558..953ec69799c209ca7e2343b222cb078795cbe346 100644 (file)
@@ -37,6 +37,7 @@ import org.sonar.core.issue.DefaultIssue;
 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.issue.IssueChangeDto;
 import org.sonar.db.issue.IssueDto;
@@ -98,6 +99,9 @@ public class SearchResponseLoader {
       loadComments(collector, dbSession, fields, result);
       loadUsers(preloadedResponseData, collector, dbSession, result);
       loadComponents(preloadedResponseData, collector, dbSession, result);
+      // for all loaded components in result we "join" branches to know to which branch components belong
+      loadBranches(dbSession, result);
+
       loadActionsAndTransitions(result, fields);
       completeTotalEffortFromFacet(facets, result);
       return result;
@@ -150,6 +154,12 @@ public class SearchResponseLoader {
     loadProjects(collector, dbSession, result);
   }
 
+  private void loadBranches(DbSession dbSession, SearchResponseData result) {
+    Set<String> branchUuids = result.getComponents().stream().map(ComponentDto::branchUuid).collect(Collectors.toSet());
+    List<BranchDto> branchDtos = dbClient.branchDao().selectByUuids(dbSession, branchUuids);
+    result.addBranches(branchDtos);
+  }
+
   private void loadProjects(Collector collector, DbSession dbSession, SearchResponseData result) {
     Collection<ComponentDto> loadedComponents = result.getComponents();
     for (ComponentDto component : loadedComponents) {
index da046ad021161f68544397e4d05c16a7d93620c4..b645521e72da66ab5c6e73567852d38a681b6733 100644 (file)
@@ -245,9 +245,10 @@ public class ComponentAction implements MeasuresWsAction {
     ComponentWsResponse.Builder response = ComponentWsResponse.newBuilder();
 
     if (refComponent.isPresent()) {
-      response.setComponent(componentDtoToWsComponent(component, measuresByMetric, singletonMap(refComponent.get().uuid(), refComponent.get())));
+      response.setComponent(componentDtoToWsComponent(component, measuresByMetric, singletonMap(refComponent.get().uuid(),
+        refComponent.get()), request.getBranch(), request.getPullRequest()));
     } else {
-      response.setComponent(componentDtoToWsComponent(component, measuresByMetric, emptyMap()));
+      response.setComponent(componentDtoToWsComponent(component, measuresByMetric, emptyMap(), request.getBranch(), request.getPullRequest()));
     }
 
     List<String> additionalFields = request.getAdditionalFields();
index 77ee6758c950f0db29210a88ec6bb751c93473cf..51f079449404de9365367555400c89905929422a 100644 (file)
@@ -20,6 +20,7 @@
 package org.sonar.server.measure.ws;
 
 import java.util.Map;
+import javax.annotation.Nullable;
 import org.sonar.db.component.ComponentDto;
 import org.sonar.db.measure.LiveMeasureDto;
 import org.sonar.db.metric.MetricDto;
@@ -34,8 +35,9 @@ class ComponentDtoToWsComponent {
   }
 
   static Component.Builder componentDtoToWsComponent(ComponentDto component, Map<MetricDto, LiveMeasureDto> measuresByMetric,
-                                                     Map<String, ComponentDto> referenceComponentsByUuid) {
-    Component.Builder wsComponent = componentDtoToWsComponent(component);
+                                                     Map<String, ComponentDto> referenceComponentsByUuid, @Nullable String branch,
+                                                     @Nullable String pullRequest) {
+    Component.Builder wsComponent = componentDtoToWsComponent(component, branch, pullRequest);
 
     ComponentDto referenceComponent = referenceComponentsByUuid.get(component.getCopyComponentUuid());
     if (referenceComponent != null) {
@@ -52,13 +54,13 @@ class ComponentDtoToWsComponent {
     return wsComponent;
   }
 
-  static Component.Builder componentDtoToWsComponent(ComponentDto component) {
+  static Component.Builder componentDtoToWsComponent(ComponentDto component, @Nullable String branch, @Nullable String pullRequest) {
     Component.Builder wsComponent = Component.newBuilder()
       .setKey(component.getKey())
       .setName(component.name())
       .setQualifier(component.qualifier());
-    ofNullable(component.getBranch()).ifPresent(wsComponent::setBranch);
-    ofNullable(component.getPullRequest()).ifPresent(wsComponent::setPullRequest);
+    ofNullable(branch).ifPresent(wsComponent::setBranch);
+    ofNullable(pullRequest).ifPresent(wsComponent::setPullRequest);
     ofNullable(component.path()).ifPresent(wsComponent::setPath);
     ofNullable(component.description()).ifPresent(wsComponent::setDescription);
     ofNullable(component.language()).ifPresent(wsComponent::setLanguage);
index 64f179e535037745a026140779288ae937b692c7..03a61ca8782f7f35ffc2bee61845e716588c1d20 100644 (file)
@@ -291,13 +291,13 @@ public class ComponentTreeAction implements MeasuresWsAction {
       toWsComponent(
         data.getBaseComponent(),
         data.getMeasuresByComponentUuidAndMetric().row(data.getBaseComponent().uuid()),
-        data.getReferenceComponentsByUuid()));
+        data.getReferenceComponentsByUuid(), request.getBranch(), request.getPullRequest()));
 
     for (ComponentDto componentDto : data.getComponents()) {
       response.addComponents(toWsComponent(
         componentDto,
         data.getMeasuresByComponentUuidAndMetric().row(componentDto.uuid()),
-        data.getReferenceComponentsByUuid()));
+        data.getReferenceComponentsByUuid(), request.getBranch(), request.getPullRequest()));
     }
 
     if (areMetricsInResponse(request)) {
@@ -332,7 +332,7 @@ public class ComponentTreeAction implements MeasuresWsAction {
       .setPageSize(request.getPageSize())
       .setTotal(0);
     if (baseComponent != null) {
-      response.setBaseComponent(componentDtoToWsComponent(baseComponent));
+      response.setBaseComponent(componentDtoToWsComponent(baseComponent, request.getBranch(), request.getPullRequest()));
     }
     return response.build();
   }
@@ -373,8 +373,8 @@ public class ComponentTreeAction implements MeasuresWsAction {
   }
 
   private static Measures.Component.Builder toWsComponent(ComponentDto component, Map<MetricDto, ComponentTreeData.Measure> measures,
-    Map<String, ComponentDto> referenceComponentsByUuid) {
-    Measures.Component.Builder wsComponent = componentDtoToWsComponent(component);
+    Map<String, ComponentDto> referenceComponentsByUuid, @Nullable String branch, @Nullable String pullRequest) {
+    Measures.Component.Builder wsComponent = componentDtoToWsComponent(component, branch, pullRequest);
     ComponentDto referenceComponent = referenceComponentsByUuid.get(component.getCopyComponentUuid());
     if (referenceComponent != null) {
       wsComponent.setRefKey(referenceComponent.getKey());
index d341ef6a1e4f75dadc8f864ff5a4c585f8fcd225..48dda725e2ee69d3baa71a7506771563901e1333 100644 (file)
@@ -34,6 +34,7 @@ import org.sonar.api.utils.text.JsonWriter;
 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.issue.IssueDto;
@@ -98,13 +99,19 @@ public class IssueSnippetsAction implements SourcesWsAction {
         Map<String, TreeSet<Integer>> linesPerComponent = getLinesPerComponent(componentUuid, locations);
         Map<String, ComponentDto> componentsByUuid = dbClient.componentDao().selectByUuids(dbSession, linesPerComponent.keySet())
           .stream().collect(Collectors.toMap(ComponentDto::uuid, c -> c));
+
+        Map<String, BranchDto> branches = dbClient.branchDao()
+          .selectByUuids(dbSession, componentsByUuid.keySet())
+          .stream()
+          .collect(Collectors.toMap(BranchDto::getUuid, b -> b));
+
         try (JsonWriter jsonWriter = response.newJsonWriter()) {
           jsonWriter.beginObject();
 
           for (Map.Entry<String, TreeSet<Integer>> e : linesPerComponent.entrySet()) {
             ComponentDto componentDto = componentsByUuid.get(e.getKey());
             if (componentDto != null) {
-              writeSnippet(dbSession, jsonWriter, componentDto, e.getValue());
+              writeSnippet(dbSession, jsonWriter, componentDto, e.getValue(), branches.get(componentDto.branchUuid()));
             }
           }
 
@@ -114,7 +121,7 @@ public class IssueSnippetsAction implements SourcesWsAction {
     }
   }
 
-  private void writeSnippet(DbSession dbSession, JsonWriter writer, ComponentDto fileDto, Set<Integer> lines) {
+  private void writeSnippet(DbSession dbSession, JsonWriter writer, ComponentDto fileDto, Set<Integer> lines, BranchDto branchDto) {
     Optional<Iterable<DbFileSources.Line>> lineSourcesOpt = sourceService.getLines(dbSession, fileDto.uuid(), lines);
     if (lineSourcesOpt.isEmpty()) {
       return;
@@ -129,7 +136,9 @@ public class IssueSnippetsAction implements SourcesWsAction {
     writer.name(fileDto.getKey()).beginObject();
 
     writer.name("component").beginObject();
-    componentViewerJsonWriter.writeComponentWithoutFav(writer, fileDto, dbSession);
+    String branch = branchDto.isMain() ? null : branchDto.getBranchKey();
+    String pullRequest = branchDto.getPullRequestKey();
+    componentViewerJsonWriter.writeComponentWithoutFav(writer, fileDto, dbSession, branch, pullRequest);
     componentViewerJsonWriter.writeMeasures(writer, fileDto, dbSession);
     writer.endObject();
     linesJsonWriter.writeSource(lineSources, writer, periodDateSupplier);
index 2af87ecd1bcc70a3c08e23c027ee55649a20657b..b1937071caaf7b6ee1a5fcdff88fe2c3a490152a 100644 (file)
@@ -23,6 +23,7 @@ import java.util.Date;
 import java.util.List;
 import java.util.stream.IntStream;
 import javax.annotation.Nullable;
+import org.apache.commons.lang.RandomStringUtils;
 import org.junit.Rule;
 import org.junit.Test;
 import org.sonar.api.server.ws.WebService.Param;
@@ -458,10 +459,11 @@ public class ActivityActionTest {
     logInAsSystemAdministrator();
     ComponentDto project = db.components().insertPrivateProject();
     userSession.addProjectPermission(UserRole.USER, project);
-    ComponentDto pullRequest = db.components().insertProjectBranch(project, b -> b.setBranchType(BranchType.PULL_REQUEST));
+    String pullRequestKey = RandomStringUtils.randomAlphanumeric(100);
+    ComponentDto pullRequest = db.components().insertProjectBranch(project, b -> b.setBranchType(BranchType.PULL_REQUEST).setKey(pullRequestKey));
     SnapshotDto analysis = db.components().insertSnapshot(pullRequest);
     CeActivityDto activity = insertActivity("T1", project, SUCCESS, analysis);
-    insertCharacteristic(activity, PULL_REQUEST, pullRequest.getPullRequest());
+    insertCharacteristic(activity, PULL_REQUEST, pullRequestKey);
 
     ActivityResponse response = ws.newRequest().executeProtobuf(ActivityResponse.class);
 
@@ -469,7 +471,7 @@ public class ActivityActionTest {
       .extracting(Task::getId, Ce.Task::getPullRequest, Ce.Task::hasPullRequestTitle, Ce.Task::getStatus, Ce.Task::getComponentKey)
       .containsExactlyInAnyOrder(
         // TODO the pull request title must be loaded from db
-        tuple("T1", pullRequest.getPullRequest(), false, Ce.TaskStatus.SUCCESS, pullRequest.getKey()));
+        tuple("T1", pullRequestKey, false, Ce.TaskStatus.SUCCESS, pullRequest.getKey()));
   }
 
   @Test
index 2b7e5c30c4280a0942bf5c8342da2ca4ed66543b..24786cb54af4237980d031c72859609b4298da44 100644 (file)
@@ -19,6 +19,7 @@
  */
 package org.sonar.server.component.ws;
 
+import org.apache.commons.lang.RandomStringUtils;
 import org.junit.Rule;
 import org.junit.Test;
 import org.sonar.api.server.ws.WebService;
@@ -324,12 +325,13 @@ public class AppActionTest {
   public void component_and_pull_request_parameters_provided() {
     ComponentDto project = db.components().insertPrivateProject();
     userSession.logIn("john").addProjectPermission(USER, project);
-    ComponentDto branch = db.components().insertProjectBranch(project, b -> b.setBranchType(PULL_REQUEST));
+    String pullRequestKey = RandomStringUtils.randomAlphanumeric(100);
+    ComponentDto branch = db.components().insertProjectBranch(project, b -> b.setBranchType(PULL_REQUEST).setKey(pullRequestKey));
     ComponentDto file = db.components().insertComponent(newFileDto(branch));
 
     String result = ws.newRequest()
       .setParam("component", file.getKey())
-      .setParam("pullRequest", file.getPullRequest())
+      .setParam("pullRequest", pullRequestKey)
       .execute()
       .getInput();
 
@@ -342,7 +344,7 @@ public class AppActionTest {
       "  \"q\": \"" + file.qualifier() + "\",\n" +
       "  \"project\": \"" + project.getKey() + "\",\n" +
       "  \"projectName\": \"" + project.longName() + "\",\n" +
-      "  \"pullRequest\": \"" + file.getPullRequest() + "\",\n" +
+      "  \"pullRequest\": \"" + pullRequestKey + "\",\n" +
       "  \"fav\": false,\n" +
       "  \"canMarkAsFavorite\": true,\n" +
       "  \"measures\": {}\n" +
index 6603f2a01971671ffedf1efc4a0b79aa553a0185..61720cbfaeaffe55b90c9b30ad76d170ff393dee 100644 (file)
@@ -22,6 +22,7 @@ package org.sonar.server.component.ws;
 import java.util.Date;
 import java.util.Optional;
 import javax.annotation.Nullable;
+import org.apache.commons.lang.RandomStringUtils;
 import org.junit.Rule;
 import org.junit.Test;
 import org.sonar.api.resources.Qualifiers;
@@ -315,8 +316,10 @@ public class ShowActionTest {
     ComponentDto portfolio2 = db.components().insertPublicPortfolio();
     ComponentDto subview = db.components().insertSubView(portfolio1);
 
+    String pullRequestKey1 = RandomStringUtils.randomAlphanumeric(100);
     ComponentDto project1 = db.components().insertPrivateProject();
-    ComponentDto branch1 = db.components().insertProjectBranch(project1, b -> b.setBranchType(PULL_REQUEST).setNeedIssueSync(true));
+    ComponentDto branch1 = db.components().insertProjectBranch(project1, b -> b.setBranchType(PULL_REQUEST).setKey(pullRequestKey1)
+      .setNeedIssueSync(true));
     ComponentDto module = db.components().insertComponent(newModuleDto(branch1));
     ComponentDto directory = db.components().insertComponent(newDirectory(module, "dir"));
     ComponentDto file = db.components().insertComponent(newFileDto(directory));
@@ -326,7 +329,8 @@ public class ShowActionTest {
     ComponentDto branch3 = db.components().insertProjectBranch(project2, b -> b.setBranchType(BRANCH).setNeedIssueSync(false));
 
     ComponentDto project3 = db.components().insertPrivateProject();
-    ComponentDto branch4 = db.components().insertProjectBranch(project3, b -> b.setBranchType(PULL_REQUEST).setNeedIssueSync(false));
+    String pullRequestKey4 = RandomStringUtils.randomAlphanumeric(100);
+    ComponentDto branch4 = db.components().insertProjectBranch(project3, b -> b.setBranchType(PULL_REQUEST).setKey(pullRequestKey4).setNeedIssueSync(false));
     ComponentDto moduleOfBranch4 = db.components().insertComponent(newModuleDto(branch4));
     ComponentDto directoryOfBranch4 = db.components().insertComponent(newDirectory(moduleOfBranch4, "dir"));
     ComponentDto fileOfBranch4 = db.components().insertComponent(newFileDto(directoryOfBranch4));
@@ -342,10 +346,10 @@ public class ShowActionTest {
 
     // if branch need sync it is propagated to other components
     assertNeedIssueSyncEqual(null, null, project1, true);
-    assertNeedIssueSyncEqual(branch1.getPullRequest(), null, branch1, true);
-    assertNeedIssueSyncEqual(branch1.getPullRequest(), null, module, true);
-    assertNeedIssueSyncEqual(branch1.getPullRequest(), null, directory, true);
-    assertNeedIssueSyncEqual(branch1.getPullRequest(), null, file, true);
+    assertNeedIssueSyncEqual(pullRequestKey1, null, branch1, true);
+    assertNeedIssueSyncEqual(pullRequestKey1, null, module, true);
+    assertNeedIssueSyncEqual(pullRequestKey1, null, directory, true);
+    assertNeedIssueSyncEqual(pullRequestKey1, null, file, true);
 
     assertNeedIssueSyncEqual(null, null, project2, true);
     assertNeedIssueSyncEqual(null, branch2.getBranch(), branch2, true);
@@ -353,10 +357,10 @@ public class ShowActionTest {
 
     // if all branches are synced, need issue sync on project is is set to false
     assertNeedIssueSyncEqual(null, null, project3, false);
-    assertNeedIssueSyncEqual(branch4.getPullRequest(), null, branch4, false);
-    assertNeedIssueSyncEqual(branch4.getPullRequest(), null, moduleOfBranch4, false);
-    assertNeedIssueSyncEqual(branch4.getPullRequest(), null, directoryOfBranch4, false);
-    assertNeedIssueSyncEqual(branch4.getPullRequest(), null, fileOfBranch4, false);
+    assertNeedIssueSyncEqual(pullRequestKey4, null, branch4, false);
+    assertNeedIssueSyncEqual(pullRequestKey4, null, moduleOfBranch4, false);
+    assertNeedIssueSyncEqual(pullRequestKey4, null, directoryOfBranch4, false);
+    assertNeedIssueSyncEqual(pullRequestKey4, null, fileOfBranch4, false);
     assertNeedIssueSyncEqual(null, branch5.getBranch(), branch5, false);
   }
 
index 0aa1331da6b7e030bb9cd690fadfbc72cb8bc675..7314720e63cd1249c1b726df2d8a2d23ea3b9712 100644 (file)
@@ -211,7 +211,8 @@ public class SearchEventsActionNewIssuesTest {
     SnapshotDto nonMainBranchAnalysis = insertAnalysis(nonMainBranch, 1_500_000_000_000L);
     insertIssue(nonMainBranch, nonMainBranchAnalysis);
     insertIssue(nonMainBranch, nonMainBranchAnalysis);
-    ComponentDto pullRequest = db.components().insertProjectBranch(project, b -> b.setBranchType(BranchType.PULL_REQUEST).setKey("42"));
+    String pullRequestKey = "42";
+    ComponentDto pullRequest = db.components().insertProjectBranch(project, b -> b.setBranchType(BranchType.PULL_REQUEST).setKey(pullRequestKey));
     SnapshotDto pullRequestAnalysis = insertAnalysis(pullRequest, 1_300_000_000_000L);
     insertIssue(pullRequest, pullRequestAnalysis);
     issueIndexer.indexAllIssues();
@@ -229,10 +230,10 @@ public class SearchEventsActionNewIssuesTest {
           format("https://sonarcloud.io/project/issues?id=%s&createdAfter=%s&assignees=%s&resolved=false&branch=%s", nonMainBranch.getKey(), encode(formatDateTime(from + 1_000L)),
             userSession.getLogin(), nonMainBranch.getBranch()),
           formatDateTime(nonMainBranchAnalysis.getCreatedAt())),
-        tuple("NEW_ISSUES", project.getKey(), format("You have 1 new issue on project '%s' on pull request '%s'", project.name(), pullRequest.getPullRequest()),
+        tuple("NEW_ISSUES", project.getKey(), format("You have 1 new issue on project '%s' on pull request '%s'", project.name(), pullRequestKey),
           format("https://sonarcloud.io/project/issues?id=%s&createdAfter=%s&assignees=%s&resolved=false&pullRequest=%s", pullRequest.getKey(),
             encode(formatDateTime(from + 1_000L)),
-            userSession.getLogin(), pullRequest.getPullRequest()),
+            userSession.getLogin(), pullRequestKey),
           formatDateTime(pullRequestAnalysis.getCreatedAt())));
   }
 
index 629d0ca0e12f302fa3264efda74e1685e6b61d48..a5160407b37f6e77964b16e5fc7eeb1bfed0d34b 100644 (file)
@@ -22,6 +22,7 @@ package org.sonar.server.duplication.ws;
 import com.google.common.collect.Iterables;
 import java.util.List;
 import javax.annotation.Nullable;
+import org.apache.commons.lang.RandomStringUtils;
 import org.junit.Rule;
 import org.junit.Test;
 import org.sonar.db.DbTester;
@@ -279,10 +280,11 @@ public class DuplicationsParserTest {
   @Test
   public void duplication_on_pull_request() {
     ComponentDto project = db.components().insertPublicProject();
-    ComponentDto pullRequest = db.components().insertProjectBranch(project, b -> b.setBranchType(BranchType.PULL_REQUEST));
+    String pullRequestKey = RandomStringUtils.randomAlphanumeric(100);
+    ComponentDto pullRequest = db.components().insertProjectBranch(project, b -> b.setBranchType(BranchType.PULL_REQUEST).setKey(pullRequestKey));
     ComponentDto file1 = db.components().insertComponent(newFileDto(pullRequest));
     ComponentDto file2 = db.components().insertComponent(newFileDto(pullRequest));
-    List<DuplicationsParser.Block> blocks = parser.parse(db.getSession(), file1, null, pullRequest.getPullRequest(),
+    List<DuplicationsParser.Block> blocks = parser.parse(db.getSession(), file1, null, pullRequestKey,
       format("<duplications>\n" +
         "  <g>\n" +
         "    <b s=\"20\" l=\"5\" r=\"%s\"/>\n" +
index ccfcd558cd250f763c93745884e4605e9e7f4d74..a48bf77e94c4435262eb4cd9d06bf6613977c7af 100644 (file)
@@ -20,6 +20,7 @@
 package org.sonar.server.duplication.ws;
 
 import java.util.function.Function;
+import org.apache.commons.lang.RandomStringUtils;
 import org.junit.Before;
 import org.junit.Rule;
 import org.junit.Test;
@@ -28,7 +29,6 @@ import org.sonar.api.server.ws.WebService;
 import org.sonar.api.web.UserRole;
 import org.sonar.core.util.Uuids;
 import org.sonar.db.DbTester;
-import org.sonar.db.component.BranchType;
 import org.sonar.db.component.ComponentDto;
 import org.sonar.db.metric.MetricDto;
 import org.sonar.server.component.TestComponentFinder;
@@ -43,6 +43,7 @@ import org.sonar.server.ws.WsActionTester;
 import static java.lang.String.format;
 import static org.assertj.core.api.Assertions.assertThat;
 import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.sonar.db.component.BranchType.PULL_REQUEST;
 import static org.sonar.db.component.ComponentTesting.newFileDto;
 import static org.sonar.db.component.SnapshotTesting.newAnalysis;
 import static org.sonar.test.JsonAssert.assertJson;
@@ -157,7 +158,8 @@ public class ShowActionTest {
   public void duplications_by_file_key_and_pull_request() {
     ComponentDto project = db.components().insertPrivateProject();
     userSessionRule.addProjectPermission(UserRole.CODEVIEWER, project);
-    ComponentDto pullRequest = db.components().insertProjectBranch(project, b -> b.setBranchType(BranchType.PULL_REQUEST));
+    String pullRequestKey = RandomStringUtils.randomAlphanumeric(100);
+    ComponentDto pullRequest = db.components().insertProjectBranch(project, b -> b.setBranchType(PULL_REQUEST).setKey(pullRequestKey));
     ComponentDto file = db.components().insertComponent(newFileDto(pullRequest));
     db.measures().insertLiveMeasure(file, dataMetric, m -> m.setData(format("<duplications>\n" +
       "  <g>\n" +
@@ -168,7 +170,7 @@ public class ShowActionTest {
 
     String result = ws.newRequest()
       .setParam("key", file.getKey())
-      .setParam("pullRequest", pullRequest.getPullRequest())
+      .setParam("pullRequest", pullRequestKey)
       .execute()
       .getInput();
 
@@ -202,7 +204,7 @@ public class ShowActionTest {
           "    }\n" +
           "  }\n" +
           "}",
-        file.getKey(), file.longName(), file.uuid(), pullRequest.getKey(), pullRequest.uuid(), project.longName(), file.getPullRequest()));
+        file.getKey(), file.longName(), file.uuid(), pullRequest.getKey(), pullRequest.uuid(), project.longName(), pullRequestKey));
   }
 
   @Test
index 6d7454ee3d06317b9fb82acbf2b7bd9ccc20777d..d764b0f1fe011a9efa9cb0d918f1ae757a2bc0d6 100644 (file)
@@ -23,6 +23,7 @@ import java.io.StringWriter;
 import java.util.Collections;
 import java.util.List;
 import javax.annotation.Nullable;
+import org.apache.commons.lang.RandomStringUtils;
 import org.junit.Rule;
 import org.junit.Test;
 import org.sonar.api.utils.text.JsonWriter;
@@ -247,7 +248,8 @@ public class ShowResponseBuilderTest {
   @Test
   public void write_duplications_on_pull_request() {
     ComponentDto project = db.components().insertPublicProject();
-    ComponentDto pullRequest = db.components().insertProjectBranch(project, b -> b.setBranchType(PULL_REQUEST));
+    String pullRequestKey = RandomStringUtils.randomAlphanumeric(100);
+    ComponentDto pullRequest = db.components().insertProjectBranch(project, b -> b.setBranchType(PULL_REQUEST).setKey(pullRequestKey));
     ComponentDto file1 = db.components().insertComponent(newFileDto(pullRequest));
     ComponentDto file2 = db.components().insertComponent(newFileDto(pullRequest));
     List<DuplicationsParser.Block> blocks = newArrayList();
@@ -255,7 +257,7 @@ public class ShowResponseBuilderTest {
       Duplication.newComponent(file1, 57, 12),
       Duplication.newComponent(file2, 73, 12))));
 
-    test(blocks, null, pullRequest.getPullRequest(),
+    test(blocks, null, pullRequestKey,
       "{\n" +
         "  \"duplications\": [\n" +
         "    {\n" +
@@ -275,14 +277,14 @@ public class ShowResponseBuilderTest {
         "      \"name\": \"" + file1.longName() + "\",\n" +
         "      \"project\": \"" + pullRequest.getKey() + "\",\n" +
         "      \"projectName\": \"" + pullRequest.longName() + "\",\n" +
-        "      \"pullRequest\": \"" + pullRequest.getPullRequest() + "\",\n" +
+        "      \"pullRequest\": \"" + pullRequestKey + "\",\n" +
         "    },\n" +
         "    \"2\": {\n" +
         "      \"key\": \"" + file2.getKey() + "\",\n" +
         "      \"name\": \"" + file2.longName() + "\",\n" +
         "      \"project\": \"" + pullRequest.getKey() + "\",\n" +
         "      \"projectName\": \"" + pullRequest.longName() + "\",\n" +
-        "      \"pullRequest\": \"" + pullRequest.getPullRequest() + "\",\n" +
+        "      \"pullRequest\": \"" + pullRequestKey + "\",\n" +
         "    }\n" +
         "  }" +
         "}");
index 38b9cc4eb4127b76aa43bff546073cdde70c617a..8ac8fd6d910139887480871b679926b629e51b9e 100644 (file)
@@ -36,6 +36,7 @@ import java.util.function.Consumer;
 import java.util.stream.IntStream;
 import java.util.stream.Stream;
 import javax.annotation.Nullable;
+import org.apache.commons.lang.RandomStringUtils;
 import org.junit.Rule;
 import org.junit.Test;
 import org.junit.runner.RunWith;
@@ -684,7 +685,7 @@ public class SearchActionTest {
     userSessionRule.registerComponents(project);
     indexPermissions();
     ComponentDto branch = dbTester.components().insertProjectBranch(project);
-    ComponentDto pullRequest = dbTester.components().insertProjectBranch(project, t -> t.setBranchType(BranchType.PULL_REQUEST));
+    ComponentDto pullRequest = dbTester.components().insertProjectBranch(project, t -> t.setBranchType(BranchType.PULL_REQUEST).setKey("prKey"));
     ComponentDto fileProject = dbTester.components().insertComponent(newFileDto(project));
     ComponentDto fileBranch = dbTester.components().insertComponent(newFileDto(branch));
     ComponentDto filePR = dbTester.components().insertComponent(newFileDto(pullRequest));
@@ -712,7 +713,7 @@ public class SearchActionTest {
       .executeProtobuf(SearchWsResponse.class);
     SearchWsResponse responseBranch = newRequest(branch)
       .executeProtobuf(SearchWsResponse.class);
-    SearchWsResponse responsePR = newRequest(pullRequest)
+    SearchWsResponse responsePR = newRequest(pullRequest, res -> res.setParam(PARAM_PULL_REQUEST, "prKey"))
       .executeProtobuf(SearchWsResponse.class);
 
     assertThat(responseProject.getHotspotsList())
@@ -1121,7 +1122,9 @@ public class SearchActionTest {
   @Test
   public void returns_pullRequest_field_of_components_of_pullRequest() {
     ComponentDto project = dbTester.components().insertPublicProject();
-    ComponentDto pullRequest = dbTester.components().insertProjectBranch(project, t -> t.setBranchType(BranchType.PULL_REQUEST));
+    String pullRequestKey = RandomStringUtils.randomAlphanumeric(100);
+    ComponentDto pullRequest = dbTester.components().insertProjectBranch(project, t -> t.setBranchType(BranchType.PULL_REQUEST)
+      .setKey(pullRequestKey));
     userSessionRule.registerComponents(project, pullRequest);
     indexPermissions();
     ComponentDto directory = dbTester.components().insertComponent(newDirectory(pullRequest, "donut/acme"));
@@ -1132,7 +1135,7 @@ public class SearchActionTest {
     IssueDto projectHotspot = insertHotspot(pullRequest, pullRequest, rule);
     indexIssues();
 
-    SearchWsResponse response = newRequest(pullRequest)
+    SearchWsResponse response = newRequest(pullRequest, r -> r.setParam(PARAM_PULL_REQUEST, "pullRequestKey"))
       .executeProtobuf(SearchWsResponse.class);
 
     assertThat(response.getHotspotsList())
@@ -1144,13 +1147,13 @@ public class SearchActionTest {
     Map<String, Component> componentByKey = response.getComponentsList().stream().collect(uniqueIndex(Component::getKey));
     Component actualProject = componentByKey.get(project.getKey());
     assertThat(actualProject.hasBranch()).isFalse();
-    assertThat(actualProject.getPullRequest()).isEqualTo(pullRequest.getPullRequest());
+    assertThat(actualProject.getPullRequest()).isEqualTo(pullRequestKey);
     Component actualDirectory = componentByKey.get(directory.getKey());
     assertThat(actualDirectory.hasBranch()).isFalse();
-    assertThat(actualDirectory.getPullRequest()).isEqualTo(pullRequest.getPullRequest());
+    assertThat(actualDirectory.getPullRequest()).isEqualTo(pullRequestKey);
     Component actualFile = componentByKey.get(file.getKey());
     assertThat(actualFile.hasBranch()).isFalse();
-    assertThat(actualFile.getPullRequest()).isEqualTo(pullRequest.getPullRequest());
+    assertThat(actualFile.getPullRequest()).isEqualTo(pullRequestKey);
   }
 
   @Test
@@ -2035,10 +2038,6 @@ public class SearchActionTest {
     if (branch != null) {
       res.setParam(PARAM_BRANCH, branch);
     }
-    String pullRequest = project.getPullRequest();
-    if (pullRequest != null) {
-      res.setParam(PARAM_PULL_REQUEST, pullRequest);
-    }
     if (status != null) {
       res.setParam(PARAM_STATUS, status);
     }
index eef8d335517ea808114ccd0fca0e2c373a0aa66c..9e6d58a003de726c90318d70043c53b3834af538 100644 (file)
@@ -35,6 +35,7 @@ import java.util.stream.Collectors;
 import java.util.stream.IntStream;
 import java.util.stream.Stream;
 import javax.annotation.Nullable;
+import org.apache.commons.lang.RandomStringUtils;
 import org.assertj.core.groups.Tuple;
 import org.junit.Rule;
 import org.junit.Test;
@@ -930,8 +931,9 @@ public class ShowActionTest {
   @Test
   public void returns_pullRequest_but_no_branch_on_component_and_project_on_pullRequest() {
     ComponentDto project = dbTester.components().insertPublicProject();
+    String pullRequestKey = RandomStringUtils.randomAlphanumeric(100);
     ComponentDto pullRequest = dbTester.components().insertProjectBranch(project,
-      t -> t.setBranchType(BranchType.PULL_REQUEST));
+      t -> t.setBranchType(BranchType.PULL_REQUEST).setKey(pullRequestKey));
     ComponentDto file = dbTester.components().insertComponent(newFileDto(pullRequest));
     userSessionRule.registerComponents(project);
     RuleDto rule = newRule(SECURITY_HOTSPOT);
@@ -944,8 +946,8 @@ public class ShowActionTest {
     Hotspots.ShowWsResponse response = newRequest(hotspot)
       .executeProtobuf(Hotspots.ShowWsResponse.class);
 
-    verifyComponent(response.getProject(), pullRequest, null, pullRequest.getPullRequest());
-    verifyComponent(response.getComponent(), file, null, pullRequest.getPullRequest());
+    verifyComponent(response.getProject(), pullRequest, null, pullRequestKey);
+    verifyComponent(response.getComponent(), file, null, pullRequestKey);
   }
 
   @Test
index 26a262a21e028cd890e9fd2df38e15e0ebe1eead..acd829d61c5ab2566a848df641b4e45895058bfa 100644 (file)
@@ -22,6 +22,7 @@ package org.sonar.server.issue.ws;
 import java.time.Clock;
 import java.util.Arrays;
 import java.util.Date;
+import org.apache.commons.lang.RandomStringUtils;
 import org.junit.Rule;
 import org.junit.Test;
 import org.sonar.api.resources.Languages;
@@ -627,7 +628,9 @@ public class SearchActionComponentsTest {
     ComponentDto project = db.components().insertPrivateProject();
     ComponentDto projectFile = db.components().insertComponent(newFileDto(project));
     IssueDto projectIssue = db.issues().insertIssue(rule, project, projectFile);
-    ComponentDto pullRequest = db.components().insertProjectBranch(project, b -> b.setBranchType(PULL_REQUEST));
+
+    String pullRequestKey = RandomStringUtils.randomAlphanumeric(100);
+    ComponentDto pullRequest = db.components().insertProjectBranch(project, b -> b.setBranchType(PULL_REQUEST).setKey(pullRequestKey));
     ComponentDto pullRequestFile = db.components().insertComponent(newFileDto(pullRequest));
     IssueDto pullRequestIssue = db.issues().insertIssue(rule, pullRequest, pullRequestFile);
     allowAnyoneOnProjects(project);
@@ -635,17 +638,17 @@ public class SearchActionComponentsTest {
 
     SearchWsResponse result = ws.newRequest()
       .setParam(PARAM_COMPONENT_KEYS, pullRequest.getKey())
-      .setParam(PARAM_PULL_REQUEST, pullRequest.getPullRequest())
+      .setParam(PARAM_PULL_REQUEST, pullRequestKey)
       .executeProtobuf(SearchWsResponse.class);
 
     assertThat(result.getIssuesList())
       .extracting(Issue::getKey, Issue::getComponent, Issue::getPullRequest)
-      .containsExactlyInAnyOrder(tuple(pullRequestIssue.getKey(), pullRequestFile.getKey(), pullRequestFile.getPullRequest()));
+      .containsExactlyInAnyOrder(tuple(pullRequestIssue.getKey(), pullRequestFile.getKey(), pullRequestKey));
     assertThat(result.getComponentsList())
       .extracting(Issues.Component::getKey, Issues.Component::getPullRequest)
       .containsExactlyInAnyOrder(
-        tuple(pullRequestFile.getKey(), pullRequestFile.getPullRequest()),
-        tuple(pullRequest.getKey(), pullRequest.getPullRequest()));
+        tuple(pullRequestFile.getKey(), pullRequestKey),
+        tuple(pullRequest.getKey(), pullRequestKey));
   }
 
   @Test
index 6b98e7d82d8d8252a3870ec2a000ec20239f9902..cf185e9ed753c364c2a7bbde6e1713c7e5ff09c9 100644 (file)
@@ -176,11 +176,12 @@ public class SearchResponseFormatFormatOperationTest {
 
   @Test
   public void formatOperation_should_add_pullrequest_on_issue() {
-    componentDto.setKey(randomAlphanumeric(5) + PULL_REQUEST_SEPARATOR + randomAlphanumeric(5));
+    String pullRequestKey = randomAlphanumeric(5);
+    componentDto.setKey(randomAlphanumeric(5) + PULL_REQUEST_SEPARATOR + pullRequestKey);
 
     Operation result = searchResponseFormat.formatOperation(searchResponseData);
 
-    assertThat(result.getIssue().getPullRequest()).isEqualTo(componentDto.getPullRequest());
+    assertThat(result.getIssue().getPullRequest()).isEqualTo(pullRequestKey);
   }
 
   @Test
index a193ae44a12951628e0701de314679741859ded7..f3a8d13fe3627acc45b123f1d6d530d4543d9ce4 100644 (file)
@@ -22,6 +22,7 @@ package org.sonar.server.qualitygate.ws;
 import java.io.IOException;
 import java.nio.charset.StandardCharsets;
 import org.apache.commons.io.IOUtils;
+import org.apache.commons.lang.RandomStringUtils;
 import org.junit.Rule;
 import org.junit.Test;
 import org.sonar.api.measures.CoreMetrics;
@@ -238,7 +239,9 @@ public class ProjectStatusActionTest {
   @Test
   public void return_live_status_when_pull_request_is_referenced_by_its_key() throws IOException {
     ComponentDto project = db.components().insertPrivateProject();
-    ComponentDto pr = db.components().insertProjectBranch(project, branch -> branch.setBranchType(BranchType.PULL_REQUEST));
+    String pullRequestKey = RandomStringUtils.randomAlphanumeric(100);
+    ComponentDto pr = db.components().insertProjectBranch(project, branch -> branch.setBranchType(BranchType.PULL_REQUEST)
+      .setKey(pullRequestKey));
 
     dbClient.snapshotDao().insert(dbSession, newAnalysis(pr)
       .setPeriodMode("last_version")
@@ -253,7 +256,7 @@ public class ProjectStatusActionTest {
 
     String response = ws.newRequest()
       .setParam(PARAM_PROJECT_KEY, project.getKey())
-      .setParam(PARAM_PULL_REQUEST, pr.getPullRequest())
+      .setParam(PARAM_PULL_REQUEST, pullRequestKey)
       .execute().getInput();
 
     assertJson(response).isSimilarTo(getClass().getResource("project_status-example.json"));
index fbbf478225056ac743ee69bd4a6831d97c99abb7..1272acfd8cf535e89084510bc4b91731a1174171 100644 (file)
@@ -47,6 +47,7 @@ import org.sonar.server.ws.TestResponse;
 import org.sonar.server.ws.WsActionTester;
 
 import static java.lang.String.format;
+import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric;
 import static org.assertj.core.api.Assertions.assertThatThrownBy;
 import static org.mockito.ArgumentMatchers.anyString;
 import static org.mockito.Mockito.mock;
@@ -143,7 +144,8 @@ public class LinesActionTest {
   public void pull_request() {
     ComponentDto project = db.components().insertPrivateProject();
     userSession.addProjectPermission(UserRole.USER, project);
-    ComponentDto branch = db.components().insertProjectBranch(project, b -> b.setBranchType(PULL_REQUEST));
+    String pullRequestKey = randomAlphanumeric(100);
+    ComponentDto branch = db.components().insertProjectBranch(project, b -> b.setBranchType(PULL_REQUEST).setKey(pullRequestKey));
     ComponentDto file = db.components().insertComponent(newFileDto(branch));
     db.getDbClient().fileSourceDao().insert(db.getSession(), new FileSourceDto()
       .setUuid(Uuids.createFast())
@@ -157,7 +159,7 @@ public class LinesActionTest {
 
     tester.newRequest()
       .setParam("key", file.getKey())
-      .setParam("pullRequest", file.getPullRequest())
+      .setParam("pullRequest", pullRequestKey)
       .execute()
       .assertJson(getClass(), "show_source.json");
   }