]> source.dussan.org Git - sonarqube.git/commitdiff
SONAR-6498 WS permissions/delete_template impossible to delete a default template
authorTeryk Bellahsene <teryk.bellahsene@sonarsource.com>
Fri, 28 Aug 2015 13:43:20 +0000 (15:43 +0200)
committerTeryk Bellahsene <teryk.bellahsene@sonarsource.com>
Fri, 28 Aug 2015 15:30:34 +0000 (17:30 +0200)
29 files changed:
server/sonar-server/src/main/java/org/sonar/server/permission/DefaultPermissionTemplates.java [new file with mode: 0644]
server/sonar-server/src/main/java/org/sonar/server/permission/PermissionFinder.java
server/sonar-server/src/main/java/org/sonar/server/permission/PermissionTemplateService.java
server/sonar-server/src/main/java/org/sonar/server/permission/PermissionTemplateUpdater.java
server/sonar-server/src/main/java/org/sonar/server/permission/ws/CreateTemplateAction.java
server/sonar-server/src/main/java/org/sonar/server/permission/ws/DefaultPermissionTemplateFinder.java [new file with mode: 0644]
server/sonar-server/src/main/java/org/sonar/server/permission/ws/DeleteTemplateAction.java
server/sonar-server/src/main/java/org/sonar/server/permission/ws/PermissionDependenciesFinder.java
server/sonar-server/src/main/java/org/sonar/server/permission/ws/PermissionsWsModule.java
server/sonar-server/src/main/java/org/sonar/server/permission/ws/ResourceTypeToQualifier.java [new file with mode: 0644]
server/sonar-server/src/main/java/org/sonar/server/permission/ws/SearchProjectPermissionsDataLoader.java
server/sonar-server/src/main/java/org/sonar/server/startup/RegisterPermissionTemplates.java
server/sonar-server/src/test/java/org/sonar/server/permission/PermissionFinderTest.java
server/sonar-server/src/test/java/org/sonar/server/permission/PermissionTemplateServiceTest.java
server/sonar-server/src/test/java/org/sonar/server/permission/PermissionTemplateUpdaterTest.java
server/sonar-server/src/test/java/org/sonar/server/permission/ws/AddGroupToTemplateActionTest.java
server/sonar-server/src/test/java/org/sonar/server/permission/ws/AddUserToTemplateActionTest.java
server/sonar-server/src/test/java/org/sonar/server/permission/ws/DefaultPermissionTemplateFinderTest.java [new file with mode: 0644]
server/sonar-server/src/test/java/org/sonar/server/permission/ws/DeleteTemplateActionTest.java
server/sonar-server/src/test/java/org/sonar/server/permission/ws/PermissionsWsModuleTest.java
server/sonar-server/src/test/java/org/sonar/server/permission/ws/RemoveGroupFromTemplateActionTest.java
server/sonar-server/src/test/java/org/sonar/server/permission/ws/RemoveUserFromTemplateActionTest.java
server/sonar-server/src/test/java/org/sonar/server/permission/ws/UpdateTemplateActionTest.java
server/sonar-server/src/test/java/org/sonar/server/startup/RegisterPermissionTemplatesTest.java
sonar-db/src/main/java/org/sonar/db/RowNotFoundException.java
sonar-db/src/main/java/org/sonar/db/permission/PermissionTemplateDao.java
sonar-db/src/main/java/org/sonar/db/permission/PermissionTemplateMapper.java
sonar-db/src/main/resources/org/sonar/db/permission/PermissionTemplateMapper.xml
sonar-db/src/test/java/org/sonar/db/permission/PermissionTemplateDaoTest.java

diff --git a/server/sonar-server/src/main/java/org/sonar/server/permission/DefaultPermissionTemplates.java b/server/sonar-server/src/main/java/org/sonar/server/permission/DefaultPermissionTemplates.java
new file mode 100644 (file)
index 0000000..ed1743a
--- /dev/null
@@ -0,0 +1,32 @@
+/*
+ * SonarQube, open source software quality management tool.
+ * Copyright (C) 2008-2014 SonarSource
+ * mailto:contact AT sonarsource DOT com
+ *
+ * SonarQube 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.
+ *
+ * SonarQube 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 static java.lang.String.format;
+
+public class DefaultPermissionTemplates {
+  public static final String DEFAULT_TEMPLATE_PROPERTY = "sonar.permission.template.default";
+  private static final String DEFAULT_ROOT_QUALIFIER_TEMPLATE_PROPERTY = "sonar.permission.template.%s.default";
+
+  public static String defaultRootQualifierTemplateProperty(String qualifier) {
+    return format(DEFAULT_ROOT_QUALIFIER_TEMPLATE_PROPERTY, qualifier);
+  }
+}
index cff70f7e089cb08e7cc7ee59a671d9a9c219b06e..393d594d9634ac18b52727405acbffd451ae47b3 100644 (file)
@@ -152,7 +152,7 @@ public class PermissionFinder {
   }
 
   private Long templateId(String templateKey) {
-    PermissionTemplateDto dto = permissionTemplateDao.selectByKey(templateKey);
+    PermissionTemplateDto dto = permissionTemplateDao.selectByUuid(templateKey);
     if (dto == null) {
       throw new NotFoundException(String.format("Template '%s' does not exist", templateKey));
     }
index 1d658d0d195db29deb2a47293341c587559c7c7e..d7e412765d9abca2d6cffda35420031f51ed516e 100644 (file)
@@ -75,7 +75,7 @@ public class PermissionTemplateService {
   @CheckForNull
   public PermissionTemplate selectPermissionTemplate(String templateKey) {
     checkGlobalAdminUser(userSession);
-    PermissionTemplateDto permissionTemplateDto = permissionTemplateDao.selectByKeyWithUserAndGroupPermissions(templateKey);
+    PermissionTemplateDto permissionTemplateDto = permissionTemplateDao.selectByUuidWithUserAndGroupPermissions(templateKey);
     return PermissionTemplate.create(permissionTemplateDto);
   }
 
@@ -132,7 +132,13 @@ public class PermissionTemplateService {
 
   public void deletePermissionTemplate(Long templateId) {
     checkGlobalAdminUser(userSession);
-    permissionTemplateDao.deleteById(templateId);
+    DbSession dbSession = dbClient.openSession(false);
+    try {
+      permissionTemplateDao.deleteById(dbSession, templateId);
+      dbSession.commit();
+    } finally {
+      dbClient.closeSession(dbSession);
+    }
   }
 
   /**
index a0a34505897030a201c3cf08d07e4d5f1879d50e..55fde3b40554c1320481030c043eb14cb4ca397b 100644 (file)
@@ -87,7 +87,7 @@ abstract class PermissionTemplateUpdater {
   }
 
   private Long getTemplateId(String key) {
-    PermissionTemplateDto permissionTemplateDto = dbClient.permissionTemplateDao().selectByKey(key);
+    PermissionTemplateDto permissionTemplateDto = dbClient.permissionTemplateDao().selectByUuid(key);
     if (permissionTemplateDto == null) {
       throw new BadRequestException("Unknown template: " + key);
     }
index 04141c3dad403c2a77d0f013b576c8c9c85cfe60..92ea3b0097dd1dde34c0ebaa8696086d09aefb02 100644 (file)
@@ -31,6 +31,7 @@ import org.sonar.server.user.UserSession;
 import org.sonarqube.ws.Permissions;
 import org.sonarqube.ws.Permissions.PermissionTemplate;
 
+import static java.lang.String.format;
 import static org.sonar.server.permission.PermissionPrivilegeChecker.checkGlobalAdminUser;
 import static org.sonar.server.permission.ws.Parameters.PARAM_TEMPLATE_DESCRIPTION;
 import static org.sonar.server.permission.ws.Parameters.PARAM_TEMPLATE_NAME;
@@ -100,8 +101,7 @@ public class CreateTemplateAction implements PermissionsWsAction {
     validateTemplateNameFormat(name);
 
     PermissionTemplateDto permissionTemplateWithSameName = dbClient.permissionTemplateDao().selectByName(dbSession, name);
-    checkRequest(permissionTemplateWithSameName == null, String.format
-      (MSG_TEMPLATE_WITH_SAME_NAME, name));
+    checkRequest(permissionTemplateWithSameName == null, format(MSG_TEMPLATE_WITH_SAME_NAME, name));
   }
 
   private PermissionTemplateDto insertTemplate(DbSession dbSession, String name, String description, String projectPattern) {
diff --git a/server/sonar-server/src/main/java/org/sonar/server/permission/ws/DefaultPermissionTemplateFinder.java b/server/sonar-server/src/main/java/org/sonar/server/permission/ws/DefaultPermissionTemplateFinder.java
new file mode 100644 (file)
index 0000000..1f6c853
--- /dev/null
@@ -0,0 +1,70 @@
+/*
+ * SonarQube, open source software quality management tool.
+ * Copyright (C) 2008-2014 SonarSource
+ * mailto:contact AT sonarsource DOT com
+ *
+ * SonarQube 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.
+ *
+ * SonarQube 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.ws;
+
+import com.google.common.base.Function;
+import com.google.common.collect.FluentIterable;
+import com.google.common.collect.ImmutableSet;
+import java.util.Set;
+import javax.annotation.Nonnull;
+import org.sonar.api.config.Settings;
+import org.sonar.api.resources.ResourceTypes;
+
+import static com.google.common.base.Objects.firstNonNull;
+import static org.sonar.server.permission.DefaultPermissionTemplates.DEFAULT_TEMPLATE_PROPERTY;
+import static org.sonar.server.permission.DefaultPermissionTemplates.defaultRootQualifierTemplateProperty;
+import static org.sonar.server.permission.ws.ResourceTypeToQualifier.RESOURCE_TYPE_TO_QUALIFIER;
+
+public class DefaultPermissionTemplateFinder {
+  private final Settings settings;
+  private final ResourceTypes resourceTypes;
+
+  public DefaultPermissionTemplateFinder(Settings settings, ResourceTypes resourceTypes) {
+    this.settings = settings;
+    this.resourceTypes = resourceTypes;
+  }
+
+  public Set<String> getDefaultTemplateUuids() {
+    return ImmutableSet.<String>builder()
+      .addAll(
+        FluentIterable.from(resourceTypes.getRoots())
+          .transform(RESOURCE_TYPE_TO_QUALIFIER)
+          .transform(new QualifierToDefaultTemplate(settings))
+          .toSet())
+      .add(settings.getString(DEFAULT_TEMPLATE_PROPERTY))
+      .build();
+  }
+
+  private static class QualifierToDefaultTemplate implements Function<String, String> {
+    private final Settings settings;
+
+    QualifierToDefaultTemplate(Settings settings) {
+      this.settings = settings;
+    }
+
+    @Override
+    public String apply(@Nonnull String qualifier) {
+      String qualifierProperty = settings.getString(defaultRootQualifierTemplateProperty(qualifier));
+      return firstNonNull(qualifierProperty, settings.getString(DEFAULT_TEMPLATE_PROPERTY));
+    }
+  }
+
+}
index 8f15173e3e3cb1a350a0f3650bbd5f479770979a..1e25d69cad12d2f73dcf05f4b402325eec60242a 100644 (file)
 
 package org.sonar.server.permission.ws;
 
+import java.util.Set;
 import org.sonar.api.server.ws.Request;
 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.permission.PermissionTemplateDto;
 import org.sonar.server.user.UserSession;
 
 import static org.sonar.server.permission.PermissionPrivilegeChecker.checkGlobalAdminUser;
 import static org.sonar.server.permission.ws.Parameters.PARAM_TEMPLATE_ID;
 import static org.sonar.server.permission.ws.Parameters.createTemplateKeyParameter;
+import static org.sonar.server.ws.WsUtils.checkRequest;
 
 public class DeleteTemplateAction implements PermissionsWsAction {
   private final DbClient dbClient;
   private final UserSession userSession;
+  private final PermissionDependenciesFinder finder;
+  private final DefaultPermissionTemplateFinder defaultPermissionTemplateFinder;
 
-  public DeleteTemplateAction(DbClient dbClient, UserSession userSession) {
+  public DeleteTemplateAction(DbClient dbClient, UserSession userSession, PermissionDependenciesFinder finder, DefaultPermissionTemplateFinder defaultPermissionTemplateFinder) {
     this.dbClient = dbClient;
     this.userSession = userSession;
+    this.finder = finder;
+    this.defaultPermissionTemplateFinder = defaultPermissionTemplateFinder;
   }
 
   @Override
@@ -55,16 +62,28 @@ public class DeleteTemplateAction implements PermissionsWsAction {
   @Override
   public void handle(Request wsRequest, Response wsResponse) throws Exception {
     checkGlobalAdminUser(userSession);
-    String key = wsRequest.mandatoryParam(PARAM_TEMPLATE_ID);
 
+    String uuid = wsRequest.mandatoryParam(PARAM_TEMPLATE_ID);
+    checkTemplateUuidIsNotDefault(uuid);
+
+    deleteTemplate(uuid);
+
+    wsResponse.noContent();
+  }
+
+  private void deleteTemplate(String uuid) {
     DbSession dbSession = dbClient.openSession(false);
     try {
-      dbClient.permissionTemplateDao().deleteByKey(dbSession, key);
+      PermissionTemplateDto template = finder.getTemplate(dbSession, uuid);
+      dbClient.permissionTemplateDao().deleteById(dbSession, template.getId());
       dbSession.commit();
-
-      wsResponse.noContent();
     } finally {
       dbClient.closeSession(dbSession);
     }
   }
+
+  private void checkTemplateUuidIsNotDefault(String key) {
+    Set<String> defaultTemplateUuids = defaultPermissionTemplateFinder.getDefaultTemplateUuids();
+    checkRequest(!defaultTemplateUuids.contains(key), "It is not possible to delete a default template");
+  }
 }
index a6a4e862d8c2429e1a2e3786127e0866925288ad..dcd4d66dbb3cc5398365c9d931b95c1ccd1ba680 100644 (file)
@@ -95,8 +95,8 @@ public class PermissionDependenciesFinder {
       format("User with login '%s' is not found'", userLogin));
   }
 
-  PermissionTemplateDto getTemplate(DbSession dbSession, String templateKey) {
-    return checkFound(dbClient.permissionTemplateDao().selectByKey(dbSession, templateKey),
-      format("Permission template with key '%s' is not found", templateKey));
+  PermissionTemplateDto getTemplate(DbSession dbSession, String uuid) {
+    return checkFound(dbClient.permissionTemplateDao().selectByUuid(dbSession, uuid),
+      format("Permission template with id '%s' is not found", uuid));
   }
 }
index 6998cf230158585ad9c7d2cc961cb23433988509..6769088cde549b963272412d71684da8d08bebe7 100644 (file)
@@ -27,6 +27,7 @@ public class PermissionsWsModule extends Module {
   protected void configureModule() {
     add(
       PermissionsWs.class,
+      // actions
       AddGroupAction.class,
       AddUserAction.class,
       RemoveGroupAction.class,
@@ -34,16 +35,18 @@ public class PermissionsWsModule extends Module {
       UsersAction.class,
       GroupsAction.class,
       SearchGlobalPermissionsAction.class,
-      PermissionChangeBuilder.class,
       SearchProjectPermissionsAction.class,
-      SearchProjectPermissionsDataLoader.class,
-      PermissionDependenciesFinder.class,
-      AddUserToTemplateAction.class,
       RemoveUserFromTemplateAction.class,
+      AddUserToTemplateAction.class,
       AddGroupToTemplateAction.class,
       RemoveGroupFromTemplateAction.class,
       CreateTemplateAction.class,
       UpdateTemplateAction.class,
-      DeleteTemplateAction.class);
+      DeleteTemplateAction.class,
+      // utility classes
+      PermissionChangeBuilder.class,
+      SearchProjectPermissionsDataLoader.class,
+      PermissionDependenciesFinder.class,
+      DefaultPermissionTemplateFinder.class);
   }
 }
diff --git a/server/sonar-server/src/main/java/org/sonar/server/permission/ws/ResourceTypeToQualifier.java b/server/sonar-server/src/main/java/org/sonar/server/permission/ws/ResourceTypeToQualifier.java
new file mode 100644 (file)
index 0000000..a751be7
--- /dev/null
@@ -0,0 +1,39 @@
+/*
+ * SonarQube, open source software quality management tool.
+ * Copyright (C) 2008-2014 SonarSource
+ * mailto:contact AT sonarsource DOT com
+ *
+ * SonarQube 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.
+ *
+ * SonarQube 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.ws;
+
+import com.google.common.base.Function;
+import javax.annotation.Nonnull;
+import org.sonar.api.resources.ResourceType;
+
+class ResourceTypeToQualifier {
+
+  static final Function<ResourceType, String> RESOURCE_TYPE_TO_QUALIFIER = Singleton.INSTANCE;
+
+  private enum Singleton implements Function<ResourceType, String> {
+    INSTANCE;
+
+    @Override
+    public String apply(@Nonnull ResourceType resourceType) {
+      return resourceType.getQualifier();
+    }
+  }
+}
index 925b70d735f7e2259366aa976b11c1907123a4ef..1326164704b3875ddd4aaf268d9aa10af7f008e6 100644 (file)
@@ -31,7 +31,6 @@ import java.util.List;
 import javax.annotation.Nonnull;
 import org.apache.ibatis.session.ResultContext;
 import org.apache.ibatis.session.ResultHandler;
-import org.sonar.api.resources.ResourceType;
 import org.sonar.api.resources.ResourceTypes;
 import org.sonar.api.server.ws.Request;
 import org.sonar.api.utils.Paging;
@@ -46,6 +45,7 @@ import static org.sonar.api.server.ws.WebService.Param.PAGE;
 import static org.sonar.api.server.ws.WebService.Param.PAGE_SIZE;
 import static org.sonar.api.server.ws.WebService.Param.TEXT_QUERY;
 import static org.sonar.api.utils.Paging.forPageIndex;
+import static org.sonar.server.permission.ws.ResourceTypeToQualifier.RESOURCE_TYPE_TO_QUALIFIER;
 import static org.sonar.server.permission.ws.SearchProjectPermissionsData.newBuilder;
 
 public class SearchProjectPermissionsDataLoader {
@@ -56,7 +56,7 @@ public class SearchProjectPermissionsDataLoader {
   public SearchProjectPermissionsDataLoader(DbClient dbClient, ComponentFinder componentFinder, ResourceTypes resourceTypes) {
     this.dbClient = dbClient;
     this.componentFinder = componentFinder;
-    this.rootQualifiers = Collections2.transform(resourceTypes.getRoots(), new ResourceTypeToQualifierFunction());
+    this.rootQualifiers = Collections2.transform(resourceTypes.getRoots(), RESOURCE_TYPE_TO_QUALIFIER);
   }
 
   public SearchProjectPermissionsData load(Request wsRequest) {
@@ -135,11 +135,4 @@ public class SearchProjectPermissionsDataLoader {
       return component.getId();
     }
   }
-
-  private static class ResourceTypeToQualifierFunction implements Function<ResourceType, String> {
-    @Override
-    public String apply(@Nonnull ResourceType resourceType) {
-      return resourceType.getQualifier();
-    }
-  }
 }
index b54beb3e14f133cd6f55da7cd50f553623cab718..688e3bf3c705f0a8017ecb98825f68c03126e89f 100644 (file)
@@ -20,6 +20,7 @@
 
 package org.sonar.server.startup;
 
+import org.sonar.api.resources.Qualifiers;
 import org.sonar.api.security.DefaultGroups;
 import org.sonar.api.utils.log.Logger;
 import org.sonar.api.utils.log.Loggers;
@@ -32,10 +33,10 @@ import org.sonar.db.permission.PermissionTemplateDto;
 import org.sonar.db.user.GroupDto;
 import org.sonar.server.platform.PersistentSettings;
 
-public class RegisterPermissionTemplates {
+import static org.sonar.server.permission.DefaultPermissionTemplates.DEFAULT_TEMPLATE_PROPERTY;
+import static org.sonar.server.permission.DefaultPermissionTemplates.defaultRootQualifierTemplateProperty;
 
-  public static final String DEFAULT_TEMPLATE_PROPERTY = "sonar.permission.template.default";
-  public static final String DEFAULT_PROJECTS_TEMPLATE_PROPERTY = "sonar.permission.template.TRK.default";
+public class RegisterPermissionTemplates {
 
   private static final Logger LOG = Loggers.get(RegisterPermissionTemplates.class);
 
@@ -52,7 +53,7 @@ public class RegisterPermissionTemplates {
 
     if (shouldRegister()) {
       if (hasExistingPermissionsConfig()) {
-        String projectsPermissionsKey = settings.getString(DEFAULT_PROJECTS_TEMPLATE_PROPERTY);
+        String projectsPermissionsKey = settings.getString(defaultRootQualifierTemplateProperty(Qualifiers.PROJECT));
         setDefaultProperty(projectsPermissionsKey);
       } else {
         insertDefaultTemplate();
@@ -64,7 +65,7 @@ public class RegisterPermissionTemplates {
   }
 
   private boolean hasExistingPermissionsConfig() {
-    return settings.getString(DEFAULT_PROJECTS_TEMPLATE_PROPERTY) != null;
+    return settings.getString(defaultRootQualifierTemplateProperty(Qualifiers.PROJECT)) != null;
   }
 
   private boolean shouldRegister() {
index b3592ca78a2489d0d0086d79cb4836c210a4472d..36cf19fc38edae2c05b8b9ab95d0a5adc2f997e7 100644 (file)
@@ -264,7 +264,7 @@ public class PermissionFinderTest {
 
   @Test
   public void find_users_from_permission_template() {
-    when(permissionTemplateDao.selectByKey(anyString())).thenReturn(new PermissionTemplateDto().setId(1L).setKee("my_template"));
+    when(permissionTemplateDao.selectByUuid(anyString())).thenReturn(new PermissionTemplateDto().setId(1L).setKee("my_template"));
 
     when(permissionTemplateDao.selectUsers(any(DbSession.class), any(PermissionQuery.class), anyLong(), anyInt(), anyInt())).thenReturn(
       newArrayList(new UserWithPermissionDto().setName("user1").setPermission("user"))
@@ -279,7 +279,7 @@ public class PermissionFinderTest {
 
   @Test
   public void fail_to_find_users_from_permission_template_when_template_not_found() {
-    when(permissionTemplateDao.selectByKey(anyString())).thenReturn(null);
+    when(permissionTemplateDao.selectByUuid(anyString())).thenReturn(null);
 
     try {
       underTest.findUsersWithPermissionTemplate(PermissionQuery.builder().permission("user").template("Unknown").build());
@@ -291,7 +291,7 @@ public class PermissionFinderTest {
 
   @Test
   public void find_groups_from_permission_template() {
-    when(permissionTemplateDao.selectByKey(anyString())).thenReturn(new PermissionTemplateDto().setId(1L).setKee("my_template"));
+    when(permissionTemplateDao.selectByUuid(anyString())).thenReturn(new PermissionTemplateDto().setId(1L).setKee("my_template"));
 
     when(permissionTemplateDao.selectGroups(any(DbSession.class), any(PermissionQuery.class), anyLong())).thenReturn(
       newArrayList(new GroupWithPermissionDto().setName("users").setPermission("user"))
@@ -305,7 +305,7 @@ public class PermissionFinderTest {
 
   @Test
   public void fail_to_find_groups_from_permission_template_when_template_not_found() {
-    when(permissionTemplateDao.selectByKey(anyString())).thenReturn(null);
+    when(permissionTemplateDao.selectByUuid(anyString())).thenReturn(null);
 
     try {
       underTest.findGroupsWithPermissionTemplate(PermissionQuery.builder().permission("user").template("Unknown").build());
index 02cdf8b6c19b22711641624d5984b63ec9d7c82d..6dd8aab018512718c0deff3fba86f616ceb66df2 100644 (file)
@@ -147,11 +147,11 @@ public class PermissionTemplateServiceTest {
 
   @Test
   public void should_delete_permission_template() {
-    when(permissionTemplateDao.selectByKey(DEFAULT_KEY)).thenReturn(DEFAULT_TEMPLATE);
+    when(permissionTemplateDao.selectByUuid(DEFAULT_KEY)).thenReturn(DEFAULT_TEMPLATE);
 
     underTest.deletePermissionTemplate(1L);
 
-    verify(permissionTemplateDao, times(1)).deleteById(1L);
+    verify(permissionTemplateDao).deleteById(any(DbSession.class), eq(1L));
   }
 
   @Test
@@ -177,7 +177,7 @@ public class PermissionTemplateServiceTest {
       .setUsersPermissions(usersPermissions)
       .setGroupsByPermission(groupsPermissions);
 
-    when(permissionTemplateDao.selectByKeyWithUserAndGroupPermissions("my template")).thenReturn(permissionTemplateDto);
+    when(permissionTemplateDao.selectByUuidWithUserAndGroupPermissions("my template")).thenReturn(permissionTemplateDto);
 
     PermissionTemplate permissionTemplate = underTest.selectPermissionTemplate("my template");
 
@@ -271,7 +271,7 @@ public class PermissionTemplateServiceTest {
   public void should_add_user_permission() {
     UserDto userDto = new UserDto().setId(1L).setLogin("user").setName("user");
     when(userDao.selectActiveUserByLogin("user")).thenReturn(userDto);
-    when(permissionTemplateDao.selectByKey(DEFAULT_KEY)).thenReturn(DEFAULT_TEMPLATE);
+    when(permissionTemplateDao.selectByUuid(DEFAULT_KEY)).thenReturn(DEFAULT_TEMPLATE);
 
     underTest.addUserPermission(DEFAULT_KEY, DEFAULT_PERMISSION, "user");
 
@@ -283,7 +283,7 @@ public class PermissionTemplateServiceTest {
     expected.expect(BadRequestException.class);
     expected.expectMessage("Unknown user:");
 
-    when(permissionTemplateDao.selectByKey(DEFAULT_KEY)).thenReturn(DEFAULT_TEMPLATE);
+    when(permissionTemplateDao.selectByUuid(DEFAULT_KEY)).thenReturn(DEFAULT_TEMPLATE);
     when(userDao.selectActiveUserByLogin("unknown")).thenReturn(null);
 
     underTest.addUserPermission(DEFAULT_KEY, DEFAULT_PERMISSION, "unknown");
@@ -293,7 +293,7 @@ public class PermissionTemplateServiceTest {
   public void should_remove_user_permission() {
     UserDto userDto = new UserDto().setId(1L).setLogin("user").setName("user");
     when(userDao.selectActiveUserByLogin("user")).thenReturn(userDto);
-    when(permissionTemplateDao.selectByKey(DEFAULT_KEY)).thenReturn(DEFAULT_TEMPLATE);
+    when(permissionTemplateDao.selectByUuid(DEFAULT_KEY)).thenReturn(DEFAULT_TEMPLATE);
 
     underTest.removeUserPermission(DEFAULT_KEY, DEFAULT_PERMISSION, "user");
 
@@ -304,7 +304,7 @@ public class PermissionTemplateServiceTest {
   public void should_add_group_permission() {
     GroupDto groupDto = new GroupDto().setId(1L).setName("group");
     when(groupDao.selectByName(any(DbSession.class), eq("group"))).thenReturn(groupDto);
-    when(permissionTemplateDao.selectByKey(DEFAULT_KEY)).thenReturn(DEFAULT_TEMPLATE);
+    when(permissionTemplateDao.selectByUuid(DEFAULT_KEY)).thenReturn(DEFAULT_TEMPLATE);
 
     underTest.addGroupPermission(DEFAULT_KEY, DEFAULT_PERMISSION, "group");
 
@@ -316,7 +316,7 @@ public class PermissionTemplateServiceTest {
     expected.expect(BadRequestException.class);
     expected.expectMessage("Unknown group:");
 
-    when(permissionTemplateDao.selectByKey(DEFAULT_KEY)).thenReturn(DEFAULT_TEMPLATE);
+    when(permissionTemplateDao.selectByUuid(DEFAULT_KEY)).thenReturn(DEFAULT_TEMPLATE);
     when(groupDao.selectByName(any(DbSession.class), eq("unknown"))).thenReturn(null);
 
     underTest.addGroupPermission(DEFAULT_KEY, DEFAULT_PERMISSION, "unknown");
@@ -326,7 +326,7 @@ public class PermissionTemplateServiceTest {
   public void should_remove_group_permission() {
     GroupDto groupDto = new GroupDto().setId(1L).setName("group");
     when(groupDao.selectByName(any(DbSession.class), eq("group"))).thenReturn(groupDto);
-    when(permissionTemplateDao.selectByKey(DEFAULT_KEY)).thenReturn(DEFAULT_TEMPLATE);
+    when(permissionTemplateDao.selectByUuid(DEFAULT_KEY)).thenReturn(DEFAULT_TEMPLATE);
 
     underTest.removeGroupPermission(DEFAULT_KEY, DEFAULT_PERMISSION, "group");
 
@@ -335,7 +335,7 @@ public class PermissionTemplateServiceTest {
 
   @Test
   public void should_add_permission_to_anyone_group() {
-    when(permissionTemplateDao.selectByKey(DEFAULT_KEY)).thenReturn(DEFAULT_TEMPLATE);
+    when(permissionTemplateDao.selectByUuid(DEFAULT_KEY)).thenReturn(DEFAULT_TEMPLATE);
 
     underTest.addGroupPermission(DEFAULT_KEY, DEFAULT_PERMISSION, "Anyone");
 
@@ -345,7 +345,7 @@ public class PermissionTemplateServiceTest {
 
   @Test
   public void should_remove_permission_from_anyone_group() {
-    when(permissionTemplateDao.selectByKey(DEFAULT_KEY)).thenReturn(DEFAULT_TEMPLATE);
+    when(permissionTemplateDao.selectByUuid(DEFAULT_KEY)).thenReturn(DEFAULT_TEMPLATE);
 
     underTest.removeGroupPermission(DEFAULT_KEY, DEFAULT_PERMISSION, "Anyone");
 
index 270bf15228e2abfdc4510ed444bf5fb64179994c..2e346fe58ce7f3f9ea5b09d6e64b7f4fa700c278 100644 (file)
@@ -76,7 +76,7 @@ public class PermissionTemplateUpdaterTest {
   public void should_execute_on_valid_parameters() {
 
     final PermissionTemplateDao permissionTemplateDao = mock(PermissionTemplateDao.class);
-    when(permissionTemplateDao.selectByKey("my_template")).thenReturn(new PermissionTemplateDto().setId(1L));
+    when(permissionTemplateDao.selectByUuid("my_template")).thenReturn(new PermissionTemplateDto().setId(1L));
     when(dbClient.permissionTemplateDao()).thenReturn(permissionTemplateDao);
 
     PermissionTemplateUpdater updater =
@@ -97,7 +97,7 @@ public class PermissionTemplateUpdaterTest {
     expected.expectMessage("Unknown template:");
 
     final PermissionTemplateDao permissionTemplateDao = mock(PermissionTemplateDao.class);
-    when(permissionTemplateDao.selectByKey("my_template")).thenReturn(null);
+    when(permissionTemplateDao.selectByUuid("my_template")).thenReturn(null);
 
     PermissionTemplateUpdater updater =
       new PermissionTemplateUpdater(dbClient, userSessionRule, "my_template", UserRole.USER, "user") {
@@ -113,7 +113,7 @@ public class PermissionTemplateUpdaterTest {
     expected.expect(BadRequestException.class);
 
     final PermissionTemplateDao permissionTemplateDao = mock(PermissionTemplateDao.class);
-    when(permissionTemplateDao.selectByKey("my_template")).thenReturn(new PermissionTemplateDto().setId(1L));
+    when(permissionTemplateDao.selectByUuid("my_template")).thenReturn(new PermissionTemplateDto().setId(1L));
     when(dbClient.permissionTemplateDao()).thenReturn(permissionTemplateDao);
 
     PermissionTemplateUpdater updater =
index 559d46605727e5cb5a81d0f0a495fb5d6a6885ac..16c4e5ea5935e67c6f5d7937461f9a1658ecf304 100644 (file)
@@ -189,7 +189,7 @@ public class AddGroupToTemplateActionTest {
   @Test
   public void fail_if_template_key_does_not_exist() {
     expectedException.expect(NotFoundException.class);
-    expectedException.expectMessage("Permission template with key 'unknown-key' is not found");
+    expectedException.expectMessage("Permission template with id 'unknown-key' is not found");
 
     newRequest(GROUP_NAME, "unknown-key", CODEVIEWER);
   }
index 5f4afa4bb4dd4787e9f56e5b86754bbd9c9ea7c7..023da2d085424b205cd1f3500fdb912f6ebb0147 100644 (file)
@@ -157,7 +157,7 @@ public class AddUserToTemplateActionTest {
   @Test
   public void fail_if_template_key_does_not_exist() {
     expectedException.expect(NotFoundException.class);
-    expectedException.expectMessage("Permission template with key 'unknown-key' is not found");
+    expectedException.expectMessage("Permission template with id 'unknown-key' is not found");
 
     newRequest(USER_LOGIN, "unknown-key", CODEVIEWER);
   }
diff --git a/server/sonar-server/src/test/java/org/sonar/server/permission/ws/DefaultPermissionTemplateFinderTest.java b/server/sonar-server/src/test/java/org/sonar/server/permission/ws/DefaultPermissionTemplateFinderTest.java
new file mode 100644 (file)
index 0000000..c7425eb
--- /dev/null
@@ -0,0 +1,92 @@
+/*
+ * SonarQube, open source software quality management tool.
+ * Copyright (C) 2008-2014 SonarSource
+ * mailto:contact AT sonarsource DOT com
+ *
+ * SonarQube 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.
+ *
+ * SonarQube 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.ws;
+
+import java.util.Collections;
+import java.util.List;
+import java.util.Set;
+import org.junit.Before;
+import org.junit.Test;
+import org.sonar.api.config.Settings;
+import org.sonar.api.resources.Qualifiers;
+import org.sonar.api.resources.ResourceType;
+import org.sonar.api.resources.ResourceTypes;
+
+import static java.util.Arrays.asList;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+import static org.sonar.server.permission.DefaultPermissionTemplates.DEFAULT_TEMPLATE_PROPERTY;
+import static org.sonar.server.permission.DefaultPermissionTemplates.defaultRootQualifierTemplateProperty;
+
+public class DefaultPermissionTemplateFinderTest {
+
+  ResourceTypes resourceTypes = mock(ResourceTypes.class);
+  Settings settings = new Settings();
+
+  DefaultPermissionTemplateFinder underTest;
+
+  @Before
+  public void setUp() {
+    underTest = new DefaultPermissionTemplateFinder(settings, resourceTypes);
+    settings
+      .setProperty(DEFAULT_TEMPLATE_PROPERTY, "default-template-uuid")
+      .setProperty(defaultRootQualifierTemplateProperty(Qualifiers.PROJECT), "default-project-template-uuid")
+      .setProperty(defaultRootQualifierTemplateProperty("DEV"), "default-dev-template-uuid")
+      .setProperty(defaultRootQualifierTemplateProperty(Qualifiers.VIEW), "default-view-template-uuid");
+    when(resourceTypes.getRoots()).thenReturn(rootResourceTypes());
+  }
+
+  @Test
+  public void get_default_template_uuids_in_settings() {
+    Set<String> result = underTest.getDefaultTemplateUuids();
+
+    assertThat(result).containsOnly("default-template-uuid", "default-project-template-uuid", "default-view-template-uuid", "default-dev-template-uuid");
+  }
+
+  @Test
+  public void get_default_template_uuid_if_no_root_resource() {
+    when(resourceTypes.getRoots()).thenReturn(Collections.<ResourceType>emptySet());
+
+    Set<String> result = underTest.getDefaultTemplateUuids();
+
+    assertThat(result).containsOnly("default-template-uuid");
+  }
+
+  @Test
+  public void get_default_template_uuid_if_no_property() {
+    settings = new Settings();
+    settings.setProperty(DEFAULT_TEMPLATE_PROPERTY, "default-template-uuid");
+    underTest = new DefaultPermissionTemplateFinder(settings, resourceTypes);
+
+    Set<String> result = underTest.getDefaultTemplateUuids();
+
+    assertThat(result).containsOnly("default-template-uuid");
+  }
+
+  private static List<ResourceType> rootResourceTypes() {
+    ResourceType project = ResourceType.builder(Qualifiers.PROJECT).build();
+    ResourceType view = ResourceType.builder(Qualifiers.VIEW).build();
+    ResourceType dev = ResourceType.builder("DEV").build();
+
+    return asList(project, view, dev);
+  }
+}
index ce7bf055326584a362fa95a259915ee704475af6..319a7e1fa2237d983be5abe8eb160248e6fe535f 100644 (file)
 
 package org.sonar.server.permission.ws;
 
+import java.util.Collections;
 import javax.annotation.Nullable;
 import org.junit.Before;
 import org.junit.Rule;
 import org.junit.Test;
 import org.junit.rules.ExpectedException;
 import org.sonar.api.utils.System2;
+import org.sonar.api.web.UserRole;
 import org.sonar.core.permission.GlobalPermissions;
 import org.sonar.db.DbClient;
 import org.sonar.db.DbSession;
 import org.sonar.db.DbTester;
 import org.sonar.db.permission.PermissionTemplateDto;
+import org.sonar.db.user.GroupDto;
+import org.sonar.db.user.GroupTesting;
+import org.sonar.db.user.UserDto;
+import org.sonar.db.user.UserTesting;
+import org.sonar.server.component.ComponentFinder;
+import org.sonar.server.exceptions.BadRequestException;
 import org.sonar.server.exceptions.ForbiddenException;
+import org.sonar.server.exceptions.NotFoundException;
 import org.sonar.server.exceptions.UnauthorizedException;
 import org.sonar.server.tester.UserSessionRule;
 import org.sonar.server.ws.TestRequest;
@@ -39,12 +48,15 @@ import org.sonar.server.ws.TestResponse;
 import org.sonar.server.ws.WsActionTester;
 
 import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+import static org.mockito.internal.util.collections.Sets.newSet;
 import static org.sonar.db.permission.PermissionTemplateTesting.newPermissionTemplateDto;
 import static org.sonar.server.permission.ws.Parameters.PARAM_TEMPLATE_ID;
 
 public class DeleteTemplateActionTest {
 
-  static final String TEMPLATE_KEY = "permission-template-key";
+  static final String TEMPLATE_UUID = "permission-template-uuid";
 
   @Rule
   public DbTester db = DbTester.create(System2.INSTANCE);
@@ -56,6 +68,8 @@ public class DeleteTemplateActionTest {
   WsActionTester ws;
   DbClient dbClient;
   DbSession dbSession;
+  DefaultPermissionTemplateFinder defautTemplatePermissionFinder;
+
   PermissionTemplateDto permissionTemplate;
 
   @Before
@@ -64,20 +78,40 @@ public class DeleteTemplateActionTest {
 
     dbClient = db.getDbClient();
     dbSession = db.getSession();
-    ws = new WsActionTester(new DeleteTemplateAction(dbClient, userSession));
-
-    permissionTemplate = insertTemplate(newPermissionTemplateDto().setKee("permission-template-key"));
-    commit();
-    assertThat(dbClient.permissionTemplateDao().selectByKey(dbSession, TEMPLATE_KEY)).isNotNull();
+    defautTemplatePermissionFinder = mock(DefaultPermissionTemplateFinder.class);
+    when(defautTemplatePermissionFinder.getDefaultTemplateUuids()).thenReturn(Collections.<String>emptySet());
+    PermissionDependenciesFinder finder = new PermissionDependenciesFinder(dbClient, new ComponentFinder(dbClient));
+    ws = new WsActionTester(new DeleteTemplateAction(dbClient, userSession, finder, defautTemplatePermissionFinder));
+
+    permissionTemplate = insertTemplateAndAssociatedPermissions(newPermissionTemplateDto().setKee(TEMPLATE_UUID));
+    PermissionTemplateDto permissionTemplateInDatabase = dbClient.permissionTemplateDao().selectByUuidWithUserAndGroupPermissions(dbSession, TEMPLATE_UUID);
+    assertThat(permissionTemplateInDatabase.getKee()).isEqualTo(TEMPLATE_UUID);
+    assertThat(permissionTemplateInDatabase.getGroupsPermissions()).isNotEmpty();
+    assertThat(permissionTemplateInDatabase.getUsersPermissions()).isNotEmpty();
   }
 
   @Test
   public void delete_template_in_db() {
-
-    TestResponse result = newRequest(TEMPLATE_KEY);
+    TestResponse result = newRequest(TEMPLATE_UUID);
 
     assertThat(result.getInput()).isEmpty();
-    assertThat(dbClient.permissionTemplateDao().selectByKey(dbSession, TEMPLATE_KEY)).isNull();
+    assertThat(dbClient.permissionTemplateDao().selectByUuidWithUserAndGroupPermissions(dbSession, TEMPLATE_UUID)).isNull();
+  }
+
+  @Test
+  public void fail_if_uuid_is_not_known() {
+    expectedException.expect(NotFoundException.class);
+
+    newRequest("unknown-template-uuid");
+  }
+
+  @Test
+  public void fail_if_template_is_default() {
+    expectedException.expect(BadRequestException.class);
+    expectedException.expectMessage("It is not possible to delete a default template");
+    when(defautTemplatePermissionFinder.getDefaultTemplateUuids()).thenReturn(newSet(TEMPLATE_UUID));
+
+    newRequest(TEMPLATE_UUID);
   }
 
   @Test
@@ -85,7 +119,7 @@ public class DeleteTemplateActionTest {
     expectedException.expect(UnauthorizedException.class);
     userSession.anonymous();
 
-    newRequest(TEMPLATE_KEY);
+    newRequest(TEMPLATE_UUID);
   }
 
   @Test
@@ -93,28 +127,35 @@ public class DeleteTemplateActionTest {
     expectedException.expect(ForbiddenException.class);
     userSession.login().setGlobalPermissions(GlobalPermissions.QUALITY_PROFILE_ADMIN);
 
-    newRequest(TEMPLATE_KEY);
+    newRequest(TEMPLATE_UUID);
   }
 
   @Test
-  public void fail_if_key_is_not_provided() {
+  public void fail_if_uuid_is_not_provided() {
     expectedException.expect(IllegalArgumentException.class);
 
     newRequest(null);
   }
 
-  private PermissionTemplateDto insertTemplate(PermissionTemplateDto template) {
-    return dbClient.permissionTemplateDao().insert(dbSession, template);
+  private PermissionTemplateDto insertTemplateAndAssociatedPermissions(PermissionTemplateDto template) {
+    dbClient.permissionTemplateDao().insert(dbSession, template);
+    UserDto user = dbClient.userDao().insert(dbSession, UserTesting.newUserDto().setActive(true));
+    GroupDto group = dbClient.groupDao().insert(dbSession, GroupTesting.newGroupDto());
+    dbClient.permissionTemplateDao().insertUserPermission(dbSession, template.getId(), user.getId(), UserRole.ADMIN);
+    dbClient.permissionTemplateDao().insertGroupPermission(dbSession, template.getId(), group.getId(), UserRole.CODEVIEWER);
+    commit();
+
+    return template;
   }
 
   private void commit() {
     dbSession.commit();
   }
 
-  private TestResponse newRequest(@Nullable String key) {
+  private TestResponse newRequest(@Nullable String id) {
     TestRequest request = ws.newRequest();
-    if (key != null) {
-      request.setParam(PARAM_TEMPLATE_ID, key);
+    if (id != null) {
+      request.setParam(PARAM_TEMPLATE_ID, id);
     }
 
     TestResponse result = executeRequest(request);
index 69eadbe065f88f9106c822813f58b494dd846471..c8c59d230901cc44f346b28de3fff7f5f774ea2f 100644 (file)
@@ -30,6 +30,6 @@ public class PermissionsWsModuleTest {
   public void verify_count_of_added_components() {
     ComponentContainer container = new ComponentContainer();
     new PermissionsWsModule().configure(container);
-    assertThat(container.size()).isEqualTo(21);
+    assertThat(container.size()).isEqualTo(22);
   }
 }
index 28e64178f61f0f07e4fc15151594ab320fdb4c03..9d2da24e995a27565bb8295349f6e8d36b7dc48d 100644 (file)
@@ -189,7 +189,7 @@ public class RemoveGroupFromTemplateActionTest {
   @Test
   public void fail_if_template_key_does_not_exist() {
     expectedException.expect(NotFoundException.class);
-    expectedException.expectMessage("Permission template with key 'unknown-key' is not found");
+    expectedException.expectMessage("Permission template with id 'unknown-key' is not found");
 
     newRequest(GROUP_NAME, "unknown-key", PERMISSION);
   }
index 7b42bab1fd17b948603f8ad3956f1ce10098d89e..08ffe9ca61bb018c46c7fcc75d12e303070d689f 100644 (file)
@@ -181,7 +181,7 @@ public class RemoveUserFromTemplateActionTest {
   @Test
   public void fail_if_template_key_does_not_exist() {
     expectedException.expect(NotFoundException.class);
-    expectedException.expectMessage("Permission template with key 'unknown-key' is not found");
+    expectedException.expectMessage("Permission template with id 'unknown-key' is not found");
 
     newRequest(USER_LOGIN, "unknown-key", DEFAULT_PERMISSION);
   }
index e9c1afa6f6d36f5186c0a96c9b3809bba42a2410..684f96ed564f4363fc188f0260db1642a218f737 100644 (file)
@@ -108,7 +108,7 @@ public class UpdateTemplateActionTest {
   public void update_with_the_same_values() {
     newRequest(templateDto.getKee(), templateDto.getName(), templateDto.getDescription(), templateDto.getKeyPattern());
 
-    PermissionTemplateDto updatedTemplate = dbClient.permissionTemplateDao().selectByKey(dbSession, templateDto.getKee());
+    PermissionTemplateDto updatedTemplate = dbClient.permissionTemplateDao().selectByUuid(dbSession, templateDto.getKee());
     assertThat(updatedTemplate.getName()).isEqualTo(templateDto.getName());
     assertThat(updatedTemplate.getDescription()).isEqualTo(templateDto.getDescription());
     assertThat(updatedTemplate.getKeyPattern()).isEqualTo(templateDto.getKeyPattern());
@@ -127,7 +127,7 @@ public class UpdateTemplateActionTest {
   @Test
   public void fail_if_key_is_not_found() {
     expectedException.expect(NotFoundException.class);
-    expectedException.expectMessage("Permission template with key 'unknown-key' is not found");
+    expectedException.expectMessage("Permission template with id 'unknown-key' is not found");
 
     newRequest("unknown-key", null, null, null);
   }
index 5c6078572957fd2ca0deb021147028e148023e43..750248d7dc9f4464aecf60a44434bd19945f44f1 100644 (file)
@@ -24,6 +24,7 @@ import org.hamcrest.BaseMatcher;
 import org.hamcrest.Description;
 import org.junit.Before;
 import org.junit.Test;
+import org.sonar.api.resources.Qualifiers;
 import org.sonar.api.security.DefaultGroups;
 import org.sonar.api.web.UserRole;
 import org.sonar.db.DbClient;
@@ -46,6 +47,8 @@ import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.verifyNoMoreInteractions;
 import static org.mockito.Mockito.verifyZeroInteractions;
 import static org.mockito.Mockito.when;
+import static org.sonar.server.permission.DefaultPermissionTemplates.DEFAULT_TEMPLATE_PROPERTY;
+import static org.sonar.server.permission.DefaultPermissionTemplates.defaultRootQualifierTemplateProperty;
 
 public class RegisterPermissionTemplatesTest {
 
@@ -94,7 +97,7 @@ public class RegisterPermissionTemplatesTest {
     verify(permissionTemplateDao).insertGroupPermission(1L, null, UserRole.USER);
     verify(permissionTemplateDao).insertGroupPermission(1L, null, UserRole.CODEVIEWER);
     verifyNoMoreInteractions(permissionTemplateDao);
-    verify(settings).saveProperty(RegisterPermissionTemplates.DEFAULT_TEMPLATE_PROPERTY, PermissionTemplateDto.DEFAULT.getKee());
+    verify(settings).saveProperty(DEFAULT_TEMPLATE_PROPERTY, PermissionTemplateDto.DEFAULT.getKee());
   }
 
   @Test
@@ -111,7 +114,7 @@ public class RegisterPermissionTemplatesTest {
 
   @Test
   public void should_reference_TRK_template_as_default_when_present() {
-    when(settings.getString(RegisterPermissionTemplates.DEFAULT_PROJECTS_TEMPLATE_PROPERTY)).thenReturn("my_projects_template");
+    when(settings.getString(defaultRootQualifierTemplateProperty(Qualifiers.PROJECT))).thenReturn("my_projects_template");
 
     LoadedTemplateDto expectedTemplate = new LoadedTemplateDto().setKey(PermissionTemplateDto.DEFAULT.getKee())
       .setType(LoadedTemplateDto.PERMISSION_TEMPLATE_TYPE);
@@ -120,7 +123,7 @@ public class RegisterPermissionTemplatesTest {
     initializer.start();
 
     verify(loadedTemplateDao).insert(argThat(Matches.template(expectedTemplate)));
-    verify(settings).saveProperty(RegisterPermissionTemplates.DEFAULT_TEMPLATE_PROPERTY, "my_projects_template");
+    verify(settings).saveProperty(DEFAULT_TEMPLATE_PROPERTY, "my_projects_template");
     verifyZeroInteractions(permissionTemplateDao);
   }
 
index 669b43f9be15b1a82ab40212b9086812a13fb249..a2f576c40b18daec6cc3972299e87c6a771200aa 100644 (file)
@@ -25,7 +25,7 @@ package org.sonar.db;
  * When selecting by id or key, the methods respect one of the following pattern:
  * <ul>
  *   <li>selectOrFailByKey return the element or throws a RowNotFoundException</li>
- *   <li>selectByKey return an Optional (now) or a nullable element (legacy)</li>
+ *   <li>selectByUuid return an Optional (now) or a nullable element (legacy)</li>
  * </ul>
  */
 public class RowNotFoundException extends RuntimeException {
index 3ea563637d9666b102e3793a35cb38a6165da95a..3700d39a1cefe301104d38beaf125bf1c8e27548 100644 (file)
@@ -126,25 +126,25 @@ public class PermissionTemplateDao implements Dao {
   }
 
   @CheckForNull
-  public PermissionTemplateDto selectByKey(DbSession session, String templateKey) {
-    return mapper(session).selectByKey(templateKey);
+  public PermissionTemplateDto selectByUuid(DbSession session, String templateKey) {
+    return mapper(session).selectByUuid(templateKey);
   }
 
   @CheckForNull
-  public PermissionTemplateDto selectByKey(String templateKey) {
+  public PermissionTemplateDto selectByUuid(String templateKey) {
     DbSession session = myBatis.openSession(false);
     try {
-      return selectByKey(session, templateKey);
+      return selectByUuid(session, templateKey);
     } finally {
       MyBatis.closeQuietly(session);
     }
   }
 
   @CheckForNull
-  public PermissionTemplateDto selectByKeyWithUserAndGroupPermissions(DbSession session, String templateKey) {
+  public PermissionTemplateDto selectByUuidWithUserAndGroupPermissions(DbSession session, String templateKey) {
     PermissionTemplateDto permissionTemplate = null;
     PermissionTemplateMapper mapper = mapper(session);
-    permissionTemplate = mapper.selectByKey(templateKey);
+    permissionTemplate = mapper.selectByUuid(templateKey);
     PermissionTemplateDto templateUsersPermissions = mapper.selectTemplateUsersPermissions(templateKey);
     if (templateUsersPermissions != null) {
       permissionTemplate.setUsersPermissions(templateUsersPermissions.getUsersPermissions());
@@ -157,10 +157,10 @@ public class PermissionTemplateDao implements Dao {
   }
 
   @CheckForNull
-  public PermissionTemplateDto selectByKeyWithUserAndGroupPermissions(String templateKey) {
+  public PermissionTemplateDto selectByUuidWithUserAndGroupPermissions(String templateKey) {
     DbSession session = myBatis.openSession(false);
     try {
-      return selectByKeyWithUserAndGroupPermissions(session, templateKey);
+      return selectByUuidWithUserAndGroupPermissions(session, templateKey);
     } finally {
       MyBatis.closeQuietly(session);
     }
@@ -186,21 +186,11 @@ public class PermissionTemplateDao implements Dao {
     return permissionTemplate;
   }
 
-  public void deleteByKey(DbSession dbSession, String key) {
-    mapper(dbSession).deleteByKey(key);
-  }
-
-  public void deleteById(Long templateId) {
-    SqlSession session = myBatis.openSession(false);
-    try {
-      PermissionTemplateMapper mapper = mapper(session);
-      mapper.deleteUsersPermissions(templateId);
-      mapper.deleteGroupsPermissions(templateId);
-      mapper.delete(templateId);
-      session.commit();
-    } finally {
-      MyBatis.closeQuietly(session);
-    }
+  public void deleteById(DbSession session, long templateId) {
+    PermissionTemplateMapper mapper = mapper(session);
+    mapper.deleteUserPermissions(templateId);
+    mapper.deleteGroupPermissions(templateId);
+    mapper.delete(templateId);
   }
 
   /**
@@ -319,25 +309,32 @@ public class PermissionTemplateDao implements Dao {
     session.commit();
   }
 
+  public void deleteGroupPermissions(DbSession session, long templateId) {
+    mapper(session).deleteGroupPermissions(templateId);
+  }
+
+  public void deleteUserPermissions(DbSession session, long templateId) {
+    mapper(session).deleteUserPermissions(templateId);
+  }
+
   /**
    * Load permission template and load associated collections of users and groups permissions
    */
   @VisibleForTesting
   PermissionTemplateDto selectPermissionTemplateWithPermissions(DbSession session, String templateKey) {
-    PermissionTemplateDto permissionTemplateDto = selectByKey(session, templateKey);
+    PermissionTemplateDto permissionTemplateDto = selectByUuid(session, templateKey);
     if (permissionTemplateDto == null) {
       throw new IllegalArgumentException("Could not retrieve permission template with key " + templateKey);
     }
-    PermissionTemplateDto templateWithPermissions = selectByKeyWithUserAndGroupPermissions(session, permissionTemplateDto.getKee());
+    PermissionTemplateDto templateWithPermissions = selectByUuidWithUserAndGroupPermissions(session, permissionTemplateDto.getKee());
     if (templateWithPermissions == null) {
       throw new IllegalArgumentException("Could not retrieve permissions for template with key " + templateKey);
     }
     return templateWithPermissions;
   }
 
-  public PermissionTemplateDto selectByName(DbSession dbSession, String templateName) {
-    char wildcard = '%';
-    return mapper(dbSession).selectByName(wildcard + templateName.toUpperCase() + wildcard);
+  public PermissionTemplateDto selectByName(DbSession dbSession, String name) {
+    return mapper(dbSession).selectByName(name.toUpperCase());
   }
 
   /**
index 536a79afbb5fe7d68bd26185d1ae2aeec9480a43..d4006be65e9ed7aaadde3b3340bee9566342e76a 100644 (file)
@@ -35,11 +35,15 @@ public interface PermissionTemplateMapper {
 
   void delete(long templateId);
 
-  void deleteUsersPermissions(long templateId);
+  void deleteUserPermissions(long templateId);
 
-  void deleteGroupsPermissions(long templateId);
+  void deleteUserPermission(PermissionTemplateUserDto permissionTemplateUser);
+
+  void deleteGroupPermissions(long templateId);
 
-  PermissionTemplateDto selectByKey(String templateKey);
+  void deleteGroupPermission(PermissionTemplateGroupDto permissionTemplateGroup);
+
+  PermissionTemplateDto selectByUuid(String templateUuid);
 
   PermissionTemplateDto selectTemplateUsersPermissions(String templateKey);
 
@@ -47,12 +51,8 @@ public interface PermissionTemplateMapper {
 
   void insertUserPermission(PermissionTemplateUserDto permissionTemplateUser);
 
-  void deleteUserPermission(PermissionTemplateUserDto permissionTemplateUser);
-
   void insertGroupPermission(PermissionTemplateGroupDto permissionTemplateGroup);
 
-  void deleteGroupPermission(PermissionTemplateGroupDto permissionTemplateGroup);
-
   void deleteByGroupId(long groupId);
 
   List<GroupWithPermissionDto> selectGroups(Map<String, Object> params);
@@ -64,6 +64,4 @@ public interface PermissionTemplateMapper {
   int countUsers(Map<String, Object> params);
 
   int countGroups(Map<String, Object> parameters);
-
-  void deleteByKey(String key);
 }
index 9eb1a4850c65b3c7442841cba2b85af62861d517..7381e9e761650b3fb0607007b09437a821adfe5b 100644 (file)
     WHERE id = #{templateId}
   </delete>
 
-  <delete id="deleteByKey" parameterType="string">
-    DELETE FROM permission_templates
-    WHERE kee = #{key}
-  </delete>
-
-  <delete id="deleteUsersPermissions" parameterType="long">
+  <delete id="deleteUserPermissions" parameterType="long">
     DELETE FROM perm_templates_users
     WHERE template_id = #{templateId}
   </delete>
 
-  <delete id="deleteGroupsPermissions" parameterType="long">
+  <delete id="deleteGroupPermissions" parameterType="long">
     DELETE FROM perm_templates_groups
     WHERE template_id = #{templateId}
   </delete>
     id, name, kee, description, key_pattern AS keyPattern, created_at AS createdAt, updated_at AS updatedAt
   </sql>
 
-  <select id="selectByKey" parameterType="String" resultType="PermissionTemplate">
+  <select id="selectByUuid" parameterType="String" resultType="PermissionTemplate">
     SELECT
     <include refid="templateColumns"/>
     FROM permission_templates
-    WHERE kee = #{kee}
+    WHERE kee=#{uuid}
   </select>
 
   <select id="selectAllPermissionTemplates" resultType="PermissionTemplate">
     SELECT
     <include refid="templateColumns"/>
     FROM permission_templates
-    WHERE UPPER(name) LIKE #{templateName} ESCAPE '/'
+    WHERE UPPER(name)=#{templateName}
   </select>
 
   <select id="selectTemplateUsersPermissions" parameterType="String" resultMap="fullPermissionsTemplateResult">
index 526892b5c8b818dbc5f14f6135efce6602f8dec3..b75c082da79f7fb7a235d069a6d6e7bd21fd7f86 100644 (file)
@@ -96,7 +96,7 @@ public class PermissionTemplateDaoTest {
   public void should_select_permission_template() {
     db.prepareDbUnit(getClass(), "selectPermissionTemplate.xml");
 
-    PermissionTemplateDto permissionTemplate = underTest.selectByKeyWithUserAndGroupPermissions("my_template_20130102_030405");
+    PermissionTemplateDto permissionTemplate = underTest.selectByUuidWithUserAndGroupPermissions("my_template_20130102_030405");
 
     assertThat(permissionTemplate).isNotNull();
     assertThat(permissionTemplate.getName()).isEqualTo("my template");
@@ -117,7 +117,7 @@ public class PermissionTemplateDaoTest {
   public void should_select_empty_permission_template() {
     db.prepareDbUnit(getClass(), "selectEmptyPermissionTemplate.xml");
 
-    PermissionTemplateDto permissionTemplate = underTest.selectByKeyWithUserAndGroupPermissions("my_template_20130102_030405");
+    PermissionTemplateDto permissionTemplate = underTest.selectByUuidWithUserAndGroupPermissions("my_template_20130102_030405");
 
     assertThat(permissionTemplate).isNotNull();
     assertThat(permissionTemplate.getName()).isEqualTo("my template");
@@ -130,7 +130,7 @@ public class PermissionTemplateDaoTest {
   public void should_select_permission_template_by_key() {
     db.prepareDbUnit(getClass(), "selectPermissionTemplate.xml");
 
-    PermissionTemplateDto permissionTemplate = underTest.selectByKey("my_template_20130102_030405");
+    PermissionTemplateDto permissionTemplate = underTest.selectByUuid("my_template_20130102_030405");
 
     assertThat(permissionTemplate).isNotNull();
     assertThat(permissionTemplate.getId()).isEqualTo(1L);
@@ -165,22 +165,12 @@ public class PermissionTemplateDaoTest {
   public void should_delete_permission_template() {
     db.prepareDbUnit(getClass(), "deletePermissionTemplate.xml");
 
-    underTest.deleteById(1L);
+    underTest.deleteById(session, 1L);
+    session.commit();
 
     checkTemplateTables("deletePermissionTemplate-result.xml");
   }
 
-  @Test
-  public void delete_by_key() {
-    String templateKey = "permission-template-key";
-    underTest.insert(session, newPermissionTemplateDto().setKee(templateKey));
-    assertThat(underTest.selectByKey(session, templateKey)).isNotNull();
-
-    underTest.deleteByKey(session, templateKey);
-
-    assertThat(underTest.selectByKey(session, templateKey)).isNull();
-  }
-
   @Test
   public void should_add_user_permission_to_template() {
     db.prepareDbUnit(getClass(), "addUserPermissionToTemplate.xml");
@@ -252,8 +242,8 @@ public class PermissionTemplateDaoTest {
     PermissionTemplateDto permissionTemplateDto = new PermissionTemplateDto().setName("Test template").setKee("test_template");
     PermissionTemplateDto templateWithPermissions = new PermissionTemplateDto().setKee("test_template");
     underTest = mock(PermissionTemplateDao.class);
-    when(underTest.selectByKey(db.getSession(), "test_template")).thenReturn(permissionTemplateDto);
-    when(underTest.selectByKeyWithUserAndGroupPermissions(db.getSession(), "test_template")).thenReturn(templateWithPermissions);
+    when(underTest.selectByUuid(db.getSession(), "test_template")).thenReturn(permissionTemplateDto);
+    when(underTest.selectByUuidWithUserAndGroupPermissions(db.getSession(), "test_template")).thenReturn(templateWithPermissions);
     when(underTest.selectPermissionTemplateWithPermissions(db.getSession(), "test_template")).thenCallRealMethod();
 
     PermissionTemplateDto permissionTemplate = underTest.selectPermissionTemplateWithPermissions(db.getSession(), "test_template");