@@ -21,7 +21,6 @@ | |||
package org.sonar.server.ce.ws; | |||
import com.google.common.base.Optional; | |||
import javax.annotation.Nullable; | |||
import org.sonar.api.server.ws.Request; | |||
import org.sonar.api.server.ws.Response; | |||
import org.sonar.api.server.ws.WebService; | |||
@@ -85,7 +84,7 @@ public class ActivityStatusAction implements CeWsAction { | |||
try { | |||
Optional<ComponentDto> component = searchComponent(dbSession, request); | |||
String componentUuid = component.isPresent() ? component.get().uuid() : null; | |||
checkPermissions(componentUuid); | |||
checkPermissions(component); | |||
int pendingCount = dbClient.ceQueueDao().countByStatusAndComponentUuid(dbSession, CeQueueDto.Status.PENDING, componentUuid); | |||
int failingCount = dbClient.ceActivityDao().countLastByStatusAndComponentUuid(dbSession, CeActivityDto.Status.FAILED, componentUuid); | |||
@@ -106,11 +105,11 @@ public class ActivityStatusAction implements CeWsAction { | |||
return Optional.fromNullable(component); | |||
} | |||
private void checkPermissions(@Nullable String componentUuid) { | |||
if (componentUuid == null) { | |||
userSession.checkPermission(GlobalPermissions.SYSTEM_ADMIN); | |||
private void checkPermissions(Optional<ComponentDto> component) { | |||
if (component.isPresent()) { | |||
userSession.checkComponentPermission(UserRole.ADMIN, component.get()); | |||
} else { | |||
userSession.checkComponentUuidPermission(UserRole.ADMIN, componentUuid); | |||
userSession.checkPermission(GlobalPermissions.SYSTEM_ADMIN); | |||
} | |||
} | |||
@@ -83,7 +83,7 @@ public class ComponentAction implements CeWsAction { | |||
DbSession dbSession = dbClient.openSession(false); | |||
try { | |||
ComponentDto component = componentFinder.getByUuidOrKey(dbSession, wsRequest.param(PARAM_COMPONENT_ID), wsRequest.param(PARAM_COMPONENT_KEY), COMPONENT_ID_AND_KEY); | |||
userSession.checkComponentUuidPermission(UserRole.USER, component.uuid()); | |||
userSession.checkComponentPermission(UserRole.USER, component); | |||
List<CeQueueDto> queueDtos = dbClient.ceQueueDao().selectByComponentUuid(dbSession, component.uuid()); | |||
CeTaskQuery activityQuery = new CeTaskQuery() | |||
.setComponentUuid(component.uuid()) |
@@ -57,7 +57,7 @@ public class ComponentService { | |||
// TODO should be moved to ComponentUpdater | |||
public void updateKey(DbSession dbSession, ComponentDto component, String newKey) { | |||
userSession.checkComponentUuidPermission(UserRole.ADMIN, component.projectUuid()); | |||
userSession.checkComponentPermission(UserRole.ADMIN, component); | |||
checkIsProjectOrModule(component); | |||
checkProjectOrModuleKeyFormat(newKey); | |||
dbClient.componentKeyUpdaterDao().updateKey(component.uuid(), newKey); |
@@ -100,7 +100,7 @@ public class AppAction implements RequestHandler { | |||
DbSession session = dbClient.openSession(false); | |||
try { | |||
ComponentDto component = componentFinder.getByUuid(session, componentUuid); | |||
userSession.checkComponentUuidPermission(UserRole.USER, component.uuid()); | |||
userSession.checkComponentPermission(UserRole.USER, component); | |||
Map<String, MeasureDto> measuresByMetricKey = measuresByMetricKey(component, session); | |||
appendComponent(json, component, userSession, session); |
@@ -124,7 +124,7 @@ public class BulkUpdateKeyAction implements ComponentsWsAction { | |||
try { | |||
ComponentDto projectOrModule = componentFinder.getByUuidOrKey(dbSession, request.getId(), request.getKey(), ParamNames.ID_AND_KEY); | |||
checkIsProjectOrModule(projectOrModule); | |||
userSession.checkComponentUuidPermission(UserRole.ADMIN, projectOrModule.uuid()); | |||
userSession.checkComponentPermission(UserRole.ADMIN, projectOrModule); | |||
Map<String, String> newKeysByOldKeys = componentKeyUpdater.simulateBulkUpdateKey(dbSession, projectOrModule.uuid(), request.getFrom(), request.getTo()); | |||
Map<String, Boolean> newKeysWithDuplicateMap = componentKeyUpdater.checkComponentKeys(dbSession, ImmutableList.copyOf(newKeysByOldKeys.values())); |
@@ -76,7 +76,7 @@ public class ReportSubmitter { | |||
Optional<ComponentDto> opt = dbClient.componentDao().selectByKey(dbSession, effectiveProjectKey); | |||
ensureOrganizationIsConsistent(opt, organizationDto); | |||
ComponentDto project = opt.or(() -> createProject(dbSession, organizationDto.getUuid(), projectKey, projectBranch, projectName)); | |||
userSession.checkComponentUuidPermission(SCAN_EXECUTION, project.uuid()); | |||
userSession.checkComponentPermission(SCAN_EXECUTION, project); | |||
return submitReport(dbSession, reportInput, project); | |||
} | |||
} |
@@ -33,7 +33,6 @@ import org.sonar.api.web.UserRole; | |||
import org.sonar.db.DbClient; | |||
import org.sonar.db.DbSession; | |||
import org.sonar.db.component.ComponentDto; | |||
import org.sonar.db.measure.MeasureDao; | |||
import org.sonar.db.measure.MeasureDto; | |||
import org.sonar.db.measure.MeasureQuery; | |||
import org.sonar.server.component.ComponentFinder; | |||
@@ -44,16 +43,14 @@ import static org.sonar.server.component.ComponentFinder.ParamNames.UUID_AND_KEY | |||
public class ShowAction implements RequestHandler { | |||
private final DbClient dbClient; | |||
private final MeasureDao measureDao; | |||
private final DuplicationsParser parser; | |||
private final DuplicationsJsonWriter duplicationsJsonWriter; | |||
private final UserSession userSession; | |||
private final ComponentFinder componentFinder; | |||
public ShowAction(DbClient dbClient, MeasureDao measureDao, DuplicationsParser parser, | |||
DuplicationsJsonWriter duplicationsJsonWriter, UserSession userSession, ComponentFinder componentFinder) { | |||
public ShowAction(DbClient dbClient, DuplicationsParser parser, | |||
DuplicationsJsonWriter duplicationsJsonWriter, UserSession userSession, ComponentFinder componentFinder) { | |||
this.dbClient = dbClient; | |||
this.measureDao = measureDao; | |||
this.parser = parser; | |||
this.duplicationsJsonWriter = duplicationsJsonWriter; | |||
this.userSession = userSession; | |||
@@ -83,7 +80,7 @@ public class ShowAction implements RequestHandler { | |||
DbSession dbSession = dbClient.openSession(false); | |||
try { | |||
ComponentDto component = componentFinder.getByUuidOrKey(dbSession, request.param("uuid"), request.param("key"), UUID_AND_KEY); | |||
userSession.checkComponentPermission(UserRole.CODEVIEWER, component.key()); | |||
userSession.checkComponentPermission(UserRole.CODEVIEWER, component); | |||
JsonWriter json = response.newJsonWriter().beginObject(); | |||
String duplications = findDataFromComponent(dbSession, component); | |||
List<DuplicationsParser.Block> blocks = parser.parse(component, duplications, dbSession); | |||
@@ -100,7 +97,7 @@ public class ShowAction implements RequestHandler { | |||
.setComponentUuid(component.uuid()) | |||
.setMetricKey(CoreMetrics.DUPLICATIONS_DATA_KEY) | |||
.build(); | |||
Optional<MeasureDto> measure = measureDao.selectSingle(dbSession, query); | |||
Optional<MeasureDto> measure = dbClient.measureDao().selectSingle(dbSession, query); | |||
return measure.isPresent() ? measure.get().getData() : null; | |||
} | |||
} |
@@ -75,7 +75,7 @@ public class AddAction implements FavoritesWsAction { | |||
ComponentDto componentDto = componentFinder.getByKey(dbSession, request.mandatoryParam(PARAM_COMPONENT)); | |||
userSession | |||
.checkLoggedIn() | |||
.checkComponentUuidPermission(UserRole.USER, componentDto.uuid()); | |||
.checkComponentPermission(UserRole.USER, componentDto); | |||
favoriteUpdater.add(dbSession, componentDto, userSession.isLoggedIn() ? userSession.getUserId().longValue() : null); | |||
dbSession.commit(); | |||
} |
@@ -99,6 +99,6 @@ public class CustomMeasureValidator { | |||
return; | |||
} | |||
userSession.checkLoggedIn().checkComponentUuidPermission(UserRole.ADMIN, component.projectUuid()); | |||
userSession.checkLoggedIn().checkComponentPermission(UserRole.ADMIN, component); | |||
} | |||
} |
@@ -81,6 +81,6 @@ public class DeleteAction implements CustomMeasuresWsAction { | |||
} | |||
ComponentDto component = dbClient.componentDao().selectOrFailByUuid(dbSession, customMeasure.getComponentUuid()); | |||
userSession.checkLoggedIn().checkComponentUuidPermission(UserRole.ADMIN, component.projectUuid()); | |||
userSession.checkLoggedIn().checkComponentPermission(UserRole.ADMIN, component); | |||
} | |||
} |
@@ -143,7 +143,7 @@ public class SearchHistoryAction implements MeasuresWsAction { | |||
private ComponentDto searchComponent(SearchHistoryRequest request, DbSession dbSession) { | |||
ComponentDto component = componentFinder.getByKey(dbSession, request.getComponent()); | |||
userSession.checkComponentUuidPermission(UserRole.USER, component.projectUuid()); | |||
userSession.checkComponentPermission(UserRole.USER, component); | |||
return component; | |||
} | |||
@@ -113,18 +113,13 @@ public class CreateEventAction implements ProjectAnalysesWsAction { | |||
private CreateEventResponse doHandle(CreateEventRequest request) { | |||
try (DbSession dbSession = dbClient.openSession(false)) { | |||
SnapshotDto analysis = getAnalysis(dbSession, request); | |||
checkPermissions(analysis); | |||
checkExistingDbEvents(dbSession, request, analysis); | |||
EventDto dbEvent = insertDbEvent(dbSession, request, analysis); | |||
return toCreateEventResponse(dbEvent); | |||
} | |||
} | |||
private void checkPermissions(SnapshotDto analysis) { | |||
userSession.checkComponentUuidPermission(UserRole.ADMIN, analysis.getComponentUuid()); | |||
} | |||
private EventDto insertDbEvent(DbSession dbSession, CreateEventRequest request, SnapshotDto analysis) { | |||
private EventDto insertDbEvent(DbSession dbSession, CreateEventRequest request, SnapshotDto analysis) { | |||
EventDto dbEvent = dbClient.eventDao().insert(dbSession, toDbEvent(request, analysis)); | |||
if (VERSION.equals(request.getCategory())) { | |||
analysis.setVersion(request.getName()); | |||
@@ -139,6 +134,7 @@ public class CreateEventAction implements ProjectAnalysesWsAction { | |||
.orElseThrow(() -> new NotFoundException(format("Analysis '%s' is not found", request.getAnalysis()))); | |||
ComponentDto project = dbClient.componentDao().selectByUuid(dbSession, analysis.getComponentUuid()).orNull(); | |||
checkState(project != null, "Project of analysis '%s' is not found", analysis.getUuid()); | |||
userSession.checkComponentPermission(UserRole.ADMIN, project); | |||
checkArgument(Qualifiers.PROJECT.equals(project.qualifier()) && Scopes.PROJECT.equals(project.scope()), | |||
"An event must be created on a project"); | |||
return analysis; |
@@ -125,7 +125,7 @@ public class SearchAction implements ProjectAnalysesWsAction { | |||
private Consumer<SearchResults.Builder> addAnalyses() { | |||
return data -> { | |||
SnapshotQuery dbQuery = new SnapshotQuery() | |||
.setComponentUuid(data.getProjectUuid()) | |||
.setComponentUuid(data.getProject().uuid()) | |||
.setStatus(SnapshotDto.STATUS_PROCESSED) | |||
.setSort(BY_DATE, DESC); | |||
data.setAnalyses(dbClient.snapshotDao().selectAnalysesByQuery(data.getDbSession(), dbQuery)); | |||
@@ -140,14 +140,14 @@ public class SearchAction implements ProjectAnalysesWsAction { | |||
} | |||
private Consumer<SearchResults.Builder> checkPermission() { | |||
return data -> userSession.checkComponentUuidPermission(UserRole.USER, data.getProjectUuid()); | |||
return data -> userSession.checkComponentPermission(UserRole.USER, data.getProject()); | |||
} | |||
private Consumer<SearchResults.Builder> addProject() { | |||
return data -> { | |||
ComponentDto project = componentFinder.getByKey(data.getDbSession(), data.getRequest().getProject()); | |||
checkArgument(Scopes.PROJECT.equals(project.scope()) && Qualifiers.PROJECT.equals(project.qualifier()), "A project is required"); | |||
data.setProjectUuid(project.uuid()); | |||
data.setProject(project); | |||
}; | |||
} | |||
@@ -27,6 +27,7 @@ import java.util.stream.Stream; | |||
import org.sonar.api.utils.Paging; | |||
import org.sonar.core.util.stream.Collectors; | |||
import org.sonar.db.DbSession; | |||
import org.sonar.db.component.ComponentDto; | |||
import org.sonar.db.component.SnapshotDto; | |||
import org.sonar.db.event.EventDto; | |||
import org.sonarqube.ws.client.projectanalysis.SearchRequest; | |||
@@ -58,7 +59,7 @@ class SearchResults { | |||
static class Builder { | |||
private final DbSession dbSession; | |||
private final SearchRequest request; | |||
private String projectUuid; | |||
private ComponentDto project; | |||
private List<SnapshotDto> analyses; | |||
private int countAnalyses; | |||
private List<EventDto> events; | |||
@@ -68,8 +69,8 @@ class SearchResults { | |||
this.request = request; | |||
} | |||
Builder setProjectUuid(String projectUuid) { | |||
this.projectUuid = projectUuid; | |||
Builder setProject(ComponentDto project) { | |||
this.project = project; | |||
return this; | |||
} | |||
@@ -100,8 +101,8 @@ class SearchResults { | |||
return request; | |||
} | |||
String getProjectUuid() { | |||
return projectUuid; | |||
ComponentDto getProject() { | |||
return project; | |||
} | |||
List<SnapshotDto> getAnalyses() { |
@@ -106,7 +106,7 @@ public class CreateAction implements ProjectLinksWsAction { | |||
try { | |||
ComponentDto component = getComponentByUuidOrKey(dbSession, createWsRequest); | |||
userSession.checkComponentUuidPermission(UserRole.ADMIN, component.uuid()); | |||
userSession.checkComponentPermission(UserRole.ADMIN, component); | |||
ComponentLinkDto link = new ComponentLinkDto() | |||
.setComponentUuid(component.uuid()) |
@@ -46,7 +46,7 @@ public class QProfileProjectOperations { | |||
} | |||
public void addProject(DbSession dbSession, String profileKey, ComponentDto project) { | |||
checkAdminOnProject(project.key()); | |||
checkAdminOnProject(project); | |||
QualityProfileDto qualityProfile = selectProfileByKey(dbSession, profileKey); | |||
QualityProfileDto currentProfile = db.qualityProfileDao().selectByProjectAndLanguage(dbSession, project.key(), qualityProfile.getLanguage()); | |||
@@ -65,7 +65,7 @@ public class QProfileProjectOperations { | |||
} | |||
public void removeProject(DbSession dbSession, String profileKey, ComponentDto project) { | |||
checkAdminOnProject(project.key()); | |||
checkAdminOnProject(project); | |||
QualityProfileDto qualityProfile = selectProfileByKey(dbSession, profileKey); | |||
db.qualityProfileDao().deleteProjectProfileAssociation(project.uuid(), qualityProfile.getKey(), dbSession); | |||
@@ -77,8 +77,9 @@ public class QProfileProjectOperations { | |||
return WsUtils.checkFound(qualityProfile, "Quality profile does not exist"); | |||
} | |||
private void checkAdminOnProject(String projectKey) { | |||
if (!userSession.hasPermission(GlobalPermissions.QUALITY_PROFILE_ADMIN) && !userSession.hasComponentPermission(UserRole.ADMIN, projectKey)) { | |||
private void checkAdminOnProject(ComponentDto project) { | |||
if (!userSession.hasPermission(GlobalPermissions.QUALITY_PROFILE_ADMIN) && | |||
!userSession.hasComponentPermission(UserRole.ADMIN, project)) { | |||
throw new ForbiddenException("Insufficient privileges"); | |||
} | |||
} |
@@ -115,7 +115,7 @@ public class ListDefinitionsAction implements SettingsWsAction { | |||
return Optional.empty(); | |||
} | |||
ComponentDto component = componentFinder.getByKey(dbSession, componentKey); | |||
userSession.checkComponentUuidPermission(USER, component.projectUuid()); | |||
userSession.checkComponentPermission(USER, component); | |||
return Optional.of(component); | |||
} | |||
} |
@@ -140,7 +140,7 @@ public class ResetAction implements SettingsWsAction { | |||
private void checkPermissions(Optional<ComponentDto> component) { | |||
if (component.isPresent()) { | |||
userSession.checkComponentUuidPermission(UserRole.ADMIN, component.get().uuid()); | |||
userSession.checkComponentPermission(UserRole.ADMIN, component.get()); | |||
} else { | |||
userSession.checkPermission(GlobalPermissions.SYSTEM_ADMIN); | |||
} |
@@ -271,7 +271,7 @@ public class SetAction implements SettingsWsAction { | |||
private void checkPermissions(Optional<ComponentDto> component) { | |||
if (component.isPresent()) { | |||
userSession.checkComponentUuidPermission(UserRole.ADMIN, component.get().uuid()); | |||
userSession.checkComponentPermission(UserRole.ADMIN, component.get()); | |||
} else { | |||
userSession.checkPermission(GlobalPermissions.SYSTEM_ADMIN); | |||
} |
@@ -143,7 +143,7 @@ public class ValuesAction implements SettingsWsAction { | |||
return Optional.empty(); | |||
} | |||
ComponentDto component = componentFinder.getByKey(dbSession, componentKey); | |||
userSession.checkComponentUuidPermission(USER, component.projectUuid()); | |||
userSession.checkComponentPermission(USER, component); | |||
return Optional.of(component); | |||
} | |||
@@ -68,25 +68,19 @@ public class HashAction implements SourcesWsAction { | |||
@Override | |||
public void handle(Request request, Response response) throws Exception { | |||
DbSession session = dbClient.openSession(false); | |||
try { | |||
final String componentKey = request.mandatoryParam("key"); | |||
final ComponentDto component = componentFinder.getByKey(session, componentKey); | |||
userSession.checkComponentUuidPermission(UserRole.USER, component.projectUuid()); | |||
try (DbSession session = dbClient.openSession(false)) { | |||
String componentKey = request.mandatoryParam("key"); | |||
ComponentDto component = componentFinder.getByKey(session, componentKey); | |||
userSession.checkComponentPermission(UserRole.USER, component); | |||
response.stream().setMediaType("text/plain"); | |||
OutputStreamWriter writer = new OutputStreamWriter(response.stream().output(), StandardCharsets.UTF_8); | |||
try { | |||
try (OutputStreamWriter writer = new OutputStreamWriter(response.stream().output(), StandardCharsets.UTF_8)) { | |||
HashFunction hashFunction = new HashFunction(writer, componentKey); | |||
dbClient.fileSourceDao().readLineHashesStream(session, component.uuid(), hashFunction); | |||
if (!hashFunction.hasData()) { | |||
response.noContent(); | |||
} | |||
} finally { | |||
writer.close(); | |||
} | |||
} finally { | |||
session.close(); | |||
} | |||
} | |||
@@ -75,12 +75,12 @@ public class IndexAction implements SourcesWsAction { | |||
@Override | |||
public void handle(Request request, Response response) { | |||
String fileKey = request.mandatoryParam("resource"); | |||
userSession.checkComponentPermission(UserRole.CODEVIEWER, fileKey); | |||
int from = request.mandatoryParamAsInt("from"); | |||
Integer to = request.paramAsInt("to"); | |||
try (DbSession session = dbClient.openSession(false)) { | |||
ComponentDto componentDto = componentFinder.getByKey(session, fileKey); | |||
Optional<Iterable<String>> lines = sourceService.getLinesAsRawText(session, componentDto.uuid(), from, to == null ? Integer.MAX_VALUE : to - 1); | |||
ComponentDto component = componentFinder.getByKey(session, fileKey); | |||
userSession.checkComponentPermission(UserRole.CODEVIEWER, component); | |||
Optional<Iterable<String>> lines = sourceService.getLinesAsRawText(session, component.uuid(), from, to == null ? Integer.MAX_VALUE : to - 1); | |||
JsonWriter json = response.newJsonWriter().beginArray().beginObject(); | |||
if (lines.isPresent()) { | |||
int lineCounter = from; |
@@ -115,7 +115,7 @@ public class LinesAction implements SourcesWsAction { | |||
DbSession dbSession = dbClient.openSession(false); | |||
try { | |||
ComponentDto file = componentFinder.getByUuidOrKey(dbSession, request.param(PARAM_UUID), request.param(PARAM_KEY), UUID_AND_KEY); | |||
userSession.checkComponentUuidPermission(UserRole.CODEVIEWER, file.projectUuid()); | |||
userSession.checkComponentPermission(UserRole.CODEVIEWER, file); | |||
int from = request.mandatoryParamAsInt(PARAM_FROM); | |||
int to = MoreObjects.firstNonNull(request.paramAsInt(PARAM_TO), Integer.MAX_VALUE); |
@@ -67,10 +67,10 @@ public class RawAction implements SourcesWsAction { | |||
@Override | |||
public void handle(Request request, Response response) { | |||
String fileKey = request.mandatoryParam("key"); | |||
DbSession dbSession = dbClient.openSession(false); | |||
try { | |||
try (DbSession dbSession = dbClient.openSession(false)) { | |||
ComponentDto file = componentFinder.getByKey(dbSession, fileKey); | |||
userSession.checkComponentUuidPermission(UserRole.CODEVIEWER, file.projectUuid()); | |||
userSession.checkComponentPermission(UserRole.CODEVIEWER, file); | |||
Optional<Iterable<String>> lines = sourceService.getLinesAsRawText(dbSession, file.uuid(), 1, Integer.MAX_VALUE); | |||
response.stream().setMediaType("text/plain"); | |||
@@ -83,8 +83,6 @@ public class RawAction implements SourcesWsAction { | |||
} | |||
} catch (IOException e) { | |||
throw new IllegalStateException("Fail to write raw source of file " + fileKey, e); | |||
} finally { | |||
dbClient.closeSession(dbSession); | |||
} | |||
} | |||
} |
@@ -104,7 +104,7 @@ public class ScmAction implements SourcesWsAction { | |||
DbSession dbSession = dbClient.openSession(false); | |||
try { | |||
ComponentDto file = componentFinder.getByKey(dbSession, fileKey); | |||
userSession.checkComponentUuidPermission(UserRole.CODEVIEWER, file.projectUuid()); | |||
userSession.checkComponentPermission(UserRole.CODEVIEWER, file); | |||
Optional<Iterable<DbFileSources.Line>> sourceLines = sourceService.getLines(dbSession, file.uuid(), from, to); | |||
if (!sourceLines.isPresent()) { | |||
throw new NotFoundException(String.format("File '%s' has no sources", fileKey)); |
@@ -89,7 +89,7 @@ public class ShowAction implements SourcesWsAction { | |||
DbSession dbSession = dbClient.openSession(false); | |||
try { | |||
ComponentDto file = componentFinder.getByKey(dbSession, fileKey); | |||
userSession.checkComponentUuidPermission(UserRole.CODEVIEWER, file.projectUuid()); | |||
userSession.checkComponentPermission(UserRole.CODEVIEWER, file); | |||
Optional<Iterable<String>> linesHtml = sourceService.getLinesAsHtml(dbSession, file.uuid(), from, to); | |||
if (linesHtml.isPresent()) { |
@@ -228,7 +228,7 @@ public class ListAction implements TestsWsAction { | |||
private SearchResult<TestDoc> searchTestsByTestFileKey(DbSession dbSession, String testFileKey, SearchOptions searchOptions) { | |||
ComponentDto testFile = componentFinder.getByKey(dbSession, testFileKey); | |||
userSession.checkComponentUuidPermission(UserRole.CODEVIEWER, testFile.projectUuid()); | |||
userSession.checkComponentPermission(UserRole.CODEVIEWER, testFile); | |||
return testIndex.searchByTestFileUuid(testFile.uuid(), searchOptions); | |||
} | |||
@@ -245,7 +245,7 @@ public class ListAction implements TestsWsAction { | |||
private void checkComponentUuidPermission(DbSession dbSession, String componentUuid) { | |||
ComponentDto component = componentFinder.getByUuid(dbSession, componentUuid); | |||
userSession.checkComponentUuidPermission(UserRole.CODEVIEWER, component.projectUuid()); | |||
userSession.checkComponentPermission(UserRole.CODEVIEWER, component); | |||
} | |||
private static class TestToFileUuidFunction implements Function<TestDoc, String> { |
@@ -126,7 +126,7 @@ public class WebhookDeliveriesAction implements WebhooksWsAction { | |||
void ensureAdminPermission(UserSession userSession) { | |||
if (component != null) { | |||
userSession.checkComponentUuidPermission(UserRole.ADMIN, component.uuid()); | |||
userSession.checkComponentPermission(UserRole.ADMIN, component); | |||
} | |||
} | |||
@@ -98,7 +98,7 @@ public class WebhookDeliveryAction implements WebhooksWsAction { | |||
} | |||
void ensureAdminPermission(UserSession userSession) { | |||
userSession.checkComponentUuidPermission(UserRole.ADMIN, component.uuid()); | |||
userSession.checkComponentPermission(UserRole.ADMIN, component); | |||
} | |||
void writeTo(Request request, Response response) { |
@@ -23,7 +23,6 @@ import org.junit.Rule; | |||
import org.junit.Test; | |||
import org.sonar.api.server.ws.WebService; | |||
import org.sonar.db.DbClient; | |||
import org.sonar.db.measure.MeasureDao; | |||
import org.sonar.server.component.ComponentFinder; | |||
import org.sonar.server.tester.UserSessionRule; | |||
import org.sonar.server.ws.WsTester; | |||
@@ -36,7 +35,7 @@ public class DuplicationsWsTest { | |||
public UserSessionRule userSessionRule = UserSessionRule.standalone(); | |||
WsTester tester = new WsTester(new DuplicationsWs( | |||
new ShowAction(mock(DbClient.class), mock(MeasureDao.class), mock(DuplicationsParser.class), mock(DuplicationsJsonWriter.class), userSessionRule, | |||
new ShowAction(mock(DbClient.class), mock(DuplicationsParser.class), mock(DuplicationsJsonWriter.class), userSessionRule, | |||
mock(ComponentFinder.class)))); | |||
@Test |
@@ -19,137 +19,121 @@ | |||
*/ | |||
package org.sonar.server.duplication.ws; | |||
import com.google.common.base.Optional; | |||
import com.google.common.collect.Lists; | |||
import java.util.List; | |||
import java.util.function.Function; | |||
import org.junit.Before; | |||
import org.junit.Rule; | |||
import org.junit.Test; | |||
import org.junit.runner.RunWith; | |||
import org.mockito.Mock; | |||
import org.mockito.runners.MockitoJUnitRunner; | |||
import org.sonar.api.utils.text.JsonWriter; | |||
import org.junit.rules.ExpectedException; | |||
import org.sonar.api.measures.CoreMetrics; | |||
import org.sonar.api.web.UserRole; | |||
import org.sonar.db.DbClient; | |||
import org.sonar.db.DbSession; | |||
import org.sonar.db.component.ComponentDao; | |||
import org.sonar.db.DbTester; | |||
import org.sonar.db.component.ComponentDto; | |||
import org.sonar.db.measure.MeasureDao; | |||
import org.sonar.db.measure.MeasureDto; | |||
import org.sonar.db.measure.MeasureQuery; | |||
import org.sonar.db.component.SnapshotDto; | |||
import org.sonar.db.metric.MetricDto; | |||
import org.sonar.server.component.ComponentFinder; | |||
import org.sonar.server.exceptions.ForbiddenException; | |||
import org.sonar.server.exceptions.NotFoundException; | |||
import org.sonar.server.startup.RegisterMetrics; | |||
import org.sonar.server.tester.UserSessionRule; | |||
import org.sonar.server.ws.WsTester; | |||
import static com.google.common.collect.Lists.newArrayList; | |||
import static org.mockito.Matchers.any; | |||
import static org.mockito.Matchers.eq; | |||
import static org.mockito.Mockito.verify; | |||
import static org.mockito.Mockito.when; | |||
import static org.sonar.db.component.ComponentTesting.newFileDto; | |||
import static org.sonar.db.component.SnapshotTesting.newAnalysis; | |||
import static org.sonar.db.measure.MeasureTesting.newMeasureDto; | |||
@RunWith(MockitoJUnitRunner.class) | |||
public class ShowActionTest { | |||
@Rule | |||
public UserSessionRule userSessionRule = UserSessionRule.standalone(); | |||
@Mock | |||
DbSession session; | |||
@Mock | |||
DbClient dbClient; | |||
public ExpectedException expectedException = ExpectedException.none(); | |||
@Mock | |||
ComponentDao componentDao; | |||
@Mock | |||
MeasureDao measureDao; | |||
@Mock | |||
DuplicationsParser parser; | |||
@Rule | |||
public UserSessionRule userSessionRule = UserSessionRule.standalone(); | |||
@Mock | |||
DuplicationsJsonWriter duplicationsJsonWriter; | |||
@Rule | |||
public DbTester db = DbTester.create(); | |||
WsTester tester; | |||
private DuplicationsParser parser = new DuplicationsParser(db.getDbClient().componentDao()); | |||
private DuplicationsJsonWriter duplicationsJsonWriter = new DuplicationsJsonWriter(db.getDbClient().componentDao()); | |||
private WsTester tester; | |||
private MetricDto dataMetric = RegisterMetrics.MetricToDto.INSTANCE.apply(CoreMetrics.DUPLICATIONS_DATA); | |||
@Before | |||
public void setUp() { | |||
when(dbClient.openSession(false)).thenReturn(session); | |||
when(dbClient.componentDao()).thenReturn(componentDao); | |||
tester = new WsTester(new DuplicationsWs(new ShowAction(dbClient, measureDao, parser, duplicationsJsonWriter, userSessionRule, new ComponentFinder(dbClient)))); | |||
tester = new WsTester(new DuplicationsWs(new ShowAction(db.getDbClient(), parser, duplicationsJsonWriter, userSessionRule, new ComponentFinder(db.getDbClient())))); | |||
db.getDbClient().metricDao().insert(db.getSession(), dataMetric); | |||
db.commit(); | |||
} | |||
@Test | |||
public void show_duplications() throws Exception { | |||
String componentKey = "src/Foo.java"; | |||
userSessionRule.addComponentPermission(UserRole.CODEVIEWER, "org.codehaus.sonar:sonar", componentKey); | |||
ComponentDto componentDto = new ComponentDto().setId(10L).setKey(componentKey); | |||
when(componentDao.selectByKey(session, componentKey)).thenReturn(Optional.of(componentDto)); | |||
String data = "{duplications}"; | |||
when(measureDao.selectSingle(eq(session), any(MeasureQuery.class))).thenReturn( | |||
java.util.Optional.of(new MeasureDto().setData("{duplications}")) | |||
); | |||
List<DuplicationsParser.Block> blocks = newArrayList(new DuplicationsParser.Block(newArrayList(new DuplicationsParser.Duplication(componentDto, 1, 2)))); | |||
when(parser.parse(componentDto, data, session)).thenReturn(blocks); | |||
WsTester.TestRequest request = tester.newGetRequest("api/duplications", "show").setParam("key", componentKey); | |||
request.execute(); | |||
verify(duplicationsJsonWriter).write(eq(blocks), any(JsonWriter.class), eq(session)); | |||
public void get_duplications_by_file_key() throws Exception { | |||
WsTester.TestRequest request = newBaseRequest(); | |||
verifyCallToFileWithDuplications(file -> request.setParam("key", file.key())); | |||
} | |||
@Test | |||
public void show_duplications_by_uuid() throws Exception { | |||
String uuid = "ABCD"; | |||
String componentKey = "src/Foo.java"; | |||
userSessionRule.addComponentPermission(UserRole.CODEVIEWER, "org.codehaus.sonar:sonar", componentKey); | |||
ComponentDto componentDto = new ComponentDto().setId(10L).setKey(componentKey); | |||
when(componentDao.selectByUuid(session, uuid)).thenReturn(Optional.of(componentDto)); | |||
public void get_duplications_by_file_id() throws Exception { | |||
WsTester.TestRequest request = newBaseRequest(); | |||
verifyCallToFileWithDuplications(file -> request.setParam("uuid", file.uuid())); | |||
} | |||
String data = "{duplications}"; | |||
when(measureDao.selectSingle(eq(session), any(MeasureQuery.class))).thenReturn( | |||
java.util.Optional.of(new MeasureDto().setData("{duplications}")) | |||
); | |||
@Test | |||
public void return_file_with_missing_duplication_data() throws Exception { | |||
ComponentDto project = db.components().insertProject(); | |||
ComponentDto file = db.components().insertComponent(newFileDto(project).setKey("foo.js")); | |||
db.components().insertSnapshot(newAnalysis(project)); | |||
List<DuplicationsParser.Block> blocks = newArrayList(new DuplicationsParser.Block(newArrayList(new DuplicationsParser.Duplication(componentDto, 1, 2)))); | |||
when(parser.parse(componentDto, data, session)).thenReturn(blocks); | |||
userSessionRule.addProjectUuidPermissions(UserRole.CODEVIEWER, project.uuid()); | |||
WsTester.TestRequest request = tester.newGetRequest("api/duplications", "show").setParam("uuid", uuid); | |||
request.execute(); | |||
WsTester.Result result = newBaseRequest().setParam("key", file.key()).execute(); | |||
verify(duplicationsJsonWriter).write(eq(blocks), any(JsonWriter.class), eq(session)); | |||
result.assertJson("{\n" + | |||
" \"duplications\": [],\n" + | |||
" \"files\": {}\n" + | |||
"}"); | |||
} | |||
@Test | |||
public void no_duplications_when_no_data() throws Exception { | |||
String componentKey = "src/Foo.java"; | |||
userSessionRule.addComponentPermission(UserRole.CODEVIEWER, "org.codehaus.sonar:sonar", componentKey); | |||
public void return_404_if_file_does_not_exist() throws Exception { | |||
expectedException.expect(NotFoundException.class); | |||
ComponentDto componentDto = new ComponentDto().setId(10L).setKey(componentKey); | |||
when(componentDao.selectByKey(session, componentKey)).thenReturn(Optional.of(componentDto)); | |||
newBaseRequest().setParam("key", "missing").execute(); | |||
} | |||
when(measureDao.selectSingle(eq(session), any(MeasureQuery.class))).thenReturn(java.util.Optional.empty()); | |||
@Test | |||
public void return_403_if_user_is_not_allowed_to_access_project() throws Exception { | |||
ComponentDto project = db.components().insertProject(); | |||
ComponentDto file = db.components().insertComponent(newFileDto(project)); | |||
WsTester.TestRequest request = tester.newGetRequest("api/duplications", "show").setParam("key", componentKey); | |||
request.execute(); | |||
expectedException.expect(ForbiddenException.class); | |||
verify(duplicationsJsonWriter).write(eq(Lists.newArrayList()), any(JsonWriter.class), eq(session)); | |||
newBaseRequest().setParam("key", file.key()).execute(); | |||
} | |||
@Test(expected = NotFoundException.class) | |||
public void fail_when_file_not_found() throws Exception { | |||
String componentKey = "src/Foo.java"; | |||
when(componentDao.selectByKey(session, componentKey)).thenReturn(Optional.absent()); | |||
WsTester.TestRequest request = tester.newGetRequest("api/duplications", "show").setParam("key", componentKey); | |||
request.execute(); | |||
private WsTester.TestRequest newBaseRequest() { | |||
return tester.newGetRequest("api/duplications", "show"); | |||
} | |||
private void verifyCallToFileWithDuplications(Function<ComponentDto, WsTester.TestRequest> requestFactory) throws Exception { | |||
ComponentDto project = db.components().insertProject(); | |||
ComponentDto file = db.components().insertComponent(newFileDto(project).setKey("foo.js")); | |||
SnapshotDto snapshot = db.components().insertSnapshot(newAnalysis(project)); | |||
String xml = "<duplications>\n" + | |||
" <g>\n" + | |||
" <b s=\"31\" l=\"5\" r=\"foo.js\"/>\n" + | |||
" <b s=\"20\" l=\"5\" r=\"foo.js\"/>\n" + | |||
" </g>\n" + | |||
"</duplications>\n"; | |||
db.getDbClient().measureDao().insert(db.getSession(), newMeasureDto(dataMetric, file, snapshot).setData(xml)); | |||
db.commit(); | |||
userSessionRule.addProjectUuidPermissions(UserRole.CODEVIEWER, project.uuid()); | |||
WsTester.TestRequest request = requestFactory.apply(file); | |||
WsTester.Result result = request.execute(); | |||
result.assertJson("{\"duplications\":[" + | |||
"{\"blocks\":[{\"from\":20,\"size\":5,\"_ref\":\"1\"},{\"from\":31,\"size\":5,\"_ref\":\"1\"}]}]," + | |||
"\"files\":{\"1\":{\"key\":\"foo.js\",\"uuid\":\"" + file.uuid() + "\"}}}"); | |||
} | |||
} |
@@ -33,6 +33,7 @@ import org.sonar.db.DbSession; | |||
import org.sonar.db.DbTester; | |||
import org.sonar.db.component.ComponentDto; | |||
import org.sonar.db.component.ComponentLinkDto; | |||
import org.sonar.db.component.ComponentTesting; | |||
import org.sonar.db.organization.OrganizationDto; | |||
import org.sonar.server.component.ComponentFinder; | |||
import org.sonar.server.exceptions.ForbiddenException; | |||
@@ -65,12 +66,12 @@ public class CreateActionTest { | |||
@Rule | |||
public DbTester db = DbTester.create(System2.INSTANCE); | |||
DbClient dbClient = db.getDbClient(); | |||
DbSession dbSession = db.getSession(); | |||
private DbClient dbClient = db.getDbClient(); | |||
private DbSession dbSession = db.getSession(); | |||
WsActionTester ws; | |||
private WsActionTester ws; | |||
CreateAction underTest; | |||
private CreateAction underTest; | |||
@Before | |||
public void setUp() { | |||
@@ -83,11 +84,11 @@ public class CreateActionTest { | |||
@Test | |||
public void example_with_key() { | |||
insertProject(); | |||
ComponentDto project = insertProject(); | |||
String result = ws.newRequest() | |||
.setMethod("POST") | |||
.setParam(PARAM_PROJECT_KEY, PROJECT_KEY) | |||
.setParam(PARAM_PROJECT_KEY, project.key()) | |||
.setParam(PARAM_NAME, "Custom") | |||
.setParam(PARAM_URL, "http://example.org") | |||
.execute().getInput(); | |||
@@ -97,11 +98,11 @@ public class CreateActionTest { | |||
@Test | |||
public void example_with_id() { | |||
insertProject(); | |||
ComponentDto project = insertProject(); | |||
String result = ws.newRequest() | |||
.setMethod("POST") | |||
.setParam(PARAM_PROJECT_ID, PROJECT_UUID) | |||
.setParam(PARAM_PROJECT_ID, project.uuid()) | |||
.setParam(PARAM_NAME, "Custom") | |||
.setParam(PARAM_URL, "http://example.org") | |||
.execute().getInput(); | |||
@@ -111,26 +112,26 @@ public class CreateActionTest { | |||
@Test | |||
public void global_admin() throws IOException { | |||
userSession.login("login").setGlobalPermissions(SYSTEM_ADMIN); | |||
insertProject(); | |||
createAndTest(); | |||
userSession.login().setGlobalPermissions(SYSTEM_ADMIN); | |||
ComponentDto project = insertProject(); | |||
createAndTest(project); | |||
} | |||
@Test | |||
public void project_admin() throws IOException { | |||
userSession.login("login"); | |||
public void require_project_admin() throws IOException { | |||
userSession.login(); | |||
ComponentDto project = insertProject(); | |||
userSession.addProjectUuidPermissions(UserRole.ADMIN, project.uuid()); | |||
createAndTest(); | |||
createAndTest(project); | |||
} | |||
@Test | |||
public void with_long_name() throws IOException { | |||
insertProject(); | |||
ComponentDto project = insertProject(); | |||
String longName = StringUtils.leftPad("", 60, "a"); | |||
String expectedType = StringUtils.leftPad("", 20, "a"); | |||
createAndTest(longName, "http://example.org", expectedType); | |||
createAndTest(project, longName, "http://example.org", expectedType); | |||
} | |||
@Test | |||
@@ -196,7 +197,7 @@ public class CreateActionTest { | |||
@Test | |||
public void fail_if_not_project_admin() { | |||
userSession.login("login"); | |||
userSession.login(); | |||
insertProject(); | |||
expectedException.expect(ForbiddenException.class); | |||
@@ -208,17 +209,15 @@ public class CreateActionTest { | |||
} | |||
private ComponentDto insertProject() { | |||
OrganizationDto organizationDto = db.organizations().insert(); | |||
return db.components().insertProject( | |||
organizationDto, | |||
(t) -> t.setUuid(PROJECT_UUID) | |||
.setKey(PROJECT_KEY)); | |||
OrganizationDto org = db.organizations().insert(); | |||
return db.components().insertComponent( | |||
ComponentTesting.newProjectDto(org, PROJECT_UUID).setKey(PROJECT_KEY)); | |||
} | |||
private void createAndTest(String name, String url, String type) throws IOException { | |||
private void createAndTest(ComponentDto project, String name, String url, String type) throws IOException { | |||
InputStream responseStream = ws.newRequest() | |||
.setMethod("POST") | |||
.setParam(PARAM_PROJECT_KEY, PROJECT_KEY) | |||
.setParam(PARAM_PROJECT_KEY, project.key()) | |||
.setParam(PARAM_NAME, name) | |||
.setParam(PARAM_URL, url) | |||
.setMediaType(PROTOBUF) | |||
@@ -234,7 +233,7 @@ public class CreateActionTest { | |||
assertThat(link.getType()).isEqualTo(type); | |||
} | |||
private void createAndTest() throws IOException { | |||
createAndTest("Custom", "http://example.org", "custom"); | |||
private void createAndTest(ComponentDto project) throws IOException { | |||
createAndTest(project, "Custom", "http://example.org", "custom"); | |||
} | |||
} |
@@ -77,7 +77,7 @@ public class IndexActionTest { | |||
@Test | |||
public void get_json() throws Exception { | |||
String fileKey = "src/Foo.java"; | |||
userSessionRule.addComponentPermission(UserRole.CODEVIEWER, "polop", fileKey); | |||
userSessionRule.addProjectUuidPermissions(UserRole.CODEVIEWER, project.uuid()); | |||
when(componentDao.selectByKey(session, fileKey)).thenReturn(Optional.of(file)); | |||
when(sourceService.getLinesAsRawText(session, file.uuid(), 1, Integer.MAX_VALUE)).thenReturn(Optional.of((Iterable<String>) newArrayList( | |||
@@ -91,7 +91,7 @@ public class IndexActionTest { | |||
@Test | |||
public void limit_range() throws Exception { | |||
String fileKey = "src/Foo.java"; | |||
userSessionRule.addComponentPermission(UserRole.CODEVIEWER, "polop", fileKey); | |||
userSessionRule.addProjectUuidPermissions(UserRole.CODEVIEWER, project.uuid()); | |||
when(componentDao.selectByKey(session, fileKey)).thenReturn(Optional.of(file)); | |||
when(sourceService.getLinesAsRawText(session, file.uuid(), 1, 2)).thenReturn(Optional.of((Iterable<String>) newArrayList( | |||
@@ -105,13 +105,14 @@ public class IndexActionTest { | |||
@Test(expected = ForbiddenException.class) | |||
public void requires_code_viewer_permission() throws Exception { | |||
tester.newGetRequest("api/sources", "index").setParam("resource", "any").execute(); | |||
when(componentDao.selectByKey(session, "foo")).thenReturn(Optional.of(file)); | |||
tester.newGetRequest("api/sources", "index").setParam("resource", "foo").execute(); | |||
} | |||
@Test | |||
public void close_db_session() throws Exception { | |||
String fileKey = "src/Foo.java"; | |||
userSessionRule.addComponentPermission(UserRole.CODEVIEWER, "polop", fileKey); | |||
userSessionRule.addProjectUuidPermissions(UserRole.CODEVIEWER, project.uuid()); | |||
when(componentDao.selectByKey(session, fileKey)).thenReturn(Optional.<ComponentDto>absent()); | |||
WsTester.TestRequest request = tester.newGetRequest("api/sources", "index").setParam("resource", fileKey); |
@@ -258,7 +258,7 @@ public class UserSessionRule implements TestRule, UserSession { | |||
@Override | |||
public boolean hasComponentPermission(String permission, ComponentDto component) { | |||
return hasComponentUuidPermission(permission, component.projectUuid()); | |||
return currentUserSession.hasComponentPermission(permission, component); | |||
} | |||
@Override |