From 36546f92b77efb3d8597c2f63fd24ac480c2bdcc Mon Sep 17 00:00:00 2001 From: Michal Duda Date: Wed, 14 Oct 2020 12:42:09 +0200 Subject: [PATCH] SONAR-13936 cleanup --- .../db/permission/GroupPermissionDao.java | 4 +- .../db/permission/GroupPermissionMapper.java | 4 +- .../org/sonar/db/user/GroupMembershipDao.java | 9 ++-- .../org/sonar/db/user/LoginGroupCount.java | 4 ++ .../db/permission/AuthorizationDaoTest.java | 8 +-- .../db/permission/GroupPermissionDaoTest.java | 12 ++--- .../server/organization/MemberUpdater.java | 2 - .../sonar/server/permission/ProjectUuid.java | 49 ------------------- .../sonar/server/user/ServerUserSession.java | 12 ++--- .../permission/GroupPermissionChange.java | 5 +- .../permission/GroupPermissionChanger.java | 30 +++++++----- .../server/permission/PermissionChange.java | 15 +++--- .../PermissionPrivilegeChecker.java | 9 ++-- .../permission/UserPermissionChange.java | 3 +- .../permission/UserPermissionChanger.java | 17 ++++--- .../server/permission/ws/AddGroupAction.java | 10 ++-- .../server/permission/ws/AddUserAction.java | 6 +-- .../server/permission/ws/GroupsAction.java | 21 ++++---- .../permission/ws/PermissionWsSupport.java | 27 +++++----- .../server/permission/ws/ProjectWsRef.java | 6 +-- .../permission/ws/RemoveGroupAction.java | 10 ++-- .../permission/ws/RemoveUserAction.java | 7 ++- .../ws/SearchProjectPermissionsAction.java | 9 ++-- .../server/permission/ws/UsersAction.java | 27 ++++++---- .../qualitygate/ws/QualityGatesWsSupport.java | 3 +- .../server/source/ws/LinesJsonWriter.java | 27 +++++----- .../sonar/server/user/ws/CurrentAction.java | 17 +++---- .../server/usergroups/ws/CreateAction.java | 2 +- .../server/usergroups/ws/UpdateAction.java | 13 ++--- .../GroupPermissionChangerTest.java | 45 ++++++++--------- .../permission/UserPermissionChangerTest.java | 30 ++++++------ .../ws/template/CreateTemplateActionTest.java | 2 +- .../user/ws/CurrentActionHomepageTest.java | 20 +++----- .../server/user/ws/CurrentActionTest.java | 24 ++++----- 34 files changed, 222 insertions(+), 267 deletions(-) delete mode 100644 server/sonar-webserver-auth/src/main/java/org/sonar/server/permission/ProjectUuid.java diff --git a/server/sonar-db-dao/src/main/java/org/sonar/db/permission/GroupPermissionDao.java b/server/sonar-db-dao/src/main/java/org/sonar/db/permission/GroupPermissionDao.java index cb4a50c5c90..d6f03a4ff07 100644 --- a/server/sonar-db-dao/src/main/java/org/sonar/db/permission/GroupPermissionDao.java +++ b/server/sonar-db-dao/src/main/java/org/sonar/db/permission/GroupPermissionDao.java @@ -66,14 +66,14 @@ public class GroupPermissionDao implements Dao { * Select global and project permissions of a given group (Anyone group is NOT supported) * Each row returns a {@link GroupPermissionDto} */ - public void selectAllPermissionsByGroupUuid(DbSession dbSession, String groupUuid, ResultHandler resultHandler) { + public void selectAllPermissionsByGroupUuid(DbSession dbSession, String groupUuid, ResultHandler resultHandler) { mapper(dbSession).selectAllPermissionsByGroupUuid(groupUuid, resultHandler); } /** * Each row returns a {@link CountPerProjectPermission} */ - public void groupsCountByComponentUuidAndPermission(DbSession dbSession, List componentUuids, ResultHandler resultHandler) { + public void groupsCountByComponentUuidAndPermission(DbSession dbSession, List componentUuids, ResultHandler resultHandler) { Map parameters = new HashMap<>(2); parameters.put(ANYONE_GROUP_PARAMETER, DefaultGroups.ANYONE); diff --git a/server/sonar-db-dao/src/main/java/org/sonar/db/permission/GroupPermissionMapper.java b/server/sonar-db-dao/src/main/java/org/sonar/db/permission/GroupPermissionMapper.java index 124777c0c6d..1ed0ccdd410 100644 --- a/server/sonar-db-dao/src/main/java/org/sonar/db/permission/GroupPermissionMapper.java +++ b/server/sonar-db-dao/src/main/java/org/sonar/db/permission/GroupPermissionMapper.java @@ -35,7 +35,7 @@ public interface GroupPermissionMapper { List selectByGroupUuids(@Param("groupUuids") List groupUuids, @Nullable @Param("projectUuid") String projectUuid); - void groupsCountByProjectUuidAndPermission(Map parameters, ResultHandler resultHandler); + void groupsCountByProjectUuidAndPermission(Map parameters, ResultHandler resultHandler); void insert(GroupPermissionDto dto); @@ -45,7 +45,7 @@ public interface GroupPermissionMapper { List selectProjectPermissionsOfGroup(@Nullable @Param("groupUuid") String groupUuid, @Param("projectUuid") String projectUuid); - void selectAllPermissionsByGroupUuid(@Param("groupUuid") String groupUuid, ResultHandler resultHandler); + void selectAllPermissionsByGroupUuid(@Param("groupUuid") String groupUuid, ResultHandler resultHandler); /** * Lists uuid of groups with at least one permission on the specified root component but which do not have the specified diff --git a/server/sonar-db-dao/src/main/java/org/sonar/db/user/GroupMembershipDao.java b/server/sonar-db-dao/src/main/java/org/sonar/db/user/GroupMembershipDao.java index 7782d0b1156..fc45086d293 100644 --- a/server/sonar-db-dao/src/main/java/org/sonar/db/user/GroupMembershipDao.java +++ b/server/sonar-db-dao/src/main/java/org/sonar/db/user/GroupMembershipDao.java @@ -33,24 +33,25 @@ import org.sonar.db.DbSession; import static org.sonar.db.DatabaseUtils.executeLargeInputs; public class GroupMembershipDao implements Dao { + private static final String QUERY_PARAM_KEY = "query"; public List selectGroups(DbSession session, GroupMembershipQuery query, String userUuid, int offset, int limit) { - Map params = ImmutableMap.of("query", query, "userUuid", userUuid); + Map params = ImmutableMap.of(QUERY_PARAM_KEY, query, "userUuid", userUuid); return mapper(session).selectGroups(params, new RowBounds(offset, limit)); } public int countGroups(DbSession session, GroupMembershipQuery query, String userUuid) { - Map params = ImmutableMap.of("query", query, "userUuid", userUuid); + Map params = ImmutableMap.of(QUERY_PARAM_KEY, query, "userUuid", userUuid); return mapper(session).countGroups(params); } public List selectMembers(DbSession session, UserMembershipQuery query, int offset, int limit) { - Map params = ImmutableMap.of("query", query, "groupUuid", query.groupUuid()); + Map params = ImmutableMap.of(QUERY_PARAM_KEY, query, "groupUuid", query.groupUuid()); return mapper(session).selectMembers(params, new RowBounds(offset, limit)); } public int countMembers(DbSession session, UserMembershipQuery query) { - Map params = ImmutableMap.of("query", query, "groupUuid", query.groupUuid()); + Map params = ImmutableMap.of(QUERY_PARAM_KEY, query, "groupUuid", query.groupUuid()); return mapper(session).countMembers(params); } diff --git a/server/sonar-db-dao/src/main/java/org/sonar/db/user/LoginGroupCount.java b/server/sonar-db-dao/src/main/java/org/sonar/db/user/LoginGroupCount.java index 06311a14f03..7583c83c3ee 100644 --- a/server/sonar-db-dao/src/main/java/org/sonar/db/user/LoginGroupCount.java +++ b/server/sonar-db-dao/src/main/java/org/sonar/db/user/LoginGroupCount.java @@ -23,6 +23,10 @@ public class LoginGroupCount { private String login; private int groupCount; + public LoginGroupCount() { + // nothing to do here + } + public String login() { return login; } diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/permission/AuthorizationDaoTest.java b/server/sonar-db-dao/src/test/java/org/sonar/db/permission/AuthorizationDaoTest.java index cb551588b3c..9e706a8e89c 100644 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/permission/AuthorizationDaoTest.java +++ b/server/sonar-db-dao/src/test/java/org/sonar/db/permission/AuthorizationDaoTest.java @@ -158,7 +158,7 @@ public class AuthorizationDaoTest { // nobody has the permission assertThat(underTest.countUsersWithGlobalPermissionExcludingGroup(db.getSession(), - "missingPermission", group1.getUuid())).isEqualTo(0); + "missingPermission", group1.getUuid())).isZero(); } @Test @@ -191,7 +191,7 @@ public class AuthorizationDaoTest { // nobody has the permission assertThat(underTest.countUsersWithGlobalPermissionExcludingUser(db.getSession(), - "missingPermission", user1.getUuid())).isEqualTo(0); + "missingPermission", user1.getUuid())).isZero(); } @Test @@ -695,7 +695,7 @@ public class AuthorizationDaoTest { // another permission count = underTest.countUsersWithGlobalPermissionExcludingGroupMember(dbSession, DOES_NOT_EXIST, group1.getUuid(), u2.getUuid()); - assertThat(count).isEqualTo(0); + assertThat(count).isZero(); } @Test @@ -719,7 +719,7 @@ public class AuthorizationDaoTest { // another permission count = underTest.countUsersWithGlobalPermissionExcludingUserPermission(dbSession, DOES_NOT_EXIST, u2.getUuid()); - assertThat(count).isEqualTo(0); + assertThat(count).isZero(); } @Test diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/permission/GroupPermissionDaoTest.java b/server/sonar-db-dao/src/test/java/org/sonar/db/permission/GroupPermissionDaoTest.java index 72883b95728..c10fb8533d1 100644 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/permission/GroupPermissionDaoTest.java +++ b/server/sonar-db-dao/src/test/java/org/sonar/db/permission/GroupPermissionDaoTest.java @@ -59,8 +59,8 @@ public class GroupPermissionDaoTest { @Rule public DbTester db = DbTester.create(System2.INSTANCE); - private DbSession dbSession = db.getSession(); - private GroupPermissionDao underTest = new GroupPermissionDao(); + private final DbSession dbSession = db.getSession(); + private final GroupPermissionDao underTest = new GroupPermissionDao(); @Test public void group_count_by_permission_and_component_id_on_private_projects() { @@ -80,7 +80,7 @@ public class GroupPermissionDaoTest { final List result = new ArrayList<>(); underTest.groupsCountByComponentUuidAndPermission(dbSession, asList(project2.uuid(), project3.uuid(), "789"), - context -> result.add((CountPerProjectPermission) context.getResultObject())); + context -> result.add(context.getResultObject())); assertThat(result).hasSize(3); assertThat(result).extracting("permission").containsOnly(ADMIN, USER); @@ -108,7 +108,7 @@ public class GroupPermissionDaoTest { final List result = new ArrayList<>(); underTest.groupsCountByComponentUuidAndPermission(dbSession, asList(project2.uuid(), project3.uuid(), "789"), - context -> result.add((CountPerProjectPermission) context.getResultObject())); + context -> result.add(context.getResultObject())); assertThat(result).hasSize(3); assertThat(result).extracting("permission").containsOnly("p2", "p3"); @@ -472,7 +472,7 @@ public class GroupPermissionDaoTest { db.users().insertProjectPermissionOnAnyone("perm6", project1); List result = new ArrayList<>(); - underTest.selectAllPermissionsByGroupUuid(dbSession, group1.getUuid(), context -> result.add((GroupPermissionDto) context.getResultObject())); + underTest.selectAllPermissionsByGroupUuid(dbSession, group1.getUuid(), context -> result.add(context.getResultObject())); assertThat(result).extracting(GroupPermissionDto::getComponentUuid, GroupPermissionDto::getRole).containsOnly( tuple(null, "perm2"), tuple(project1.uuid(), "perm3"), tuple(project1.uuid(), "perm4"), tuple(project2.uuid(), "perm5")); @@ -490,7 +490,7 @@ public class GroupPermissionDaoTest { db.users().insertProjectPermissionOnGroup(group1, "perm5", project2); List result = new ArrayList<>(); - underTest.selectAllPermissionsByGroupUuid(dbSession, group1.getUuid(), context -> result.add((GroupPermissionDto) context.getResultObject())); + underTest.selectAllPermissionsByGroupUuid(dbSession, group1.getUuid(), context -> result.add(context.getResultObject())); assertThat(result).extracting(GroupPermissionDto::getComponentUuid, GroupPermissionDto::getRole).containsOnly( tuple(null, "perm2"), tuple(project1.uuid(), "perm3"), tuple(project1.uuid(), "perm4"), tuple(project2.uuid(), "perm5")); diff --git a/server/sonar-webserver-auth/src/main/java/org/sonar/server/organization/MemberUpdater.java b/server/sonar-webserver-auth/src/main/java/org/sonar/server/organization/MemberUpdater.java index 0a8350a72a2..f24d55a9cc0 100644 --- a/server/sonar-webserver-auth/src/main/java/org/sonar/server/organization/MemberUpdater.java +++ b/server/sonar-webserver-auth/src/main/java/org/sonar/server/organization/MemberUpdater.java @@ -135,8 +135,6 @@ public class MemberUpdater { private void removeMemberInDb(DbSession dbSession, OrganizationDto organization, UserDto user) { String userUuid = user.getUuid(); String organizationUuid = organization.getUuid(); - // dbClient.userPermissionDao().deleteOrganizationMemberPermissions(dbSession, userUuid); - //dbClient.permissionTemplateDao().deleteUserPermissionsByOrganization(dbSession, organizationUuid, userUuid); dbClient.propertiesDao().deleteByOrganizationAndUser(dbSession, organizationUuid, userUuid); dbClient.propertiesDao().deleteByOrganizationAndMatchingLogin(dbSession, organizationUuid, user.getLogin(), singletonList(DEFAULT_ISSUE_ASSIGNEE)); diff --git a/server/sonar-webserver-auth/src/main/java/org/sonar/server/permission/ProjectUuid.java b/server/sonar-webserver-auth/src/main/java/org/sonar/server/permission/ProjectUuid.java deleted file mode 100644 index 16b4a0d2d34..00000000000 --- a/server/sonar-webserver-auth/src/main/java/org/sonar/server/permission/ProjectUuid.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2020 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.server.permission; - -import javax.annotation.concurrent.Immutable; -import org.sonar.db.component.ComponentDto; - -import static java.util.Objects.requireNonNull; - -/** - * Reference to a project by its db uuid. - * - */ -@Immutable -public class ProjectUuid { - - private final String uuid; - private final boolean isPrivate; - - public ProjectUuid(ComponentDto project) { - this.uuid = requireNonNull(project.uuid()); - this.isPrivate = project.isPrivate(); - } - - public String getUuid() { - return uuid; - } - - public boolean isPrivate() { - return isPrivate; - } -} diff --git a/server/sonar-webserver-auth/src/main/java/org/sonar/server/user/ServerUserSession.java b/server/sonar-webserver-auth/src/main/java/org/sonar/server/user/ServerUserSession.java index 4f4dabb1fd0..af7a154a72e 100644 --- a/server/sonar-webserver-auth/src/main/java/org/sonar/server/user/ServerUserSession.java +++ b/server/sonar-webserver-auth/src/main/java/org/sonar/server/user/ServerUserSession.java @@ -147,8 +147,8 @@ public class ServerUserSession extends AbstractUserSession { if (permissionsByProjectUuid == null) { permissionsByProjectUuid = new HashMap<>(); } - Set permissions = permissionsByProjectUuid.computeIfAbsent(projectUuid, this::loadProjectPermissions); - return permissions.contains(permission); + Set projectPermissions = permissionsByProjectUuid.computeIfAbsent(projectUuid, this::loadProjectPermissions); + return projectPermissions.contains(permission); } /** @@ -163,10 +163,10 @@ public class ServerUserSession extends AbstractUserSession { if (component.get().isPrivate()) { return loadDbPermissions(dbSession, projectUuid); } - Set permissions = new HashSet<>(); - permissions.addAll(PUBLIC_PERMISSIONS); - permissions.addAll(loadDbPermissions(dbSession, projectUuid)); - return Collections.unmodifiableSet(permissions); + Set projectPermissions = new HashSet<>(); + projectPermissions.addAll(PUBLIC_PERMISSIONS); + projectPermissions.addAll(loadDbPermissions(dbSession, projectUuid)); + return Collections.unmodifiableSet(projectPermissions); } } diff --git a/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/GroupPermissionChange.java b/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/GroupPermissionChange.java index 5a3a4248b36..aab1652cbe2 100644 --- a/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/GroupPermissionChange.java +++ b/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/GroupPermissionChange.java @@ -20,14 +20,15 @@ package org.sonar.server.permission; import javax.annotation.Nullable; +import org.sonar.db.component.ComponentDto; public class GroupPermissionChange extends PermissionChange { private final GroupUuidOrAnyone group; - public GroupPermissionChange(Operation operation, String permission, @Nullable ProjectUuid projectUuid, + public GroupPermissionChange(Operation operation, String permission, @Nullable ComponentDto project, GroupUuidOrAnyone group, PermissionService permissionService) { - super(operation, permission, projectUuid, permissionService); + super(operation, permission, project, permissionService); this.group = group; } diff --git a/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/GroupPermissionChanger.java b/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/GroupPermissionChanger.java index b10977713f9..507f783462d 100644 --- a/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/GroupPermissionChanger.java +++ b/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/GroupPermissionChanger.java @@ -24,8 +24,10 @@ import org.sonar.core.permission.GlobalPermissions; import org.sonar.core.util.UuidFactory; import org.sonar.db.DbClient; import org.sonar.db.DbSession; +import org.sonar.db.component.ComponentDto; import org.sonar.db.permission.GroupPermissionDto; +import static com.google.common.base.Preconditions.checkNotNull; import static java.lang.String.format; import static org.sonar.api.web.UserRole.PUBLIC_PERMISSIONS; import static org.sonar.core.permission.GlobalPermissions.SYSTEM_ADMIN; @@ -59,47 +61,49 @@ public class GroupPermissionChanger { } private static boolean isImplicitlyAlreadyDone(GroupPermissionChange change) { - if (change.getProject() != null) { - return isImplicitlyAlreadyDone(change.getProject(), change); + ComponentDto project = change.getProject(); + if (project != null) { + return isImplicitlyAlreadyDone(project, change); } return false; } - private static boolean isImplicitlyAlreadyDone(ProjectUuid project, GroupPermissionChange change) { + private static boolean isImplicitlyAlreadyDone(ComponentDto project, GroupPermissionChange change) { return isAttemptToAddPublicPermissionToPublicComponent(change, project) || isAttemptToRemovePermissionFromAnyoneOnPrivateComponent(change, project); } - private static boolean isAttemptToAddPublicPermissionToPublicComponent(GroupPermissionChange change, ProjectUuid project) { + private static boolean isAttemptToAddPublicPermissionToPublicComponent(GroupPermissionChange change, ComponentDto project) { return !project.isPrivate() && change.getOperation() == ADD && PUBLIC_PERMISSIONS.contains(change.getPermission()); } - private static boolean isAttemptToRemovePermissionFromAnyoneOnPrivateComponent(GroupPermissionChange change, ProjectUuid project) { + private static boolean isAttemptToRemovePermissionFromAnyoneOnPrivateComponent(GroupPermissionChange change, ComponentDto project) { return project.isPrivate() && change.getOperation() == REMOVE && change.getGroupUuidOrAnyone().isAnyone(); } private static void ensureConsistencyWithVisibility(GroupPermissionChange change) { - if (change.getProject() != null) { + ComponentDto project = change.getProject(); + if (project != null) { checkRequest( - !isAttemptToAddPermissionToAnyoneOnPrivateComponent(change, change.getProject()), + !isAttemptToAddPermissionToAnyoneOnPrivateComponent(change, project), "No permission can be granted to Anyone on a private component"); checkRequest( - !isAttemptToRemovePublicPermissionFromPublicComponent(change, change.getProject()), + !isAttemptToRemovePublicPermissionFromPublicComponent(change, project), "Permission %s can't be removed from a public component", change.getPermission()); } } - private static boolean isAttemptToAddPermissionToAnyoneOnPrivateComponent(GroupPermissionChange change, ProjectUuid project) { + private static boolean isAttemptToAddPermissionToAnyoneOnPrivateComponent(GroupPermissionChange change, ComponentDto project) { return project.isPrivate() && change.getOperation() == ADD && change.getGroupUuidOrAnyone().isAnyone(); } - private static boolean isAttemptToRemovePublicPermissionFromPublicComponent(GroupPermissionChange change, ProjectUuid project) { + private static boolean isAttemptToRemovePublicPermissionFromPublicComponent(GroupPermissionChange change, ComponentDto project) { return !project.isPrivate() && change.getOperation() == REMOVE && PUBLIC_PERMISSIONS.contains(change.getPermission()); @@ -149,11 +153,13 @@ public class GroupPermissionChanger { } private void checkIfRemainingGlobalAdministrators(DbSession dbSession, GroupPermissionChange change) { + GroupUuidOrAnyone groupUuidOrAnyone = change.getGroupUuidOrAnyone(); if (SYSTEM_ADMIN.equals(change.getPermission()) && - !change.getGroupUuidOrAnyone().isAnyone() && + !groupUuidOrAnyone.isAnyone() && change.getProjectUuid() == null) { + String groupUuid = checkNotNull(groupUuidOrAnyone.getUuid()); // removing global admin permission from group - int remaining = dbClient.authorizationDao().countUsersWithGlobalPermissionExcludingGroup(dbSession, SYSTEM_ADMIN, change.getGroupUuidOrAnyone().getUuid()); + int remaining = dbClient.authorizationDao().countUsersWithGlobalPermissionExcludingGroup(dbSession, SYSTEM_ADMIN, groupUuid); checkRequest(remaining > 0, "Last group with permission '%s'. Permission cannot be removed.", SYSTEM_ADMIN); } } diff --git a/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/PermissionChange.java b/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/PermissionChange.java index 6fb19618a73..573f085de5e 100644 --- a/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/PermissionChange.java +++ b/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/PermissionChange.java @@ -21,6 +21,7 @@ package org.sonar.server.permission; import javax.annotation.CheckForNull; import javax.annotation.Nullable; +import org.sonar.db.component.ComponentDto; import org.sonar.db.permission.GlobalPermission; import static java.util.Objects.requireNonNull; @@ -35,15 +36,15 @@ public abstract class PermissionChange { private final Operation operation; private final String permission; - private final ProjectUuid projectUuid; + private final ComponentDto project; protected final PermissionService permissionService; - public PermissionChange(Operation operation, String permission, @Nullable ProjectUuid projectUuid, PermissionService permissionService) { + protected PermissionChange(Operation operation, String permission, @Nullable ComponentDto project, PermissionService permissionService) { this.operation = requireNonNull(operation); this.permission = requireNonNull(permission); - this.projectUuid = projectUuid; + this.project = project; this.permissionService = permissionService; - if (projectUuid == null) { + if (project == null) { checkRequest(permissionService.getGlobalPermissions().stream().anyMatch(p -> p.getKey().equals(permission)), "Invalid global permission '%s'. Valid values are %s", permission, permissionService.getGlobalPermissions().stream().map(GlobalPermission::getKey).collect(toList())); @@ -62,12 +63,12 @@ public abstract class PermissionChange { } @CheckForNull - public ProjectUuid getProject() { - return projectUuid; + public ComponentDto getProject() { + return project; } @CheckForNull public String getProjectUuid() { - return projectUuid == null ? null : projectUuid.getUuid(); + return project == null ? null : project.uuid(); } } diff --git a/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/PermissionPrivilegeChecker.java b/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/PermissionPrivilegeChecker.java index eb130d0910d..4e839ae9311 100644 --- a/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/PermissionPrivilegeChecker.java +++ b/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/PermissionPrivilegeChecker.java @@ -19,8 +19,9 @@ */ package org.sonar.server.permission; -import java.util.Optional; +import javax.annotation.Nullable; import org.sonar.api.web.UserRole; +import org.sonar.db.component.ComponentDto; import org.sonar.db.permission.GlobalPermission; import org.sonar.server.user.UserSession; @@ -41,15 +42,15 @@ public class PermissionPrivilegeChecker { * Checks that user is administrator of the specified project * @throws org.sonar.server.exceptions.ForbiddenException if user is not administrator */ - public static void checkProjectAdmin(UserSession userSession, Optional projectUuid) { + public static void checkProjectAdmin(UserSession userSession, @Nullable ComponentDto componentDto) { userSession.checkLoggedIn(); if (userSession.hasPermission(GlobalPermission.ADMINISTER)) { return; } - if (projectUuid.isPresent()) { - userSession.checkComponentUuidPermission(UserRole.ADMIN, projectUuid.get().getUuid()); + if (componentDto != null) { + userSession.checkComponentPermission(UserRole.ADMIN, componentDto); } else { throw insufficientPrivilegesException(); } diff --git a/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/UserPermissionChange.java b/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/UserPermissionChange.java index 46873260573..992ffbc76d6 100644 --- a/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/UserPermissionChange.java +++ b/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/UserPermissionChange.java @@ -20,6 +20,7 @@ package org.sonar.server.permission; import javax.annotation.Nullable; +import org.sonar.db.component.ComponentDto; import static java.util.Objects.requireNonNull; @@ -27,7 +28,7 @@ public class UserPermissionChange extends PermissionChange { private final UserId userId; - public UserPermissionChange(Operation operation, String permission, @Nullable ProjectUuid project, UserId userId, PermissionService permissionService) { + public UserPermissionChange(Operation operation, String permission, @Nullable ComponentDto project, UserId userId, PermissionService permissionService) { super(operation, permission, project, permissionService); this.userId = requireNonNull(userId); } diff --git a/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/UserPermissionChanger.java b/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/UserPermissionChanger.java index de6eb0c12b0..5c7415ebfe1 100644 --- a/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/UserPermissionChanger.java +++ b/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/UserPermissionChanger.java @@ -23,6 +23,7 @@ import java.util.List; import org.sonar.core.util.UuidFactory; import org.sonar.db.DbClient; import org.sonar.db.DbSession; +import org.sonar.db.component.ComponentDto; import org.sonar.db.permission.UserPermissionDto; import static org.sonar.api.web.UserRole.PUBLIC_PERMISSIONS; @@ -60,30 +61,32 @@ public class UserPermissionChanger { } private static boolean isImplicitlyAlreadyDone(UserPermissionChange change) { - if (change.getProject() != null) { - return isImplicitlyAlreadyDone(change.getProject(), change); + ComponentDto project = change.getProject(); + if (project != null) { + return isImplicitlyAlreadyDone(project, change); } return false; } - private static boolean isImplicitlyAlreadyDone(ProjectUuid project, UserPermissionChange change) { + private static boolean isImplicitlyAlreadyDone(ComponentDto project, UserPermissionChange change) { return isAttemptToAddPublicPermissionToPublicComponent(change, project); } - private static boolean isAttemptToAddPublicPermissionToPublicComponent(UserPermissionChange change, ProjectUuid project) { + private static boolean isAttemptToAddPublicPermissionToPublicComponent(UserPermissionChange change, ComponentDto project) { return !project.isPrivate() && change.getOperation() == ADD && PUBLIC_PERMISSIONS.contains(change.getPermission()); } private static void ensureConsistencyWithVisibility(UserPermissionChange change) { - if (change.getProject() != null) { - checkRequest(!isAttemptToRemovePublicPermissionFromPublicComponent(change, change.getProject()), + ComponentDto project = change.getProject(); + if (project != null) { + checkRequest(!isAttemptToRemovePublicPermissionFromPublicComponent(change, project), "Permission %s can't be removed from a public component", change.getPermission()); } } - private static boolean isAttemptToRemovePublicPermissionFromPublicComponent(UserPermissionChange change, ProjectUuid projectUuid) { + private static boolean isAttemptToRemovePublicPermissionFromPublicComponent(UserPermissionChange change, ComponentDto projectUuid) { return !projectUuid.isPrivate() && change.getOperation() == REMOVE && PUBLIC_PERMISSIONS.contains(change.getPermission()); diff --git a/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/ws/AddGroupAction.java b/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/ws/AddGroupAction.java index e77f8629cf8..ee494f11951 100644 --- a/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/ws/AddGroupAction.java +++ b/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/ws/AddGroupAction.java @@ -27,12 +27,12 @@ import org.sonar.api.server.ws.Response; import org.sonar.api.server.ws.WebService; import org.sonar.db.DbClient; import org.sonar.db.DbSession; +import org.sonar.db.component.ComponentDto; import org.sonar.server.permission.GroupPermissionChange; import org.sonar.server.permission.GroupUuidOrAnyone; import org.sonar.server.permission.PermissionChange; import org.sonar.server.permission.PermissionService; import org.sonar.server.permission.PermissionUpdater; -import org.sonar.server.permission.ProjectUuid; import org.sonar.server.user.UserSession; import static org.sonar.server.permission.PermissionPrivilegeChecker.checkProjectAdmin; @@ -89,14 +89,12 @@ public class AddGroupAction implements PermissionsWsAction { public void handle(Request request, Response response) throws Exception { try (DbSession dbSession = dbClient.openSession(false)) { GroupUuidOrAnyone group = wsSupport.findGroup(dbSession, request); - Optional projectUuid = wsSupport.findProjectUuid(dbSession, request); - - checkProjectAdmin(userSession, projectUuid); - + Optional project = wsSupport.findProject(dbSession, request); + checkProjectAdmin(userSession, project.orElse(null)); PermissionChange change = new GroupPermissionChange( PermissionChange.Operation.ADD, request.mandatoryParam(PARAM_PERMISSION), - projectUuid.orElse(null), + project.orElse(null), group, permissionService); permissionUpdater.apply(dbSession, ImmutableList.of(change)); } diff --git a/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/ws/AddUserAction.java b/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/ws/AddUserAction.java index e0f0b34f2e6..dacd8d3449e 100644 --- a/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/ws/AddUserAction.java +++ b/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/ws/AddUserAction.java @@ -30,7 +30,6 @@ import org.sonar.db.component.ComponentDto; import org.sonar.server.permission.PermissionChange; import org.sonar.server.permission.PermissionService; import org.sonar.server.permission.PermissionUpdater; -import org.sonar.server.permission.ProjectUuid; import org.sonar.server.permission.UserId; import org.sonar.server.permission.UserPermissionChange; import org.sonar.server.user.UserSession; @@ -89,13 +88,12 @@ public class AddUserAction implements PermissionsWsAction { try (DbSession dbSession = dbClient.openSession(false)) { UserId user = wsSupport.findUser(dbSession, request.mandatoryParam(PARAM_USER_LOGIN)); Optional project = wsSupport.findProject(dbSession, request); - Optional projectUuid = project.map(ProjectUuid::new); - checkProjectAdmin(userSession, projectUuid); + checkProjectAdmin(userSession, project.orElse(null)); PermissionChange change = new UserPermissionChange( PermissionChange.Operation.ADD, request.mandatoryParam(PARAM_PERMISSION), - projectUuid.orElse(null), + project.orElse(null), user, permissionService); permissionUpdater.apply(dbSession, singletonList(change)); } diff --git a/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/ws/GroupsAction.java b/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/ws/GroupsAction.java index 24d1e64148a..cf5f7569d6e 100644 --- a/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/ws/GroupsAction.java +++ b/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/ws/GroupsAction.java @@ -25,6 +25,7 @@ import com.google.common.collect.TreeMultimap; import com.google.common.io.Resources; import java.util.List; import java.util.Optional; +import javax.annotation.Nullable; import org.sonar.api.security.DefaultGroups; import org.sonar.api.server.ws.Change; import org.sonar.api.server.ws.Request; @@ -35,10 +36,10 @@ import org.sonar.api.utils.Paging; import org.sonar.core.util.stream.MoreCollectors; import org.sonar.db.DbClient; import org.sonar.db.DbSession; +import org.sonar.db.component.ComponentDto; import org.sonar.db.permission.GroupPermissionDto; import org.sonar.db.permission.PermissionQuery; import org.sonar.db.user.GroupDto; -import org.sonar.server.permission.ProjectUuid; import org.sonar.server.user.UserSession; import org.sonarqube.ws.Permissions.Group; import org.sonarqube.ws.Permissions.WsGroupsResponse; @@ -97,27 +98,29 @@ public class GroupsAction implements PermissionsWsAction { @Override public void handle(Request request, Response response) throws Exception { try (DbSession dbSession = dbClient.openSession(false)) { - Optional project = wsSupport.findProjectUuid(dbSession, request); - checkProjectAdmin(userSession, project); + Optional project = wsSupport.findProject(dbSession, request); + checkProjectAdmin(userSession, project.orElse(null)); - PermissionQuery query = buildPermissionQuery(request, project); + PermissionQuery query = buildPermissionQuery(request, project.orElse(null)); List groups = findGroups(dbSession, query); int total = dbClient.groupPermissionDao().countGroupsByQuery(dbSession, query); - List groupsWithPermission = findGroupPermissions(dbSession, groups, project); + List groupsWithPermission = findGroupPermissions(dbSession, groups, project.orElse(null)); Paging paging = Paging.forPageIndex(request.mandatoryParamAsInt(Param.PAGE)).withPageSize(query.getPageSize()).andTotal(total); WsGroupsResponse groupsResponse = buildResponse(groups, groupsWithPermission, paging); writeProtobuf(groupsResponse, request, response); } } - private static PermissionQuery buildPermissionQuery(Request request, Optional project) { + private static PermissionQuery buildPermissionQuery(Request request, @Nullable ComponentDto project) { String textQuery = request.param(Param.TEXT_QUERY); PermissionQuery.Builder permissionQuery = PermissionQuery.builder() .setPermission(request.param(PARAM_PERMISSION)) .setPageIndex(request.mandatoryParamAsInt(Param.PAGE)) .setPageSize(request.mandatoryParamAsInt(Param.PAGE_SIZE)) .setSearchQuery(textQuery); - project.ifPresent(projectUuid -> permissionQuery.setComponent(projectUuid.getUuid())); + if (project != null) { + permissionQuery.setComponent(project.uuid()); + } return permissionQuery.build(); } @@ -153,11 +156,11 @@ public class GroupsAction implements PermissionsWsAction { return Ordering.explicit(orderedNames).onResultOf(GroupDto::getName).immutableSortedCopy(groups); } - private List findGroupPermissions(DbSession dbSession, List groups, Optional project) { + private List findGroupPermissions(DbSession dbSession, List groups, @Nullable ComponentDto project) { if (groups.isEmpty()) { return emptyList(); } List uuids = groups.stream().map(GroupDto::getUuid).collect(MoreCollectors.toList(groups.size())); - return dbClient.groupPermissionDao().selectByGroupUuids(dbSession, uuids, project.map(ProjectUuid::getUuid).orElse(null)); + return dbClient.groupPermissionDao().selectByGroupUuids(dbSession, uuids, project != null ? project.uuid() : null); } } diff --git a/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/ws/PermissionWsSupport.java b/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/ws/PermissionWsSupport.java index 92839b63154..1622026a41d 100644 --- a/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/ws/PermissionWsSupport.java +++ b/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/ws/PermissionWsSupport.java @@ -27,14 +27,17 @@ import org.sonar.db.component.ComponentDto; import org.sonar.db.permission.template.PermissionTemplateDto; import org.sonar.db.user.UserDto; import org.sonar.server.component.ComponentFinder; +import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.permission.GroupUuidOrAnyone; -import org.sonar.server.permission.ProjectUuid; import org.sonar.server.permission.UserId; import org.sonar.server.permission.ws.template.WsTemplateRef; import org.sonar.server.usergroups.ws.GroupWsRef; import org.sonar.server.usergroups.ws.GroupWsSupport; import org.sonarqube.ws.client.permission.PermissionsWsParameters; +import static com.google.common.base.Preconditions.checkNotNull; +import static java.lang.String.format; +import static java.util.Optional.ofNullable; import static org.sonar.server.exceptions.NotFoundException.checkFound; import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_GROUP_ID; import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_GROUP_NAME; @@ -51,11 +54,6 @@ public class PermissionWsSupport { this.groupWsSupport = groupWsSupport; } - public Optional findProjectUuid(DbSession dbSession, Request request) { - return findProject(dbSession, request) - .map(ProjectUuid::new); - } - public Optional findProject(DbSession dbSession, Request request) { String uuid = request.param(PermissionsWsParameters.PARAM_PROJECT_ID); String key = request.param(PermissionsWsParameters.PARAM_PROJECT_KEY); @@ -78,20 +76,23 @@ public class PermissionWsSupport { } public UserId findUser(DbSession dbSession, String login) { - UserDto dto = dbClient.userDao().selectActiveUserByLogin(dbSession, login); - checkFound(dto, "User with login '%s' is not found'", login); + UserDto dto = ofNullable(dbClient.userDao().selectActiveUserByLogin(dbSession, login)) + .orElseThrow(() -> new NotFoundException(format("User with login '%s' is not found'", login))); return new UserId(dto.getUuid(), dto.getLogin()); } public PermissionTemplateDto findTemplate(DbSession dbSession, WsTemplateRef ref) { - if (ref.uuid() != null) { + String uuid = ref.uuid(); + String name = ref.name(); + if (uuid != null) { return checkFound( - dbClient.permissionTemplateDao().selectByUuid(dbSession, ref.uuid()), - "Permission template with id '%s' is not found", ref.uuid()); + dbClient.permissionTemplateDao().selectByUuid(dbSession, uuid), + "Permission template with id '%s' is not found", uuid); } else { + checkNotNull(name); return checkFound( - dbClient.permissionTemplateDao().selectByName(dbSession, ref.name()), - "Permission template with name '%s' is not found (case insensitive)", ref.name()); + dbClient.permissionTemplateDao().selectByName(dbSession, name), + "Permission template with name '%s' is not found (case insensitive)", name); } } diff --git a/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/ws/ProjectWsRef.java b/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/ws/ProjectWsRef.java index 84a7ce8c0d5..68336d7492e 100644 --- a/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/ws/ProjectWsRef.java +++ b/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/ws/ProjectWsRef.java @@ -19,7 +19,7 @@ */ package org.sonar.server.permission.ws; -import com.google.common.base.Optional; +import java.util.Optional; import javax.annotation.CheckForNull; import javax.annotation.Nullable; @@ -27,7 +27,7 @@ import static org.sonar.server.exceptions.BadRequestException.checkRequest; /** * Reference to a project as defined by web service callers. It allows to reference a project - * by its (functional) key or by its (technical) id. It's then converted to {@link org.sonar.server.permission.ProjectId}. + * by its (functional) key or by its (technical) uuid. * *

Factory methods guarantee that the project id and project key are not provided at the same time.

*/ @@ -44,7 +44,7 @@ public class ProjectWsRef { public static Optional newOptionalWsProjectRef(@Nullable String uuid, @Nullable String key) { if (uuid == null && key == null) { - return Optional.absent(); + return Optional.empty(); } return Optional.of(new ProjectWsRef(uuid, key)); diff --git a/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/ws/RemoveGroupAction.java b/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/ws/RemoveGroupAction.java index efdfe5062de..27cce85719f 100644 --- a/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/ws/RemoveGroupAction.java +++ b/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/ws/RemoveGroupAction.java @@ -26,15 +26,15 @@ import org.sonar.api.server.ws.Response; import org.sonar.api.server.ws.WebService; import org.sonar.db.DbClient; import org.sonar.db.DbSession; +import org.sonar.db.component.ComponentDto; import org.sonar.server.permission.GroupPermissionChange; import org.sonar.server.permission.GroupUuidOrAnyone; import org.sonar.server.permission.PermissionChange; import org.sonar.server.permission.PermissionService; import org.sonar.server.permission.PermissionUpdater; -import org.sonar.server.permission.ProjectUuid; import org.sonar.server.user.UserSession; -import static java.util.Arrays.asList; +import static java.util.Collections.singletonList; import static org.sonar.server.permission.PermissionPrivilegeChecker.checkProjectAdmin; import static org.sonar.server.permission.ws.WsParameters.createGroupIdParameter; import static org.sonar.server.permission.ws.WsParameters.createGroupNameParameter; @@ -89,16 +89,16 @@ public class RemoveGroupAction implements PermissionsWsAction { public void handle(Request request, Response response) throws Exception { try (DbSession dbSession = dbClient.openSession(false)) { GroupUuidOrAnyone group = wsSupport.findGroup(dbSession, request); - Optional project = wsSupport.findProjectUuid(dbSession, request); + Optional project = wsSupport.findProject(dbSession, request); - checkProjectAdmin(userSession, project); + checkProjectAdmin(userSession, project.orElse(null)); PermissionChange change = new GroupPermissionChange( PermissionChange.Operation.REMOVE, request.mandatoryParam(PARAM_PERMISSION), project.orElse(null), group, permissionService); - permissionUpdater.apply(dbSession, asList(change)); + permissionUpdater.apply(dbSession, singletonList(change)); } response.noContent(); } diff --git a/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/ws/RemoveUserAction.java b/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/ws/RemoveUserAction.java index 037f48a30ca..73a0abc3029 100644 --- a/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/ws/RemoveUserAction.java +++ b/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/ws/RemoveUserAction.java @@ -25,10 +25,10 @@ import org.sonar.api.server.ws.Response; import org.sonar.api.server.ws.WebService; import org.sonar.db.DbClient; import org.sonar.db.DbSession; +import org.sonar.db.component.ComponentDto; import org.sonar.server.permission.PermissionChange; import org.sonar.server.permission.PermissionService; import org.sonar.server.permission.PermissionUpdater; -import org.sonar.server.permission.ProjectUuid; import org.sonar.server.permission.UserId; import org.sonar.server.permission.UserPermissionChange; import org.sonar.server.user.UserSession; @@ -84,9 +84,8 @@ public class RemoveUserAction implements PermissionsWsAction { public void handle(Request request, Response response) throws Exception { try (DbSession dbSession = dbClient.openSession(false)) { UserId user = wsSupport.findUser(dbSession, request.mandatoryParam(PARAM_USER_LOGIN)); - Optional project = wsSupport.findProjectUuid(dbSession, request); - checkProjectAdmin(userSession, project); - + Optional project = wsSupport.findProject(dbSession, request); + checkProjectAdmin(userSession, project.orElse(null)); PermissionChange change = new UserPermissionChange( PermissionChange.Operation.REMOVE, request.mandatoryParam(PARAM_PERMISSION), diff --git a/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/ws/SearchProjectPermissionsAction.java b/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/ws/SearchProjectPermissionsAction.java index e096ee11bbb..b952d711f07 100644 --- a/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/ws/SearchProjectPermissionsAction.java +++ b/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/ws/SearchProjectPermissionsAction.java @@ -43,7 +43,6 @@ import org.sonar.db.component.ComponentQuery; import org.sonar.db.permission.CountPerProjectPermission; import org.sonar.server.permission.PermissionPrivilegeChecker; import org.sonar.server.permission.PermissionService; -import org.sonar.server.permission.ProjectUuid; import org.sonar.server.permission.RequestValidator; import org.sonar.server.user.UserSession; import org.sonarqube.ws.Common; @@ -56,8 +55,8 @@ import static org.sonar.api.utils.Paging.forPageIndex; import static org.sonar.server.permission.ws.ProjectWsRef.newOptionalWsProjectRef; import static org.sonar.server.permission.ws.SearchProjectPermissionsData.newBuilder; import static org.sonar.server.permission.ws.WsParameters.createProjectParameters; -import static org.sonar.server.ws.WsParameterBuilder.QualifierParameterContext.newQualifierParameterContext; import static org.sonar.server.ws.WsParameterBuilder.createRootQualifierParameter; +import static org.sonar.server.ws.WsParameterBuilder.QualifierParameterContext.newQualifierParameterContext; import static org.sonar.server.ws.WsUtils.writeProtobuf; import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_PROJECT_ID; import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_PROJECT_KEY; @@ -138,10 +137,10 @@ public class SearchProjectPermissionsAction implements PermissionsWsAction { } private void checkAuthorized(DbSession dbSession, SearchProjectPermissionsRequest request) { - com.google.common.base.Optional projectRef = newOptionalWsProjectRef(request.getProjectId(), request.getProjectKey()); + Optional projectRef = newOptionalWsProjectRef(request.getProjectId(), request.getProjectKey()); if (projectRef.isPresent()) { ComponentDto project = wsSupport.getRootComponentOrModule(dbSession, projectRef.get()); - PermissionPrivilegeChecker.checkProjectAdmin(userSession, Optional.of(new ProjectUuid(project))); + PermissionPrivilegeChecker.checkProjectAdmin(userSession, project); } else { userSession.checkLoggedIn().checkIsSystemAdministrator(); } @@ -222,7 +221,7 @@ public class SearchProjectPermissionsAction implements PermissionsWsAction { } private List searchRootComponents(DbSession dbSession, SearchProjectPermissionsRequest request, Paging paging) { - com.google.common.base.Optional project = newOptionalWsProjectRef(request.getProjectId(), request.getProjectKey()); + Optional project = newOptionalWsProjectRef(request.getProjectId(), request.getProjectKey()); if (project.isPresent()) { return singletonList(wsSupport.getRootComponentOrModule(dbSession, project.get())); diff --git a/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/ws/UsersAction.java b/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/ws/UsersAction.java index 6def62e7aec..72116994f61 100644 --- a/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/ws/UsersAction.java +++ b/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/ws/UsersAction.java @@ -25,6 +25,7 @@ import com.google.common.collect.TreeMultimap; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; +import javax.annotation.Nullable; import org.sonar.api.server.ws.Change; import org.sonar.api.server.ws.Request; import org.sonar.api.server.ws.Response; @@ -33,11 +34,11 @@ import org.sonar.api.server.ws.WebService.Param; import org.sonar.api.utils.Paging; import org.sonar.db.DbClient; import org.sonar.db.DbSession; +import org.sonar.db.component.ComponentDto; import org.sonar.db.permission.PermissionQuery; import org.sonar.db.permission.UserPermissionDto; import org.sonar.db.user.UserDto; import org.sonar.server.issue.AvatarResolver; -import org.sonar.server.permission.ProjectUuid; import org.sonar.server.permission.RequestValidator; import org.sonar.server.user.UserSession; import org.sonarqube.ws.Permissions; @@ -105,20 +106,20 @@ public class UsersAction implements PermissionsWsAction { @Override public void handle(Request request, Response response) throws Exception { try (DbSession dbSession = dbClient.openSession(false)) { - Optional project = wsSupport.findProjectUuid(dbSession, request); - checkProjectAdmin(userSession, project); + Optional project = wsSupport.findProject(dbSession, request); + checkProjectAdmin(userSession, project.orElse(null)); - PermissionQuery query = buildPermissionQuery(request, project); + PermissionQuery query = buildPermissionQuery(request, project.orElse(null)); List users = findUsers(dbSession, query); int total = dbClient.userPermissionDao().countUsersByQuery(dbSession, query); - List userPermissions = findUserPermissions(dbSession, users, project); + List userPermissions = findUserPermissions(dbSession, users, project.orElse(null)); Paging paging = Paging.forPageIndex(request.mandatoryParamAsInt(Param.PAGE)).withPageSize(query.getPageSize()).andTotal(total); UsersWsResponse usersWsResponse = buildResponse(users, userPermissions, paging); writeProtobuf(usersWsResponse, request, response); } } - private PermissionQuery buildPermissionQuery(Request request, Optional project) { + private PermissionQuery buildPermissionQuery(Request request, @Nullable ComponentDto project) { String textQuery = request.param(Param.TEXT_QUERY); String permission = request.param(PARAM_PERMISSION); PermissionQuery.Builder permissionQuery = PermissionQuery.builder() @@ -126,9 +127,13 @@ public class UsersAction implements PermissionsWsAction { .setPageIndex(request.mandatoryParamAsInt(Param.PAGE)) .setPageSize(request.mandatoryParamAsInt(Param.PAGE_SIZE)) .setSearchQuery(textQuery); - project.ifPresent(projectId -> permissionQuery.setComponent(projectId.getUuid())); + + if (project != null) { + permissionQuery.setComponent(project.uuid()); + } + if (permission != null) { - if (project.isPresent()) { + if (project != null) { requestValidator.validateProjectPermission(permission); } else { validateGlobalPermission(permission); @@ -166,14 +171,16 @@ public class UsersAction implements PermissionsWsAction { return Ordering.explicit(orderedUuids).onResultOf(UserDto::getUuid).immutableSortedCopy(dbClient.userDao().selectByUuids(dbSession, orderedUuids)); } - private List findUserPermissions(DbSession dbSession, List users, Optional project) { + private List findUserPermissions(DbSession dbSession, List users, @Nullable ComponentDto project) { if (users.isEmpty()) { return emptyList(); } List userUuids = users.stream().map(UserDto::getUuid).collect(Collectors.toList()); PermissionQuery.Builder queryBuilder = PermissionQuery.builder() .withAtLeastOnePermission(); - project.ifPresent(p -> queryBuilder.setComponent(p.getUuid())); + if (project != null) { + queryBuilder.setComponent(project.uuid()); + } return dbClient.userPermissionDao().selectUserPermissionsByQuery(dbSession, queryBuilder.build(), userUuids); } } diff --git a/server/sonar-webserver-webapi/src/main/java/org/sonar/server/qualitygate/ws/QualityGatesWsSupport.java b/server/sonar-webserver-webapi/src/main/java/org/sonar/server/qualitygate/ws/QualityGatesWsSupport.java index bbd8b093a62..1c6b7216fd0 100644 --- a/server/sonar-webserver-webapi/src/main/java/org/sonar/server/qualitygate/ws/QualityGatesWsSupport.java +++ b/server/sonar-webserver-webapi/src/main/java/org/sonar/server/qualitygate/ws/QualityGatesWsSupport.java @@ -111,8 +111,7 @@ public class QualityGatesWsSupport { OrganizationDto getOrganization(DbSession dbSession, String key) { Optional organizationDto = dbClient.organizationDao().selectByKey(dbSession, key); - OrganizationDto organization = checkFoundWithOptional(organizationDto, "No organization with key '%s'", key); - return organization; + return checkFoundWithOptional(organizationDto, "No organization with key '%s'", key); } OrganizationDto getOrganization(DbSession dbSession, Request request) { diff --git a/server/sonar-webserver-webapi/src/main/java/org/sonar/server/source/ws/LinesJsonWriter.java b/server/sonar-webserver-webapi/src/main/java/org/sonar/server/source/ws/LinesJsonWriter.java index f99122b83f0..64bf8ebacdf 100644 --- a/server/sonar-webserver-webapi/src/main/java/org/sonar/server/source/ws/LinesJsonWriter.java +++ b/server/sonar-webserver-webapi/src/main/java/org/sonar/server/source/ws/LinesJsonWriter.java @@ -47,21 +47,18 @@ public class LinesJsonWriter { if (line.hasScmDate()) { json.prop("scmDate", DateUtils.formatDateTime(new Date(line.getScmDate()))); } - Optional lineHits = getLineHits(line); - if (lineHits.isPresent()) { - json.prop("utLineHits", lineHits.get()); - json.prop("lineHits", lineHits.get()); - } - Optional conditions = getConditions(line); - if (conditions.isPresent()) { - json.prop("utConditions", conditions.get()); - json.prop("conditions", conditions.get()); - } - Optional coveredConditions = getCoveredConditions(line); - if (coveredConditions.isPresent()) { - json.prop("utCoveredConditions", coveredConditions.get()); - json.prop("coveredConditions", coveredConditions.get()); - } + getLineHits(line).ifPresent(lh -> { + json.prop("utLineHits", lh); + json.prop("lineHits", lh); + }); + getConditions(line).ifPresent(conditions -> { + json.prop("utConditions", conditions); + json.prop("conditions", conditions); + }); + getCoveredConditions(line).ifPresent(coveredConditions -> { + json.prop("utCoveredConditions", coveredConditions); + json.prop("coveredConditions", coveredConditions); + }); json.prop("duplicated", line.getDuplicationCount() > 0); if (line.hasIsNewLine()) { json.prop("isNew", line.getIsNewLine()); diff --git a/server/sonar-webserver-webapi/src/main/java/org/sonar/server/user/ws/CurrentAction.java b/server/sonar-webserver-webapi/src/main/java/org/sonar/server/user/ws/CurrentAction.java index 536316eb69f..f28a1735d08 100644 --- a/server/sonar-webserver-webapi/src/main/java/org/sonar/server/user/ws/CurrentAction.java +++ b/server/sonar-webserver-webapi/src/main/java/org/sonar/server/user/ws/CurrentAction.java @@ -37,7 +37,6 @@ import org.sonar.db.permission.GlobalPermission; import org.sonar.db.project.ProjectDto; import org.sonar.db.user.UserDto; import org.sonar.server.issue.AvatarResolver; -import org.sonar.server.organization.DefaultOrganizationProvider; import org.sonar.server.permission.PermissionService; import org.sonar.server.user.UserSession; import org.sonarqube.ws.Users.CurrentWsResponse; @@ -60,20 +59,17 @@ import static org.sonarqube.ws.Users.CurrentWsResponse.HomepageType.PROJECT; import static org.sonarqube.ws.client.user.UsersWsParameters.ACTION_CURRENT; public class CurrentAction implements UsersWsAction { - private final UserSession userSession; private final DbClient dbClient; - private final DefaultOrganizationProvider defaultOrganizationProvider; private final AvatarResolver avatarResolver; private final HomepageTypes homepageTypes; private final PlatformEditionProvider editionProvider; private final PermissionService permissionService; - public CurrentAction(UserSession userSession, DbClient dbClient, DefaultOrganizationProvider defaultOrganizationProvider, - AvatarResolver avatarResolver, HomepageTypes homepageTypes, PlatformEditionProvider editionProvider, PermissionService permissionService) { + public CurrentAction(UserSession userSession, DbClient dbClient, AvatarResolver avatarResolver, HomepageTypes homepageTypes, + PlatformEditionProvider editionProvider, PermissionService permissionService) { this.userSession = userSession; this.dbClient = dbClient; - this.defaultOrganizationProvider = defaultOrganizationProvider; this.avatarResolver = avatarResolver; this.homepageTypes = homepageTypes; this.editionProvider = editionProvider; @@ -101,9 +97,9 @@ public class CurrentAction implements UsersWsAction { } } else { writeProtobuf(newBuilder() - .setIsLoggedIn(false) - .setPermissions(Permissions.newBuilder().addAllGlobal(getGlobalPermissions()).build()) - .build(), + .setIsLoggedIn(false) + .setPermissions(Permissions.newBuilder().addAllGlobal(getGlobalPermissions()).build()) + .build(), request, response); } } @@ -132,9 +128,8 @@ public class CurrentAction implements UsersWsAction { } private List getGlobalPermissions() { - String defaultOrganizationUuid = defaultOrganizationProvider.get().getUuid(); return permissionService.getGlobalPermissions().stream() - .filter(permission -> userSession.hasPermission(permission)) + .filter(userSession::hasPermission) .map(GlobalPermission::getKey) .collect(toList()); } diff --git a/server/sonar-webserver-webapi/src/main/java/org/sonar/server/usergroups/ws/CreateAction.java b/server/sonar-webserver-webapi/src/main/java/org/sonar/server/usergroups/ws/CreateAction.java index 1b860f02350..4fb772f53dc 100644 --- a/server/sonar-webserver-webapi/src/main/java/org/sonar/server/usergroups/ws/CreateAction.java +++ b/server/sonar-webserver-webapi/src/main/java/org/sonar/server/usergroups/ws/CreateAction.java @@ -101,7 +101,7 @@ public class CreateAction implements UserGroupsWsAction { } } - private void writeResponse(Request request, Response response, GroupDto group) { + private static void writeResponse(Request request, Response response, GroupDto group) { UserGroups.CreateWsResponse.Builder respBuilder = UserGroups.CreateWsResponse.newBuilder(); // 'default' is always false as it's not possible to create a default group respBuilder.setGroup(toProtobuf(group, 0, false)); diff --git a/server/sonar-webserver-webapi/src/main/java/org/sonar/server/usergroups/ws/UpdateAction.java b/server/sonar-webserver-webapi/src/main/java/org/sonar/server/usergroups/ws/UpdateAction.java index 11204fa47de..bdea35d89ac 100644 --- a/server/sonar-webserver-webapi/src/main/java/org/sonar/server/usergroups/ws/UpdateAction.java +++ b/server/sonar-webserver-webapi/src/main/java/org/sonar/server/usergroups/ws/UpdateAction.java @@ -29,14 +29,15 @@ import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.user.GroupDto; import org.sonar.db.user.UserMembershipQuery; +import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.user.UserSession; import org.sonarqube.ws.UserGroups; import static java.lang.String.format; +import static java.util.Optional.ofNullable; import static org.sonar.api.user.UserGroupValidation.GROUP_NAME_MAX_LENGTH; import static org.sonar.core.util.Uuids.UUID_EXAMPLE_01; import static org.sonar.db.permission.GlobalPermission.ADMINISTER; -import static org.sonar.server.exceptions.NotFoundException.checkFound; import static org.sonar.server.qualitygate.ws.QualityGatesWsParameters.PARAM_CURRENT_NAME; import static org.sonar.server.usergroups.ws.GroupWsSupport.DESCRIPTION_MAX_LENGTH; import static org.sonar.server.usergroups.ws.GroupWsSupport.PARAM_GROUP_DESCRIPTION; @@ -100,17 +101,17 @@ public class UpdateAction implements UserGroupsWsAction { String groupUuid = request.param(PARAM_GROUP_ID); String currentName = request.param(PARAM_CURRENT_NAME); - if ((groupUuid == null) == (currentName == null)) { + if ((groupUuid == null && currentName == null) || (groupUuid != null && currentName != null)) { throw new IllegalArgumentException(format("Need to specify one and only one of '%s' or '%s'", PARAM_GROUP_ID, PARAM_CURRENT_NAME)); } GroupDto group; if (groupUuid != null) { - group = dbClient.groupDao().selectByUuid(dbSession, groupUuid); - checkFound(group, "Could not find a user group with id '%s'.", groupUuid); + group = ofNullable(dbClient.groupDao().selectByUuid(dbSession, groupUuid)) + .orElseThrow(() -> new NotFoundException(format("Could not find a user group with id '%s'.", groupUuid))); } else { - group = dbClient.groupDao().selectByName(dbSession, currentName).orElse(null); - checkFound(group, "Could not find a user group with name '%s'.", currentName); + group = dbClient.groupDao().selectByName(dbSession, currentName) + .orElseThrow(() -> new NotFoundException(format("Could not find a user group with name '%s'.", currentName))); } userSession.checkPermission(ADMINISTER); diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/GroupPermissionChangerTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/GroupPermissionChangerTest.java index 8d06bddfa35..d75c17e3a96 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/GroupPermissionChangerTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/GroupPermissionChangerTest.java @@ -53,9 +53,9 @@ public class GroupPermissionChangerTest { @Rule public ExpectedException expectedException = ExpectedException.none(); - private ResourceTypes resourceTypes = new ResourceTypesRule().setRootQualifiers(Qualifiers.PROJECT); - private PermissionService permissionService = new PermissionServiceImpl(resourceTypes); - private GroupPermissionChanger underTest = new GroupPermissionChanger(db.getDbClient(), new SequenceUuidFactory()); + private final ResourceTypes resourceTypes = new ResourceTypesRule().setRootQualifiers(Qualifiers.PROJECT); + private final PermissionService permissionService = new PermissionServiceImpl(resourceTypes); + private final GroupPermissionChanger underTest = new GroupPermissionChanger(db.getDbClient(), new SequenceUuidFactory()); private GroupDto group; private ComponentDto privateProject; private ComponentDto publicProject; @@ -90,8 +90,9 @@ public class GroupPermissionChangerTest { GroupUuidOrAnyone anyOneGroup = GroupUuidOrAnyone.forAnyone(); permissionService.getAllProjectPermissions() .forEach(perm -> { + GroupPermissionChange change = new GroupPermissionChange(PermissionChange.Operation.ADD, perm, privateProject, anyOneGroup, permissionService); try { - apply(new GroupPermissionChange(PermissionChange.Operation.ADD, perm, new ProjectUuid(privateProject), anyOneGroup, permissionService)); + apply(change); fail("a BadRequestException should have been thrown"); } catch (BadRequestException e) { assertThat(e).hasMessage("No permission can be granted to Anyone on a private component"); @@ -107,7 +108,7 @@ public class GroupPermissionChangerTest { GroupUuidOrAnyone anyOneGroup = GroupUuidOrAnyone.forAnyone(); permissionService.getAllProjectPermissions() .forEach(perm -> { - apply(new GroupPermissionChange(PermissionChange.Operation.REMOVE, perm, new ProjectUuid(privateProject), anyOneGroup, permissionService)); + apply(new GroupPermissionChange(PermissionChange.Operation.REMOVE, perm, privateProject, anyOneGroup, permissionService)); assertThat(db.users().selectAnyonePermissions(privateProject)).contains(perm); }); @@ -141,7 +142,7 @@ public class GroupPermissionChangerTest { private void applyAddsPermissionToGroupOnPrivateProject(String permission) { GroupUuidOrAnyone groupUuid = GroupUuidOrAnyone.from(group); - apply(new GroupPermissionChange(PermissionChange.Operation.ADD, permission, new ProjectUuid(privateProject), groupUuid, permissionService)); + apply(new GroupPermissionChange(PermissionChange.Operation.ADD, permission, privateProject, groupUuid, permissionService)); assertThat(db.users().selectGroupPermissions(group, null)).isEmpty(); assertThat(db.users().selectGroupPermissions(group, privateProject)).containsOnly(permission); @@ -176,7 +177,7 @@ public class GroupPermissionChangerTest { GroupUuidOrAnyone groupUuid = GroupUuidOrAnyone.from(group); db.users().insertProjectPermissionOnGroup(group, permission, privateProject); - apply(new GroupPermissionChange(PermissionChange.Operation.ADD, permission, new ProjectUuid(privateProject), groupUuid, permissionService)); + apply(new GroupPermissionChange(PermissionChange.Operation.ADD, permission, privateProject, groupUuid, permissionService)); assertThat(db.users().selectGroupPermissions(group, privateProject)).containsOnly(permission); } @@ -185,7 +186,7 @@ public class GroupPermissionChangerTest { public void apply_has_no_effect_when_adding_USER_permission_to_group_AnyOne_on_a_public_project() { GroupUuidOrAnyone groupUuid = GroupUuidOrAnyone.forAnyone(); - apply(new GroupPermissionChange(PermissionChange.Operation.ADD, UserRole.USER, new ProjectUuid(publicProject), groupUuid, permissionService)); + apply(new GroupPermissionChange(PermissionChange.Operation.ADD, UserRole.USER, publicProject, groupUuid, permissionService)); assertThat(db.users().selectAnyonePermissions(publicProject)).isEmpty(); } @@ -194,7 +195,7 @@ public class GroupPermissionChangerTest { public void apply_has_no_effect_when_adding_CODEVIEWER_permission_to_group_AnyOne_on_a_public_project() { GroupUuidOrAnyone groupUuid = GroupUuidOrAnyone.forAnyone(); - apply(new GroupPermissionChange(PermissionChange.Operation.ADD, UserRole.CODEVIEWER, new ProjectUuid(publicProject), groupUuid, permissionService)); + apply(new GroupPermissionChange(PermissionChange.Operation.ADD, UserRole.CODEVIEWER, publicProject, groupUuid, permissionService)); assertThat(db.users().selectAnyonePermissions(publicProject)).isEmpty(); } @@ -206,14 +207,14 @@ public class GroupPermissionChangerTest { expectedException.expect(BadRequestException.class); expectedException.expectMessage("It is not possible to add the 'admin' permission to group 'Anyone'"); - apply(new GroupPermissionChange(PermissionChange.Operation.ADD, UserRole.ADMIN, new ProjectUuid(publicProject), groupUuid, permissionService)); + apply(new GroupPermissionChange(PermissionChange.Operation.ADD, UserRole.ADMIN, publicProject, groupUuid, permissionService)); } @Test public void apply_adds_permission_ISSUE_ADMIN_to_group_AnyOne_on_a_public_project() { GroupUuidOrAnyone groupUuid = GroupUuidOrAnyone.forAnyone(); - apply(new GroupPermissionChange(PermissionChange.Operation.ADD, UserRole.ISSUE_ADMIN, new ProjectUuid(publicProject), groupUuid, permissionService)); + apply(new GroupPermissionChange(PermissionChange.Operation.ADD, UserRole.ISSUE_ADMIN, publicProject, groupUuid, permissionService)); assertThat(db.users().selectAnyonePermissions(publicProject)).containsOnly(UserRole.ISSUE_ADMIN); } @@ -222,7 +223,7 @@ public class GroupPermissionChangerTest { public void apply_adds_permission_SCAN_EXECUTION_to_group_AnyOne_on_a_public_project() { GroupUuidOrAnyone groupUuid = GroupUuidOrAnyone.forAnyone(); - apply(new GroupPermissionChange(PermissionChange.Operation.ADD, GlobalPermissions.SCAN_EXECUTION, new ProjectUuid(publicProject), groupUuid, permissionService)); + apply(new GroupPermissionChange(PermissionChange.Operation.ADD, GlobalPermissions.SCAN_EXECUTION, publicProject, groupUuid, permissionService)); assertThat(db.users().selectAnyonePermissions(publicProject)).containsOnly(GlobalPermissions.SCAN_EXECUTION); } @@ -234,7 +235,7 @@ public class GroupPermissionChangerTest { expectedException.expect(BadRequestException.class); expectedException.expectMessage("Permission user can't be removed from a public component"); - apply(new GroupPermissionChange(PermissionChange.Operation.REMOVE, UserRole.USER, new ProjectUuid(publicProject), groupUuid, permissionService)); + apply(new GroupPermissionChange(PermissionChange.Operation.REMOVE, UserRole.USER, publicProject, groupUuid, permissionService)); } @Test @@ -244,7 +245,7 @@ public class GroupPermissionChangerTest { expectedException.expect(BadRequestException.class); expectedException.expectMessage("Permission codeviewer can't be removed from a public component"); - apply(new GroupPermissionChange(PermissionChange.Operation.REMOVE, UserRole.CODEVIEWER, new ProjectUuid(publicProject), groupUuid, permissionService)); + apply(new GroupPermissionChange(PermissionChange.Operation.REMOVE, UserRole.CODEVIEWER, publicProject, groupUuid, permissionService)); } @Test @@ -266,7 +267,7 @@ public class GroupPermissionChangerTest { GroupUuidOrAnyone groupUuid = GroupUuidOrAnyone.forAnyone(); db.users().insertProjectPermissionOnAnyone(permission, publicProject); - apply(new GroupPermissionChange(PermissionChange.Operation.REMOVE, permission, new ProjectUuid(publicProject), groupUuid, permissionService)); + apply(new GroupPermissionChange(PermissionChange.Operation.REMOVE, permission, publicProject, groupUuid, permissionService)); assertThat(db.users().selectAnyonePermissions(publicProject)).isEmpty(); } @@ -278,7 +279,7 @@ public class GroupPermissionChangerTest { expectedException.expect(BadRequestException.class); expectedException.expectMessage("Permission user can't be removed from a public component"); - apply(new GroupPermissionChange(PermissionChange.Operation.REMOVE, UserRole.USER, new ProjectUuid(publicProject), groupUuid, permissionService)); + apply(new GroupPermissionChange(PermissionChange.Operation.REMOVE, UserRole.USER, publicProject, groupUuid, permissionService)); } @Test @@ -288,7 +289,7 @@ public class GroupPermissionChangerTest { expectedException.expect(BadRequestException.class); expectedException.expectMessage("Permission codeviewer can't be removed from a public component"); - apply(new GroupPermissionChange(PermissionChange.Operation.REMOVE, UserRole.CODEVIEWER, new ProjectUuid(publicProject), groupUuid, permissionService)); + apply(new GroupPermissionChange(PermissionChange.Operation.REMOVE, UserRole.CODEVIEWER, publicProject, groupUuid, permissionService)); } @Test @@ -320,7 +321,7 @@ public class GroupPermissionChangerTest { .filter(perm -> !UserRole.ADMIN.equals(perm) && !GlobalPermissions.SCAN_EXECUTION.equals(perm)) .forEach(perm -> { try { - apply(new GroupPermissionChange(PermissionChange.Operation.ADD, perm, new ProjectUuid(privateProject), groupUuid, permissionService)); + new GroupPermissionChange(PermissionChange.Operation.ADD, perm, privateProject, groupUuid, permissionService); fail("a BadRequestException should have been thrown for permission " + perm); } catch (BadRequestException e) { assertThat(e).hasMessage("Invalid project permission '" + perm + @@ -338,7 +339,7 @@ public class GroupPermissionChangerTest { .filter(perm -> !UserRole.ADMIN.equals(perm) && !GlobalPermissions.SCAN_EXECUTION.equals(perm)) .forEach(perm -> { try { - apply(new GroupPermissionChange(PermissionChange.Operation.ADD, perm, new ProjectUuid(publicProject), groupUuid, permissionService)); + new GroupPermissionChange(PermissionChange.Operation.ADD, perm, publicProject, groupUuid, permissionService); fail("a BadRequestException should have been thrown for permission " + perm); } catch (BadRequestException e) { assertThat(e).hasMessage("Invalid project permission '" + perm + @@ -356,7 +357,7 @@ public class GroupPermissionChangerTest { .filter(perm -> !GlobalPermissions.SCAN_EXECUTION.equals(perm) && !GlobalPermission.ADMINISTER.getKey().equals(perm)) .forEach(permission -> { try { - apply(new GroupPermissionChange(PermissionChange.Operation.ADD, permission, null, groupUuid, permissionService)); + new GroupPermissionChange(PermissionChange.Operation.ADD, permission, null, groupUuid, permissionService); fail("a BadRequestException should have been thrown for permission " + permission); } catch (BadRequestException e) { assertThat(e).hasMessage("Invalid global permission '" + permission + "'. Valid values are [admin, gateadmin, profileadmin, provisioning, scan]"); @@ -382,7 +383,7 @@ public class GroupPermissionChangerTest { db.users().insertProjectPermissionOnGroup(group, UserRole.ISSUE_ADMIN, privateProject); db.users().insertProjectPermissionOnGroup(group, UserRole.CODEVIEWER, privateProject); - apply(new GroupPermissionChange(PermissionChange.Operation.REMOVE, UserRole.ISSUE_ADMIN, new ProjectUuid(privateProject), groupUuid, permissionService)); + apply(new GroupPermissionChange(PermissionChange.Operation.REMOVE, UserRole.ISSUE_ADMIN, privateProject, groupUuid, permissionService)); assertThat(db.users().selectGroupPermissions(group, null)).containsOnly(ADMINISTER_QUALITY_GATES.getKey()); assertThat(db.users().selectGroupPermissions(group, privateProject)).containsOnly(UserRole.CODEVIEWER); @@ -392,7 +393,7 @@ public class GroupPermissionChangerTest { public void do_not_fail_if_removing_a_permission_that_does_not_exist() { GroupUuidOrAnyone groupUuid = GroupUuidOrAnyone.from(group); - apply(new GroupPermissionChange(PermissionChange.Operation.REMOVE, UserRole.ISSUE_ADMIN, new ProjectUuid(privateProject), groupUuid, permissionService)); + apply(new GroupPermissionChange(PermissionChange.Operation.REMOVE, UserRole.ISSUE_ADMIN, privateProject, groupUuid, permissionService)); assertThat(db.users().selectGroupPermissions(group, null)).isEmpty(); assertThat(db.users().selectGroupPermissions(group, privateProject)).isEmpty(); diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/UserPermissionChangerTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/UserPermissionChangerTest.java index 79aca80b2b8..5906f964a92 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/UserPermissionChangerTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/UserPermissionChangerTest.java @@ -57,9 +57,9 @@ public class UserPermissionChangerTest { @Rule public ExpectedException expectedException = ExpectedException.none(); - private ResourceTypes resourceTypes = new ResourceTypesRule().setRootQualifiers(Qualifiers.PROJECT); - private PermissionService permissionService = new PermissionServiceImpl(resourceTypes); - private UserPermissionChanger underTest = new UserPermissionChanger(db.getDbClient(), new SequenceUuidFactory()); + private final ResourceTypes resourceTypes = new ResourceTypesRule().setRootQualifiers(Qualifiers.PROJECT); + private final PermissionService permissionService = new PermissionServiceImpl(resourceTypes); + private final UserPermissionChanger underTest = new UserPermissionChanger(db.getDbClient(), new SequenceUuidFactory()); private UserDto user1; private UserDto user2; private ComponentDto privateProject; @@ -106,7 +106,7 @@ public class UserPermissionChangerTest { @Test public void apply_has_no_effect_when_adding_permission_USER_on_a_public_project() { - UserPermissionChange change = new UserPermissionChange(ADD, USER, new ProjectUuid(publicProject), UserId.from(user1), permissionService); + UserPermissionChange change = new UserPermissionChange(ADD, USER, publicProject, UserId.from(user1), permissionService); apply(change); @@ -115,7 +115,7 @@ public class UserPermissionChangerTest { @Test public void apply_has_no_effect_when_adding_permission_CODEVIEWER_on_a_public_project() { - UserPermissionChange change = new UserPermissionChange(ADD, CODEVIEWER, new ProjectUuid(publicProject), UserId.from(user1), permissionService); + UserPermissionChange change = new UserPermissionChange(ADD, CODEVIEWER, publicProject, UserId.from(user1), permissionService); apply(change); @@ -138,7 +138,7 @@ public class UserPermissionChangerTest { } private void applyAddsPermissionOnAPublicProject(String permission) { - UserPermissionChange change = new UserPermissionChange(ADD, permission, new ProjectUuid(publicProject), UserId.from(user1), permissionService); + UserPermissionChange change = new UserPermissionChange(ADD, permission, publicProject, UserId.from(user1), permissionService); apply(change); @@ -147,7 +147,7 @@ public class UserPermissionChangerTest { @Test public void apply_fails_with_BadRequestException_when_removing_permission_USER_from_a_public_project() { - UserPermissionChange change = new UserPermissionChange(REMOVE, USER, new ProjectUuid(publicProject), UserId.from(user1), permissionService); + UserPermissionChange change = new UserPermissionChange(REMOVE, USER, publicProject, UserId.from(user1), permissionService); expectedException.expect(BadRequestException.class); expectedException.expectMessage("Permission user can't be removed from a public component"); @@ -157,7 +157,7 @@ public class UserPermissionChangerTest { @Test public void apply_fails_with_BadRequestException_when_removing_permission_CODEVIEWER_from_a_public_project() { - UserPermissionChange change = new UserPermissionChange(REMOVE, CODEVIEWER, new ProjectUuid(publicProject), UserId.from(user1), permissionService); + UserPermissionChange change = new UserPermissionChange(REMOVE, CODEVIEWER, publicProject, UserId.from(user1), permissionService); expectedException.expect(BadRequestException.class); expectedException.expectMessage("Permission codeviewer can't be removed from a public component"); @@ -182,7 +182,7 @@ public class UserPermissionChangerTest { private void applyRemovesPermissionFromPublicProject(String permission) { db.users().insertProjectPermissionOnUser(user1, permission, publicProject); - UserPermissionChange change = new UserPermissionChange(REMOVE, permission, new ProjectUuid(publicProject), UserId.from(user1), permissionService); + UserPermissionChange change = new UserPermissionChange(REMOVE, permission, publicProject, UserId.from(user1), permissionService); apply(change); @@ -193,7 +193,7 @@ public class UserPermissionChangerTest { public void apply_adds_any_permission_to_a_private_project() { permissionService.getAllProjectPermissions() .forEach(permission -> { - UserPermissionChange change = new UserPermissionChange(ADD, permission, new ProjectUuid(privateProject), UserId.from(user1), permissionService); + UserPermissionChange change = new UserPermissionChange(ADD, permission, privateProject, UserId.from(user1), permissionService); apply(change); @@ -208,7 +208,7 @@ public class UserPermissionChangerTest { permissionService.getAllProjectPermissions() .forEach(permission -> { - UserPermissionChange change = new UserPermissionChange(REMOVE, permission, new ProjectUuid(privateProject), UserId.from(user1), permissionService); + UserPermissionChange change = new UserPermissionChange(REMOVE, permission, privateProject, UserId.from(user1), permissionService); apply(change); @@ -230,7 +230,7 @@ public class UserPermissionChangerTest { @Test public void add_project_permission_to_user() { - UserPermissionChange change = new UserPermissionChange(ADD, ISSUE_ADMIN, new ProjectUuid(privateProject), UserId.from(user1), permissionService); + UserPermissionChange change = new UserPermissionChange(ADD, ISSUE_ADMIN, privateProject, UserId.from(user1), permissionService); apply(change); assertThat(db.users().selectPermissionsOfUser(user1)).isEmpty(); @@ -254,7 +254,7 @@ public class UserPermissionChangerTest { expectedException.expect(BadRequestException.class); expectedException.expectMessage("Invalid project permission 'gateadmin'. Valid values are [" + StringUtils.join(permissionService.getAllProjectPermissions(), ", ") + "]"); - UserPermissionChange change = new UserPermissionChange(ADD, QUALITY_GATE_ADMIN, new ProjectUuid(privateProject), UserId.from(user1), permissionService); + UserPermissionChange change = new UserPermissionChange(ADD, QUALITY_GATE_ADMIN, privateProject, UserId.from(user1), permissionService); apply(change); } @@ -291,7 +291,7 @@ public class UserPermissionChangerTest { db.users().insertProjectPermissionOnUser(user2, ISSUE_ADMIN, privateProject); db.users().insertProjectPermissionOnUser(user1, ISSUE_ADMIN, project2); - UserPermissionChange change = new UserPermissionChange(REMOVE, ISSUE_ADMIN, new ProjectUuid(privateProject), UserId.from(user1), permissionService); + UserPermissionChange change = new UserPermissionChange(REMOVE, ISSUE_ADMIN, privateProject, UserId.from(user1), permissionService); apply(change); assertThat(db.users().selectProjectPermissionsOfUser(user1, privateProject)).containsOnly(USER); @@ -309,7 +309,7 @@ public class UserPermissionChangerTest { @Test public void do_not_fail_if_removing_a_project_permission_that_does_not_exist() { - UserPermissionChange change = new UserPermissionChange(REMOVE, ISSUE_ADMIN, new ProjectUuid(privateProject), UserId.from(user1), permissionService); + UserPermissionChange change = new UserPermissionChange(REMOVE, ISSUE_ADMIN, privateProject, UserId.from(user1), permissionService); apply(change); assertThat(db.users().selectProjectPermissionsOfUser(user1, privateProject)).isEmpty(); diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/template/CreateTemplateActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/template/CreateTemplateActionTest.java index 19a019ae84c..ba2c0033ecb 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/template/CreateTemplateActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/template/CreateTemplateActionTest.java @@ -40,7 +40,7 @@ import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_P public class CreateTemplateActionTest extends BasePermissionWsTest { private static final long NOW = 1_440_512_328_743L; - private System2 system = new TestSystem2().setNow(NOW); + private final System2 system = new TestSystem2().setNow(NOW); @Override protected CreateTemplateAction buildWsAction() { diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/user/ws/CurrentActionHomepageTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/user/ws/CurrentActionHomepageTest.java index 5c05c4f650d..0c4fb688385 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/user/ws/CurrentActionHomepageTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/user/ws/CurrentActionHomepageTest.java @@ -40,8 +40,6 @@ import org.sonar.db.DbTester; import org.sonar.db.component.ComponentDto; import org.sonar.db.user.UserDto; import org.sonar.server.issue.AvatarResolverImpl; -import org.sonar.server.organization.DefaultOrganizationProvider; -import org.sonar.server.organization.TestDefaultOrganizationProvider; import org.sonar.server.permission.PermissionService; import org.sonar.server.permission.PermissionServiceImpl; import org.sonar.server.tester.UserSessionRule; @@ -63,16 +61,14 @@ public class CurrentActionHomepageTest { @Rule public ExpectedException expectedException = ExpectedException.none(); - private DbClient dbClient = db.getDbClient(); - private DefaultOrganizationProvider defaultOrganizationProvider = TestDefaultOrganizationProvider.from(db); + private final DbClient dbClient = db.getDbClient(); - private PlatformEditionProvider platformEditionProvider = mock(PlatformEditionProvider.class); - private HomepageTypesImpl homepageTypes = new HomepageTypesImpl(); - private PermissionService permissionService = new PermissionServiceImpl(new ResourceTypes(new ResourceTypeTree[] { + private final PlatformEditionProvider platformEditionProvider = mock(PlatformEditionProvider.class); + private final HomepageTypesImpl homepageTypes = new HomepageTypesImpl(); + private final PermissionService permissionService = new PermissionServiceImpl(new ResourceTypes(new ResourceTypeTree[] { ResourceTypeTree.builder().addType(ResourceType.builder(Qualifiers.PROJECT).build()).build()})); - - private WsActionTester ws = new WsActionTester( - new CurrentAction(userSessionRule, dbClient, defaultOrganizationProvider, new AvatarResolverImpl(), homepageTypes, platformEditionProvider, permissionService)); + private final WsActionTester ws = new WsActionTester( + new CurrentAction(userSessionRule, dbClient, new AvatarResolverImpl(), homepageTypes, platformEditionProvider, permissionService)); @Test public void return_homepage_when_set_to_portfolios() { @@ -247,7 +243,7 @@ public class CurrentActionHomepageTest { CurrentWsResponse response = ws.newRequest().executeProtobuf(CurrentWsResponse.class); - assertThat(response.getHomepage().getType().toString()).isEqualTo("PROJECTS"); + assertThat(response.getHomepage().getType()).hasToString("PROJECTS"); } @Test @@ -257,7 +253,7 @@ public class CurrentActionHomepageTest { CurrentWsResponse response = ws.newRequest().executeProtobuf(CurrentWsResponse.class); - assertThat(response.getHomepage().getType().toString()).isEqualTo("PROJECTS"); + assertThat(response.getHomepage().getType()).hasToString("PROJECTS"); } private CurrentWsResponse call() { diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/user/ws/CurrentActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/user/ws/CurrentActionTest.java index bd7954d913b..0c1422130ce 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/user/ws/CurrentActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/user/ws/CurrentActionTest.java @@ -22,7 +22,6 @@ package org.sonar.server.user.ws; import java.util.Collections; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.resources.Qualifiers; import org.sonar.api.resources.ResourceType; import org.sonar.api.resources.ResourceTypeTree; @@ -34,7 +33,6 @@ import org.sonar.db.DbTester; import org.sonar.db.component.ComponentDto; import org.sonar.db.user.UserDto; import org.sonar.server.issue.AvatarResolverImpl; -import org.sonar.server.organization.TestDefaultOrganizationProvider; import org.sonar.server.permission.PermissionService; import org.sonar.server.permission.PermissionServiceImpl; import org.sonar.server.tester.UserSessionRule; @@ -43,6 +41,7 @@ import org.sonarqube.ws.Users.CurrentWsResponse; import static com.google.common.collect.Lists.newArrayList; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.tuple; import static org.mockito.Mockito.mock; import static org.sonar.api.web.UserRole.USER; @@ -57,17 +56,13 @@ public class CurrentActionTest { public UserSessionRule userSession = UserSessionRule.standalone(); @Rule public DbTester db = DbTester.create(System2.INSTANCE); - @Rule - public ExpectedException expectedException = ExpectedException.none(); - private PlatformEditionProvider platformEditionProvider = mock(PlatformEditionProvider.class); - private HomepageTypesImpl homepageTypes = new HomepageTypesImpl(); - private PermissionService permissionService = new PermissionServiceImpl(new ResourceTypes(new ResourceTypeTree[] { + private final PlatformEditionProvider platformEditionProvider = mock(PlatformEditionProvider.class); + private final HomepageTypesImpl homepageTypes = new HomepageTypesImpl(); + private final PermissionService permissionService = new PermissionServiceImpl(new ResourceTypes(new ResourceTypeTree[] { ResourceTypeTree.builder().addType(ResourceType.builder(Qualifiers.PROJECT).build()).build()})); - - private WsActionTester ws = new WsActionTester( - new CurrentAction(userSession, db.getDbClient(), TestDefaultOrganizationProvider.from(db), new AvatarResolverImpl(), homepageTypes, platformEditionProvider, - permissionService)); + private final WsActionTester ws = new WsActionTester( + new CurrentAction(userSession, db.getDbClient(), new AvatarResolverImpl(), homepageTypes, platformEditionProvider, permissionService)); @Test public void return_user_info() { @@ -179,10 +174,9 @@ public class CurrentActionTest { db.users().insertUser(usert -> usert.setLogin("another")); userSession.logIn("obiwan.kenobi"); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("User login 'obiwan.kenobi' cannot be found"); - - call(); + assertThatThrownBy(this::call) + .isInstanceOf(IllegalStateException.class) + .hasMessage("User login 'obiwan.kenobi' cannot be found"); } @Test -- 2.39.5