@Test public void search_groups_with_project_permissions() { dbClient.componentDao().insert(dbSession, newProjectDto("project-uuid").setKey("project-key")); ComponentDto project = dbClient.componentDao().selectOrFailByUuid(dbSession, "project-uuid"); GroupDto group = insertGroup(new GroupDto().setName("project-group-name")); insertGroupRole( new GroupRoleDto() .setGroupId(group.getId()) .setRole(ISSUE_ADMIN) .setResourceId(project.getId())); userSession.login().addProjectUuidPermissions(UserRole.ADMIN, "project-uuid"); String result = ws.newRequest() .setParam(PARAM_PERMISSION, ISSUE_ADMIN) .setParam(PARAM_PROJECT_ID, "project-uuid") .execute() .getInput(); assertThat(result) .contains("project-group-name") .doesNotContain("group-1") .doesNotContain("group-2") .doesNotContain("group-3"); }
private List<ComponentDto> searchProjects( DbSession dbSession, @Nullable List<String> uuids, @Nullable List<String> keys) { if (uuids != null) { return dbClient.componentDao().selectByUuids(dbSession, uuids); } if (keys != null) { return dbClient.componentDao().selectByKeys(dbSession, keys); } throw new IllegalArgumentException("ids or keys must be provided"); }
public DefaultIssue createManualIssue( String componentKey, RuleKey ruleKey, @Nullable Integer line, @Nullable String message, @Nullable String severity) { verifyLoggedIn(); DbSession dbSession = dbClient.openSession(false); try { Optional<ComponentDto> componentOptional = dbClient.componentDao().selectByKey(dbSession, componentKey); if (!componentOptional.isPresent()) { throw new BadRequestException( String.format("Component with key '%s' not found", componentKey)); } ComponentDto component = componentOptional.get(); ComponentDto project = dbClient.componentDao().selectOrFailByUuid(dbSession, component.projectUuid()); userSession.checkComponentPermission(UserRole.USER, project.getKey()); if (!ruleKey.isManual()) { throw new IllegalArgumentException( "Issues can be created only on rules marked as 'manual': " + ruleKey); } Rule rule = getNullableRuleByKey(ruleKey); if (rule == null) { throw new IllegalArgumentException("Unknown rule: " + ruleKey); } DefaultIssue issue = new DefaultIssueBuilder() .componentKey(component.getKey()) .projectKey(project.getKey()) .line(line) .message(!Strings.isNullOrEmpty(message) ? message : rule.getName()) .severity(Objects.firstNonNull(severity, Severity.MAJOR)) .ruleKey(ruleKey) .reporter(userSession.getLogin()) .assignee(findSourceLineUser(dbSession, component.uuid(), line)) .build(); Date now = new Date(); issue.setCreationDate(now); issue.setUpdateDate(now); issueStorage.save(issue); return issue; } finally { dbSession.close(); } }
@Test public void list_based_on_source_file_key_and_line_number() throws Exception { String sourceFileUuid = "MAIN-FILE-UUID"; String sourceFileKey = "MAIN-FILE-KEY"; userSessionRule.addProjectUuidPermissions(UserRole.CODEVIEWER, TestFile1.PROJECT_UUID); dbClient .componentDao() .insert( db.getSession(), TestFile1.dto(), TestFile2.dto(), new ComponentDto() .setUuid(sourceFileUuid) .setUuidPath(TestFile1.PROJECT_UUID + "." + sourceFileUuid + ".") .setRootUuid(TestFile1.PROJECT_UUID) .setKey(sourceFileKey) .setProjectUuid(TestFile1.PROJECT_UUID)); db.getSession().commit(); es.putDocuments( TestIndexDefinition.INDEX, TestIndexDefinition.TYPE, TestFile1.doc(), TestFile2.doc()); WsTester.TestRequest request = ws.newGetRequest("api/tests", "list") .setParam(ListAction.SOURCE_FILE_KEY, sourceFileKey) .setParam(ListAction.SOURCE_FILE_LINE_NUMBER, "10"); request.execute().assertJson(getClass(), "list-main-file.json"); }
@Test public void covered_files() throws Exception { userSessionRule.addComponentUuidPermission(UserRole.CODEVIEWER, "SonarQube", "test-file-uuid"); when(testIndex.searchByTestUuid(anyString()).fileUuid()).thenReturn("test-file-uuid"); when(testIndex.coveredFiles("test-uuid")) .thenReturn( Arrays.asList( new CoveredFileDoc() .setFileUuid("bar-uuid") .setCoveredLines(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)), new CoveredFileDoc() .setFileUuid("file-uuid") .setCoveredLines(Arrays.asList(1, 2, 3)))); when(dbClient.componentDao().selectByUuids(any(DbSession.class), anyList())) .thenReturn( Arrays.asList( newFileDto(newProjectDto(), "bar-uuid") .setKey("org.foo.Bar.java") .setLongName("src/main/java/org/foo/Bar.java"), newFileDto(newProjectDto(), "file-uuid") .setKey("org.foo.File.java") .setLongName("src/main/java/org/foo/File.java"))); WsTester.TestRequest request = ws.newGetRequest("api/tests", "covered_files").setParam(TEST_UUID, "test-uuid"); request.execute().assertJson(getClass(), "tests-covered-files.json"); }
private void appendComponent( JsonWriter json, ComponentDto component, UserSession userSession, DbSession session) { List<PropertyDto> propertyDtos = dbClient .propertiesDao() .selectByQuery( PropertyQuery.builder() .setKey("favourite") .setComponentId(component.getId()) .setUserId(userSession.getUserId()) .build(), session); boolean isFavourite = propertyDtos.size() == 1; json.prop("key", component.key()); json.prop("uuid", component.uuid()); json.prop("path", component.path()); json.prop("name", component.name()); json.prop("longName", component.longName()); json.prop("q", component.qualifier()); ComponentDto parentProject = retrieveRootIfNotCurrentComponent(component, session); ComponentDto project = dbClient.componentDao().selectOrFailByUuid(session, component.projectUuid()); // Do not display parent project if parent project and project are the same boolean displayParentProject = parentProject != null && !parentProject.uuid().equals(project.uuid()); json.prop("subProject", displayParentProject ? parentProject.key() : null); json.prop("subProjectName", displayParentProject ? parentProject.longName() : null); json.prop("project", project.key()); json.prop("projectName", project.longName()); json.prop("fav", isFavourite); }
@Test public void change_project_association_with_key_and_uuid() throws Exception { ComponentDto project = ComponentTesting.newProjectDto("ABCD").setId(1L); db.componentDao().insert(session, project); QualityProfileDto profile1 = QProfileTesting.newXooP1(); QualityProfileDto profile2 = QProfileTesting.newXooP2(); db.qualityProfileDao().insert(session, profile1, profile2); db.qualityProfileDao() .insertProjectProfileAssociation(project.uuid(), profile1.getKey(), session); session.commit(); wsTester .newPostRequest(QProfilesWs.API_ENDPOINT, "add_project") .setParam("profileKey", profile2.getKee()) .setParam("projectUuid", project.uuid()) .execute() .assertNoContent(); assertThat( tester .get(QProfileFactory.class) .getByProjectAndLanguage(session, project.getKey(), "xoo") .getKee()) .isEqualTo(profile2.getKee()); }
@Test public void returns_full_object_in_response() throws Exception { MetricDto metric = MetricTesting.newMetricDto() .setEnabled(true) .setValueType(ValueType.STRING.name()) .setKey("metric-key"); dbClient.metricDao().insert(dbSession, metric); ComponentDto component = ComponentTesting.newProjectDto("project-uuid").setKey("project-key"); dbClient.componentDao().insert(dbSession, component); CustomMeasureDto customMeasure = newCustomMeasure(component, metric) .setCreatedAt(100_000_000L) .setDescription("custom-measure-description") .setTextValue("text-measure-value"); dbClient.customMeasureDao().insert(dbSession, customMeasure); dbSession.commit(); when(system.now()).thenReturn(123_456_789L); WsTester.Result response = ws.newPostRequest(CustomMeasuresWs.ENDPOINT, UpdateAction.ACTION) .setParam(PARAM_ID, String.valueOf(customMeasure.getId())) .setParam(PARAM_DESCRIPTION, "new-custom-measure-description") .setParam(PARAM_VALUE, "new-text-measure-value") .execute(); response.assertJson(getClass(), "custom-measure.json"); String responseAsString = response.outputAsString(); assertThat(responseAsString) .matches(String.format(".*\"id\"\\s*:\\s*\"%s\".*", customMeasure.getId())); assertThat(responseAsString) .matches(String.format(".*\"id\"\\s*:\\s*\"%s\".*", metric.getId())); assertThat(responseAsString).matches(".*createdAt.*updatedAt.*"); }
@Test public void fail_if_not_logged_in() throws Exception { userSessionRule.anonymous(); expectedException.expect(UnauthorizedException.class); MetricDto metric = MetricTesting.newMetricDto().setEnabled(true).setValueType(ValueType.STRING.name()); dbClient.metricDao().insert(dbSession, metric); ComponentDto component = ComponentTesting.newProjectDto("project-uuid"); dbClient.componentDao().insert(dbSession, component); CustomMeasureDto customMeasure = newCustomMeasureDto() .setMetricId(metric.getId()) .setComponentUuid(component.uuid()) .setCreatedAt(system.now()) .setDescription("custom-measure-description") .setTextValue("text-measure-value"); dbClient.customMeasureDao().insert(dbSession, customMeasure); dbSession.commit(); ws.newPostRequest(CustomMeasuresWs.ENDPOINT, UpdateAction.ACTION) .setParam(PARAM_ID, String.valueOf(customMeasure.getId())) .setParam(PARAM_DESCRIPTION, "new-custom-measure-description") .setParam(PARAM_VALUE, "1984") .execute(); }
@Test public void set_variation() { // Project SnapshotDto period1ProjectSnapshot = createForProject(PROJECT_DTO); dbClient.snapshotDao().insert(session, period1ProjectSnapshot); dbClient .measureDao() .insert( session, newMeasureDto( ISSUES_METRIC.getId(), PROJECT_DTO.getId(), period1ProjectSnapshot.getId(), 60d)); // Directory ComponentDto directoryDto = ComponentTesting.newDirectory(PROJECT_DTO, "dir"); dbClient.componentDao().insert(session, directoryDto); SnapshotDto period1DirectorySnapshot = createForComponent(directoryDto, period1ProjectSnapshot); dbClient.snapshotDao().insert(session, period1DirectorySnapshot); dbClient .measureDao() .insert( session, newMeasureDto( ISSUES_METRIC.getId(), directoryDto.getId(), period1DirectorySnapshot.getId(), 10d)); session.commit(); periodsHolder.setPeriods(newPeriod(1, period1ProjectSnapshot)); Component directory = ReportComponent.builder(Component.Type.DIRECTORY, 2).setUuid(directoryDto.uuid()).build(); Component project = ReportComponent.builder(Component.Type.PROJECT, 1) .setUuid(PROJECT_DTO.uuid()) .addChildren(directory) .build(); treeRootHolder.setRoot(project); addRawMeasure(project, ISSUES_METRIC, Measure.newMeasureBuilder().create(80, null)); addRawMeasure(directory, ISSUES_METRIC, Measure.newMeasureBuilder().create(20, null)); underTest.execute(); assertThat( measureRepository .getRawMeasure(project, ISSUES_METRIC) .get() .getVariations() .getVariation1()) .isEqualTo(20d); assertThat( measureRepository .getRawMeasure(directory, ISSUES_METRIC) .get() .getVariations() .getVariation1()) .isEqualTo(10d); }
@CheckForNull private ComponentDto retrieveRootIfNotCurrentComponent( ComponentDto componentDto, DbSession session) { if (componentDto.uuid().equals(componentDto.getRootUuid())) { return null; } return dbClient.componentDao().selectOrFailByUuid(session, componentDto.getRootUuid()); }
void saveIssue( DbSession session, DefaultIssue issue, IssueChangeContext context, @Nullable String comment) { String projectKey = issue.projectKey(); if (projectKey == null) { throw new IllegalStateException(String.format("Issue '%s' has no project key", issue.key())); } issueStorage.save(session, issue); Rule rule = getNullableRuleByKey(issue.ruleKey()); ComponentDto project = dbClient.componentDao().selectOrFailByKey(session, projectKey); notificationService.scheduleForSending( new IssueChangeNotification() .setIssue(issue) .setChangeAuthorLogin(context.login()) .setRuleName(rule != null ? rule.getName() : null) .setProject(project.getKey(), project.name()) .setComponent(dbClient.componentDao().selectOrFailByKey(session, issue.componentKey())) .setComment(comment)); }
@Test(expected = ForbiddenException.class) public void fail_when_no_sufficent_privilege_on_file_key() throws Exception { userSessionRule.addProjectUuidPermissions(UserRole.USER, TestFile1.PROJECT_UUID); dbClient.componentDao().insert(db.getSession(), TestFile1.dto()); db.getSession().commit(); ws.newGetRequest("api/tests", "list") .setParam(ListAction.TEST_FILE_KEY, TestFile1.KEY) .execute(); }
@Before public void setUp() { dbTester.truncateTables(); dbClient.componentDao().insert(session, PROJECT_DTO); session.commit(); underTest = new FillMeasuresWithVariationsStep( dbClient, treeRootHolder, periodsHolder, metricRepository, measureRepository); }
private Map<String, String> keysByUUid(DbSession session, ComponentDto component) { Map<String, String> keysByUUid = newHashMap(); if (Scopes.PROJECT.equals(component.scope())) { List<ComponentDto> modulesTree = dbClient.componentDao().selectDescendantModules(session, component.uuid()); for (ComponentDto componentDto : modulesTree) { keysByUUid.put(componentDto.uuid(), componentDto.key()); } } else { String moduleUuid = component.moduleUuid(); if (moduleUuid == null) { throw new IllegalArgumentException( String.format("The component '%s' has no module uuid", component.uuid())); } ComponentDto module = dbClient.componentDao().selectOrFailByUuid(session, moduleUuid); keysByUUid.put(module.uuid(), module.key()); } return keysByUUid; }
@Test public void delete_projects_by_uuid_when_admin_on_the_project() throws Exception { insertNewProjectInDbAndReturnSnapshotId(1); userSessionRule.login("login").addProjectUuidPermissions(UserRole.ADMIN, "project-uuid-1"); newRequest().setParam(PARAM_ID, "project-uuid-1").execute(); dbSession.commit(); assertThat(dbClient.componentDao().selectByUuid(dbSession, "project-uuid-1")).isAbsent(); }
@Test public void delete_projects_and_data_in_db_by_key() throws Exception { insertNewProjectInDbAndReturnSnapshotId(1); insertNewProjectInDbAndReturnSnapshotId(2); newRequest().setParam(PARAM_KEY, "project-key-1").execute(); dbSession.commit(); assertThat(dbClient.componentDao().selectByUuid(dbSession, "project-uuid-1")).isAbsent(); assertThat(dbClient.componentDao().selectOrFailByUuid(dbSession, "project-uuid-2")).isNotNull(); }
private ComponentDtosAndTotal searchComponents( DbSession dbSession, ComponentTreeQuery dbQuery, ComponentTreeWsRequest wsRequest) { if (dbQuery.getQualifiers() != null && dbQuery.getQualifiers().isEmpty()) { return new ComponentDtosAndTotal(Collections.emptyList(), 0); } String strategy = requireNonNull(wsRequest.getStrategy()); switch (strategy) { case CHILDREN_STRATEGY: return new ComponentDtosAndTotal( dbClient.componentDao().selectChildren(dbSession, dbQuery), dbClient.componentDao().countChildren(dbSession, dbQuery)); case LEAVES_STRATEGY: case ALL_STRATEGY: return new ComponentDtosAndTotal( dbClient.componentDao().selectDescendants(dbSession, dbQuery), dbClient.componentDao().countDescendants(dbSession, dbQuery)); default: throw new IllegalStateException("Unknown component tree strategy"); } }
@Test public void fail_if_project_uuid_and_project_key_are_provided() { expectedException.expect(BadRequestException.class); dbClient.componentDao().insert(dbSession, newProjectDto("project-uuid").setKey("project-key")); ws.newRequest() .setParam(PARAM_PERMISSION, SCAN_EXECUTION) .setParam(PARAM_PROJECT_ID, "project-uuid") .setParam(PARAM_PROJECT_KEY, "project-key") .execute(); }
@Test public void return_undefined_status_if_measure_is_not_found() { ComponentDto project = newProjectDto("project-uuid"); dbClient.componentDao().insert(dbSession, project); SnapshotDto snapshot = dbClient.snapshotDao().insert(dbSession, newSnapshotForProject(project)); dbSession.commit(); ProjectStatusWsResponse result = newRequest(snapshot.getId().toString()); assertThat(result.getProjectStatus().getStatus()).isEqualTo(Status.NONE); assertThat(result.getProjectStatus().getConditionsCount()).isEqualTo(0); }
@Test public void fail_if_scope_is_not_project() throws Exception { expectedException.expect(IllegalArgumentException.class); dbClient .componentDao() .insert( dbSession, ComponentTesting.newFileDto(ComponentTesting.newProjectDto(), null, "file-uuid")); dbSession.commit(); newRequest().setParam(PARAM_ID, "file-uuid").execute(); }
@Test public void fail_if_qualifier_is_not_deletable() throws Exception { expectedException.expect(IllegalArgumentException.class); dbClient .componentDao() .insert( dbSession, ComponentTesting.newProjectDto("project-uuid").setQualifier(Qualifiers.FILE)); dbSession.commit(); when(resourceType.getBooleanProperty(anyString())).thenReturn(false); newRequest().setParam(PARAM_ID, "project-uuid").execute(); }
@Override public void handle(Request request, Response response) { String query = request.mandatoryParam(Param.TEXT_QUERY); if (query.length() < MINIMUM_SEARCH_CHARACTERS) { throw new IllegalArgumentException( String.format("Minimum search is %s characters", MINIMUM_SEARCH_CHARACTERS)); } String componentUuid = request.mandatoryParam(PARAM_COMPONENT_UUID); JsonWriter json = response.newJsonWriter(); json.beginObject(); DbSession session = dbClient.openSession(false); try { ComponentDto componentDto = componentFinder.getByUuid(session, componentUuid); userSession.checkProjectUuidPermission(UserRole.USER, componentDto.projectUuid()); Set<Long> projectIds = newLinkedHashSet( dbClient .componentIndexDao() .selectProjectIdsFromQueryAndViewOrSubViewUuid( session, query, componentDto.uuid())); Collection<Long> authorizedProjectIds = dbClient .authorizationDao() .keepAuthorizedProjectIds( session, projectIds, userSession.getUserId(), UserRole.USER); SearchOptions options = new SearchOptions(); options.setPage(request.mandatoryParamAsInt(PAGE), request.mandatoryParamAsInt(PAGE_SIZE)); Set<Long> pagedProjectIds = pagedProjectIds(authorizedProjectIds, options); List<ComponentDto> projects = dbClient.componentDao().selectByIds(session, pagedProjectIds); options.writeJson(json, authorizedProjectIds.size()); json.name("components").beginArray(); for (ComponentDto project : projects) { json.beginObject(); json.prop("uuid", project.uuid()); json.prop("name", project.name()); json.endObject(); } json.endArray(); } finally { MyBatis.closeQuietly(session); } json.endObject(); json.close(); }
@Test public void list_based_on_test_file_key() throws Exception { userSessionRule.addComponentPermission( UserRole.CODEVIEWER, TestFile1.PROJECT_UUID, TestFile1.KEY); dbClient.componentDao().insert(db.getSession(), TestFile1.dto()); db.getSession().commit(); es.putDocuments(TestIndexDefinition.INDEX, TestIndexDefinition.TYPE, TestFile1.doc()); WsTester.TestRequest request = ws.newGetRequest("api/tests", "list").setParam(ListAction.TEST_FILE_KEY, TestFile1.KEY); request.execute().assertJson(getClass(), "list-test-uuid.json"); }
private Map<String, ComponentDto> searchReferenceComponentsById( DbSession dbSession, List<ComponentDto> components) { List<String> referenceComponentUUids = from(components) .transform(ComponentDto::getCopyResourceUuid) .filter(Predicates.<String>notNull()) .toList(); if (referenceComponentUUids.isEmpty()) { return emptyMap(); } return FluentIterable.from( dbClient.componentDao().selectByUuids(dbSession, referenceComponentUUids)) .uniqueIndex(ComponentDto::uuid); }
@Test public void delete_project_and_data_in_db_by_uuid() throws Exception { long snapshotId1 = insertNewProjectInDbAndReturnSnapshotId(1); long snapshotId2 = insertNewProjectInDbAndReturnSnapshotId(2); newRequest().setParam(PARAM_ID, "project-uuid-1").execute(); dbSession.commit(); assertThat(dbClient.componentDao().selectByUuid(dbSession, "project-uuid-1")).isAbsent(); assertThat(dbClient.componentDao().selectOrFailByUuid(dbSession, "project-uuid-2")).isNotNull(); assertThat(dbClient.snapshotDao().selectById(dbSession, snapshotId1)).isNull(); assertThat(dbClient.snapshotDao().selectById(dbSession, snapshotId2)).isNotNull(); assertThat(dbClient.issueDao().selectByKey(dbSession, "issue-key-1").isPresent()).isFalse(); assertThat(dbClient.issueDao().selectOrFailByKey(dbSession, "issue-key-2")).isNotNull(); }
private long insertNewProjectInDbAndReturnSnapshotId(int id) { String suffix = String.valueOf(id); ComponentDto project = ComponentTesting.newProjectDto("project-uuid-" + suffix).setKey("project-key-" + suffix); RuleDto rule = RuleTesting.newDto(RuleKey.of("sonarqube", "rule-" + suffix)); dbClient.ruleDao().insert(dbSession, rule); IssueDto issue = IssueTesting.newDto(rule, project, project).setKee("issue-key-" + suffix); dbClient.componentDao().insert(dbSession, project); SnapshotDto snapshot = dbClient.snapshotDao().insert(dbSession, SnapshotTesting.newAnalysis(project)); dbClient.issueDao().insert(dbSession, issue); dbSession.commit(); return snapshot.getId(); }
@Before public void setUp() { DbClient dbClient = mock(DbClient.class); when(dbClient.openSession(false)).thenReturn(session); when(dbClient.componentDao()).thenReturn(componentDao); when(dbClient.propertiesDao()).thenReturn(propertiesDao); when(dbClient.measureDao()).thenReturn(measureDao); when(measureDao.selectByComponentKeyAndMetricKeys( eq(session), anyString(), anyListOf(String.class))) .thenReturn(measures); tester = new WsTester( new ComponentsWs( new AppAction( dbClient, durations, i18n, userSessionRule, new ComponentFinder(dbClient)), mock(SearchAction.class))); }
@Test(expected = ForbiddenException.class) public void fail_when_no_sufficient_privilege_on_main_file_uuid() throws Exception { userSessionRule.addProjectUuidPermissions(UserRole.USER, TestFile1.PROJECT_UUID); String mainFileUuid = "MAIN-FILE-UUID"; dbClient .componentDao() .insert( db.getSession(), new ComponentDto() .setUuid(mainFileUuid) .setUuidPath(TestFile1.PROJECT_UUID + "." + mainFileUuid + ".") .setRootUuid(TestFile1.PROJECT_UUID) .setProjectUuid(TestFile1.PROJECT_UUID)); db.getSession().commit(); ws.newGetRequest("api/tests", "list") .setParam(ListAction.SOURCE_FILE_ID, mainFileUuid) .setParam(ListAction.SOURCE_FILE_LINE_NUMBER, "10") .execute(); }
@Test public void return_undefined_status_if_measure_data_is_not_well_formatted() { userSession.setGlobalPermissions(GlobalPermissions.SCAN_EXECUTION); ComponentDto project = newProjectDto("project-uuid"); dbClient.componentDao().insert(dbSession, project); SnapshotDto snapshot = dbClient.snapshotDao().insert(dbSession, newSnapshotForProject(project)); MetricDto metric = dbClient .metricDao() .insert( dbSession, newMetricDto().setEnabled(true).setKey(CoreMetrics.QUALITY_GATE_DETAILS_KEY)); MeasureDto measure = newMeasureDto(metric, snapshot.getId()).setData(""); dbClient.measureDao().insert(dbSession, measure); dbSession.commit(); ProjectStatusWsResponse result = newRequest(String.valueOf(snapshot.getId())); assertThat(result.getProjectStatus().getStatus()).isEqualTo(Status.NONE); assertThat(result.getProjectStatus().getConditionsCount()).isEqualTo(0); }