Added more handling on deleted group and tests.

Change-Id: Ibc9b8dd8434cdc576d917a1784a719cdfe767066
diff --git a/full/Changes b/full/Changes
index 3a47fd0..8ee4c63 100644
--- a/full/Changes
+++ b/full/Changes
@@ -1,5 +1,5 @@
 version 0.60 release
-13/03/2018
+14/03/2018
 	- set up mail settings using localhost port 25 (margaretha)
 	- added mail template in kustvakt configuration (margaretha)
 	- added mail settings to readme (margaretha)
@@ -12,6 +12,7 @@
 	- fixed sqlite trigger (margaretha)
 	- fixed member exist error message (margaretha)
 	- fixed member invitation to join deleted group (margaretha)
+	- added checking deleted group (margaretha)
 
 version 0.59.10	
 20/02/2018 
diff --git a/full/src/main/java/de/ids_mannheim/korap/dao/RoleDao.java b/full/src/main/java/de/ids_mannheim/korap/dao/RoleDao.java
index fdf1c46..6cbfaa1 100644
--- a/full/src/main/java/de/ids_mannheim/korap/dao/RoleDao.java
+++ b/full/src/main/java/de/ids_mannheim/korap/dao/RoleDao.java
@@ -1,7 +1,6 @@
 package de.ids_mannheim.korap.dao;
 
 import java.util.List;
-import java.util.Set;
 
 import javax.persistence.EntityManager;
 import javax.persistence.PersistenceContext;
@@ -9,7 +8,6 @@
 import javax.persistence.criteria.CriteriaBuilder;
 import javax.persistence.criteria.CriteriaQuery;
 import javax.persistence.criteria.ListJoin;
-import javax.persistence.criteria.Predicate;
 import javax.persistence.criteria.Root;
 
 import org.springframework.beans.factory.annotation.Autowired;
@@ -17,7 +15,6 @@
 import org.springframework.transaction.annotation.Transactional;
 
 import de.ids_mannheim.korap.constant.PrivilegeType;
-import de.ids_mannheim.korap.entity.Privilege;
 import de.ids_mannheim.korap.entity.Role;
 import de.ids_mannheim.korap.entity.Role_;
 import de.ids_mannheim.korap.entity.UserGroupMember;
diff --git a/full/src/main/java/de/ids_mannheim/korap/service/UserGroupService.java b/full/src/main/java/de/ids_mannheim/korap/service/UserGroupService.java
index 28f14a7..981085e 100644
--- a/full/src/main/java/de/ids_mannheim/korap/service/UserGroupService.java
+++ b/full/src/main/java/de/ids_mannheim/korap/service/UserGroupService.java
@@ -186,7 +186,12 @@
             throws KustvaktException {
         User user = authManager.getUser(username);
         UserGroup userGroup = userGroupDao.retrieveGroupById(groupId);
-        if (userGroup.getCreatedBy().equals(username) || user.isSystemAdmin()) {
+        if (userGroup.getStatus() == UserGroupStatus.DELETED) {
+            throw new KustvaktException(StatusCodes.GROUP_DELETED,
+                    "Group " + userGroup.getName() + " has been deleted.",
+                    userGroup.getName());
+        }
+        else if (userGroup.getCreatedBy().equals(username) || user.isSystemAdmin()) {
             // soft delete
             userGroupDao.deleteGroup(groupId, username,
                     config.isSoftDeleteGroup());
@@ -234,8 +239,9 @@
         int groupId = userGroup.getId();
         ParameterChecker.checkIntegerValue(groupId, "userGroupId");
 
-        GroupMemberStatus existingStatus = memberExists(username, groupId, status);
-        if (existingStatus != null){
+        GroupMemberStatus existingStatus =
+                memberExists(username, groupId, status);
+        if (existingStatus != null) {
             throw new KustvaktException(StatusCodes.GROUP_MEMBER_EXISTS,
                     "Username " + username + " with status " + existingStatus
                             + " exists in the user-group "
@@ -336,7 +342,12 @@
         ParameterChecker.checkStringValue(username, "userId");
         ParameterChecker.checkIntegerValue(groupId, "groupId");
 
-        UserGroup group = userGroupDao.retrieveGroupById(groupId);
+        UserGroup userGroup = userGroupDao.retrieveGroupById(groupId);
+        if (userGroup.getStatus() == UserGroupStatus.DELETED) {
+            throw new KustvaktException(StatusCodes.GROUP_DELETED,
+                    "Group " + userGroup.getName() + " has been deleted.",
+                    userGroup.getName());
+        }
 
         UserGroupMember member =
                 groupMemberDao.retrieveMemberById(username, groupId);
@@ -344,14 +355,15 @@
         if (status.equals(GroupMemberStatus.DELETED)) {
             throw new KustvaktException(StatusCodes.GROUP_MEMBER_DELETED,
                     username + " has already been deleted from the group "
-                            + group.getName(),
-                    username, group.getName());
+                            + userGroup.getName(),
+                    username, userGroup.getName());
         }
         else if (member.getStatus().equals(GroupMemberStatus.ACTIVE)) {
             throw new KustvaktException(StatusCodes.GROUP_MEMBER_EXISTS,
                     "Username " + username + " with status " + status
-                            + " exists in the user-group " + group.getName(),
-                    username, status.name(), group.getName());
+                            + " exists in the user-group "
+                            + userGroup.getName(),
+                    username, status.name(), userGroup.getName());
         }
         // status pending
         else {
@@ -387,7 +399,12 @@
             String deletedBy) throws KustvaktException {
         User user = authManager.getUser(deletedBy);
         UserGroup userGroup = userGroupDao.retrieveGroupById(groupId);
-        if (memberId.equals(userGroup.getCreatedBy())) {
+        if (userGroup.getStatus() == UserGroupStatus.DELETED) {
+            throw new KustvaktException(StatusCodes.GROUP_DELETED,
+                    "Group " + userGroup.getName() + " has been deleted.",
+                    userGroup.getName());
+        }
+        else if (memberId.equals(userGroup.getCreatedBy())) {
             throw new KustvaktException(StatusCodes.NOT_ALLOWED,
                     "Operation " + "'delete group owner'" + "is not allowed.",
                     "delete group owner");
diff --git a/full/src/test/java/de/ids_mannheim/korap/config/TestBeans.java b/full/src/test/java/de/ids_mannheim/korap/config/TestBeans.java
index 85a0f4a..d0c490c 100644
--- a/full/src/test/java/de/ids_mannheim/korap/config/TestBeans.java
+++ b/full/src/test/java/de/ids_mannheim/korap/config/TestBeans.java
@@ -1,12 +1,15 @@
 package de.ids_mannheim.korap.config;
 
-import de.ids_mannheim.korap.handlers.AdminDao;
+import java.util.List;
+
 import de.ids_mannheim.korap.interfaces.AuthenticationManagerIface;
 import de.ids_mannheim.korap.interfaces.EncryptionIface;
-import de.ids_mannheim.korap.interfaces.db.*;
-import org.springframework.context.annotation.Bean;
-
-import java.util.List;
+import de.ids_mannheim.korap.interfaces.db.AdminHandlerIface;
+import de.ids_mannheim.korap.interfaces.db.AuditingIface;
+import de.ids_mannheim.korap.interfaces.db.EntityHandlerIface;
+import de.ids_mannheim.korap.interfaces.db.PolicyHandlerIface;
+import de.ids_mannheim.korap.interfaces.db.ResourceOperationIface;
+import de.ids_mannheim.korap.interfaces.db.UserDataDbIface;
 
 /**
  * @author hanl
diff --git a/full/src/test/java/de/ids_mannheim/korap/web/controller/UserGroupControllerTest.java b/full/src/test/java/de/ids_mannheim/korap/web/controller/UserGroupControllerTest.java
index ff6a563..04314fc 100644
--- a/full/src/test/java/de/ids_mannheim/korap/web/controller/UserGroupControllerTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/web/controller/UserGroupControllerTest.java
@@ -58,11 +58,10 @@
                 .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
                 .get(ClientResponse.class);
         String entity = response.getEntity(String.class);
-        System.out.println(entity);
+        //        System.out.println(entity);
         assertEquals(Status.OK.getStatusCode(), response.getStatus());
 
         JsonNode node = JsonUtils.readTree(entity);
-
         JsonNode group = node.get(1);
         assertEquals(2, group.at("/id").asInt());
         assertEquals("dory group", group.at("/name").asText());
@@ -181,6 +180,9 @@
         testDeleteMemberUnauthorized(groupId);
         testDeleteMember(groupId);
         testDeleteGroup(groupId);
+
+        testSubscribeToDeletedGroup(groupId);
+        testUnsubscribeToDeletedGroup(groupId);
     }
 
 
@@ -330,6 +332,27 @@
     }
 
     @Test
+    public void testDeleteDeletedGroup () throws UniformInterfaceException,
+            ClientHandlerException, KustvaktException {
+        ClientResponse response = resource().path("group").path("delete")
+                .queryParam("groupId", "4")
+                .header(Attributes.AUTHORIZATION,
+                        handler.createBasicAuthorizationHeaderValue("dory",
+                                "pass"))
+                .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
+                .delete(ClientResponse.class);
+
+        assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
+
+        String entity = response.getEntity(String.class);
+        JsonNode node = JsonUtils.readTree(entity);
+        assertEquals(StatusCodes.GROUP_DELETED, node.at("/errors/0/0").asInt());
+        assertEquals("Group deleted group has been deleted.",
+                node.at("/errors/0/1").asText());
+        assertEquals("deleted group", node.at("/errors/0/2").asText());
+    }
+
+    @Test
     public void testDeleteGroupOwner () throws UniformInterfaceException,
             ClientHandlerException, KustvaktException {
         // delete marlin from marlin group
@@ -452,7 +475,7 @@
 
         testDeletePendingMember();
     }
-    
+
     @Test
     public void testInvitePendingMember () throws UniformInterfaceException,
             ClientHandlerException, KustvaktException {
@@ -521,7 +544,8 @@
 
     @Test
     public void testInviteMemberToDeletedGroup ()
-            throws UniformInterfaceException, ClientHandlerException, KustvaktException {
+            throws UniformInterfaceException, ClientHandlerException,
+            KustvaktException {
         String[] members = new String[] { "nemo" };
 
         UserGroupJson userGroup = new UserGroupJson();
@@ -541,15 +565,12 @@
 
         String entity = response.getEntity(String.class);
         JsonNode node = JsonUtils.readTree(entity);
-        assertEquals(StatusCodes.GROUP_DELETED,
-                node.at("/errors/0/0").asInt());
-        assertEquals(
-                "Group deleted group has been deleted.",
+        assertEquals(StatusCodes.GROUP_DELETED, node.at("/errors/0/0").asInt());
+        assertEquals("Group deleted group has been deleted.",
                 node.at("/errors/0/1").asText());
-        assertEquals("deleted group",
-                node.at("/errors/0/2").asText());
+        assertEquals("deleted group", node.at("/errors/0/2").asText());
     }
-    
+
     // marlin has GroupMemberStatus.PENDING in dory group
     @Test
     public void testSubscribePendingMember () throws KustvaktException {
@@ -673,6 +694,29 @@
                 node.at("/errors/0/1").asText());
     }
 
+    private void testSubscribeToDeletedGroup (String groupId)
+            throws UniformInterfaceException, ClientHandlerException,
+            KustvaktException {
+        MultivaluedMap<String, String> form = new MultivaluedMapImpl();
+        form.add("groupId", groupId);
+
+        ClientResponse response = resource().path("group").path("subscribe")
+                .type(MediaType.APPLICATION_FORM_URLENCODED)
+                .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
+                .header(Attributes.AUTHORIZATION,
+                        handler.createBasicAuthorizationHeaderValue("nemo",
+                                "pass"))
+                .entity(form).post(ClientResponse.class);
+
+        assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
+
+        String entity = response.getEntity(String.class);
+        JsonNode node = JsonUtils.readTree(entity);
+        assertEquals(StatusCodes.GROUP_DELETED, node.at("/errors/0/0").asInt());
+        assertEquals("Group new user group has been deleted.",
+                node.at("/errors/0/1").asText());
+    }
+
     private void testUnsubscribeActiveMember (
             MultivaluedMap<String, String> form)
             throws UniformInterfaceException, ClientHandlerException,
@@ -739,8 +783,6 @@
                                 "pass"))
                 .entity(form).post(ClientResponse.class);
 
-        String entity = response.getEntity(String.class);
-        //        System.out.println(entity);
         assertEquals(Status.OK.getStatusCode(), response.getStatus());
 
         node = retrieveUserGroups("marlin");
@@ -749,4 +791,98 @@
         // invite marlin to dory group to set back the GroupMemberStatus.PENDING
         testInviteDeletedMember();
     }
+
+    @Test
+    public void testUnsubscribeMissingGroupId () throws KustvaktException {
+        MultivaluedMap<String, String> form = new MultivaluedMapImpl();
+
+        ClientResponse response = resource().path("group").path("unsubscribe")
+                .type(MediaType.APPLICATION_FORM_URLENCODED)
+                .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
+                .header(Attributes.AUTHORIZATION,
+                        handler.createBasicAuthorizationHeaderValue("marlin",
+                                "pass"))
+                .entity(form).post(ClientResponse.class);
+
+        assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
+
+        String entity = response.getEntity(String.class);
+        JsonNode node = JsonUtils.readTree(entity);
+
+        assertEquals(StatusCodes.MISSING_ARGUMENT,
+                node.at("/errors/0/0").asInt());
+        assertEquals("groupId", node.at("/errors/0/1").asText());
+        assertEquals("0", node.at("/errors/0/2").asText());
+    }
+
+    @Test
+    public void testUnsubscribeNonExistentMember () throws KustvaktException {
+        MultivaluedMap<String, String> form = new MultivaluedMapImpl();
+        form.add("groupId", "2");
+
+        ClientResponse response = resource().path("group").path("unsubscribe")
+                .type(MediaType.APPLICATION_FORM_URLENCODED)
+                .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
+                .header(Attributes.AUTHORIZATION,
+                        handler.createBasicAuthorizationHeaderValue("bruce",
+                                "pass"))
+                .entity(form).post(ClientResponse.class);
+
+        assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
+
+        String entity = response.getEntity(String.class);
+        JsonNode node = JsonUtils.readTree(entity);
+
+        assertEquals(StatusCodes.GROUP_MEMBER_NOT_FOUND,
+                node.at("/errors/0/0").asInt());
+        assertEquals("bruce is not found in the group",
+                node.at("/errors/0/1").asText());
+    }
+
+    @Test
+    public void testUnsubscribeToNonExistentGroup () throws KustvaktException {
+        MultivaluedMap<String, String> form = new MultivaluedMapImpl();
+        form.add("groupId", "100");
+
+        ClientResponse response = resource().path("group").path("unsubscribe")
+                .type(MediaType.APPLICATION_FORM_URLENCODED)
+                .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
+                .header(Attributes.AUTHORIZATION,
+                        handler.createBasicAuthorizationHeaderValue("pearl",
+                                "pass"))
+                .entity(form).post(ClientResponse.class);
+
+        assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
+
+        String entity = response.getEntity(String.class);
+        JsonNode node = JsonUtils.readTree(entity);
+
+        assertEquals(StatusCodes.GROUP_NOT_FOUND,
+                node.at("/errors/0/0").asInt());
+        assertEquals("Group with id 100 is not found",
+                node.at("/errors/0/1").asText());
+    }
+
+    private void testUnsubscribeToDeletedGroup (String groupId)
+            throws UniformInterfaceException, ClientHandlerException,
+            KustvaktException {
+        MultivaluedMap<String, String> form = new MultivaluedMapImpl();
+        form.add("groupId", groupId);
+
+        ClientResponse response = resource().path("group").path("unsubscribe")
+                .type(MediaType.APPLICATION_FORM_URLENCODED)
+                .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
+                .header(Attributes.AUTHORIZATION,
+                        handler.createBasicAuthorizationHeaderValue("nemo",
+                                "pass"))
+                .entity(form).post(ClientResponse.class);
+
+        assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
+
+        String entity = response.getEntity(String.class);
+        JsonNode node = JsonUtils.readTree(entity);
+        assertEquals(StatusCodes.GROUP_DELETED, node.at("/errors/0/0").asInt());
+        assertEquals("Group new user group has been deleted.",
+                node.at("/errors/0/1").asText());
+    }
 }