Fixed creator param when storing query or VC by admins for others.

Change-Id: I1085ab5fa2ca9b1d76022794b5f86224ed75df20
diff --git a/full/Changes b/full/Changes
index b58f77a..25bab49 100644
--- a/full/Changes
+++ b/full/Changes
@@ -6,6 +6,9 @@
 2021-08-13
 - Fixed missing request entity.
 - Updated the query service to enable editing query references.
+2021-08-16
+- Fixed creator param when storing query or VC by admins for 
+  the system or other users.
 
 # version 0.63.2
 2021-06-11
diff --git a/full/src/main/java/de/ids_mannheim/korap/config/NamedVCLoader.java b/full/src/main/java/de/ids_mannheim/korap/config/NamedVCLoader.java
index 7e946a7..ac782b6 100644
--- a/full/src/main/java/de/ids_mannheim/korap/config/NamedVCLoader.java
+++ b/full/src/main/java/de/ids_mannheim/korap/config/NamedVCLoader.java
@@ -61,7 +61,7 @@
         String json = IOUtils.toString(is, "utf-8");
         if (json != null) {
             cacheVC(json, filename);
-            vcService.storeQuery(filename, ResourceType.SYSTEM,
+            vcService.storeQuery("system",filename, ResourceType.SYSTEM,
                     QueryType.VIRTUAL_CORPUS, json, null, null, null, true,
                     "system", null, null);
         }
@@ -106,7 +106,7 @@
                     // ignore
                     if (DEBUG) jlog.debug(e);
                 }
-                vcService.storeQuery(filename, ResourceType.SYSTEM,
+                vcService.storeQuery("system",filename, ResourceType.SYSTEM,
                         QueryType.VIRTUAL_CORPUS, json, null, null, null, true,
                         "system", null, null);
             }
diff --git a/full/src/main/java/de/ids_mannheim/korap/service/QueryService.java b/full/src/main/java/de/ids_mannheim/korap/service/QueryService.java
index f54dd92..7e89803 100644
--- a/full/src/main/java/de/ids_mannheim/korap/service/QueryService.java
+++ b/full/src/main/java/de/ids_mannheim/korap/service/QueryService.java
@@ -206,7 +206,7 @@
         QueryDO query = queryDao.retrieveQueryByName(queryName, queryCreator);
         
         if (query == null) {
-            storeQuery(queryJson, queryName, username);
+            storeQuery(queryJson, queryName, queryCreator, username);
             return Status.CREATED;
         }
         else {
@@ -284,9 +284,9 @@
                     + ". Hidden access exists! Access id: " + access.getId());
         }
     }
-
-    public void storeQuery (QueryJson query, String queryName, String createdBy)
-            throws KustvaktException {
+    
+    public void storeQuery (QueryJson query, String queryName,
+            String queryCreator, String username) throws KustvaktException {
         String koralQuery = null;
         if (query.getQueryType().equals(QueryType.VIRTUAL_CORPUS)) {
             ParameterChecker.checkStringValue(query.getCorpusQuery(),
@@ -301,15 +301,16 @@
                     serializeQuery(query.getQuery(), query.getQueryLanguage());
         }
 
-        storeQuery(queryName, query.getType(), query.getQueryType(), koralQuery,
-                query.getDefinition(), query.getDescription(),
-                query.getStatus(), query.isCached(), createdBy,
+        storeQuery(username, queryName, query.getType(), query.getQueryType(),
+                koralQuery, query.getDefinition(), query.getDescription(),
+                query.getStatus(), query.isCached(), queryCreator,
                 query.getQuery(), query.getQueryLanguage());
     }
 
-    public void storeQuery (String queryName, ResourceType type, QueryType queryType,
-            String koralQuery, String definition, String description,
-            String status, boolean isCached, String username, String query,
+    public void storeQuery (String username, String queryName,
+            ResourceType type, QueryType queryType, String koralQuery,
+            String definition, String description, String status,
+            boolean isCached, String queryCreator, String query,
             String queryLanguage) throws KustvaktException {
         ParameterChecker.checkNameValue(queryName, "queryName");
         ParameterChecker.checkObjectValue(type, "type");
@@ -321,11 +322,16 @@
                     queryName);
         }
 
-        if (type.equals(ResourceType.SYSTEM) && !username.equals("system")
-                && !adminDao.isAdmin(username)) {
-            throw new KustvaktException(StatusCodes.AUTHORIZATION_FAILED,
-                    "Unauthorized operation for user: " + username, username);
+        if (type.equals(ResourceType.SYSTEM)){
+            if (adminDao.isAdmin(username)) {
+                queryCreator="system";
+            }
+            else if (!username.equals("system")) {
+                throw new KustvaktException(StatusCodes.AUTHORIZATION_FAILED,
+                        "Unauthorized operation for user: " + username, username);    
+            }
         }
+        
 
         CorpusAccess requiredAccess = CorpusAccess.PUB;
         if (queryType.equals(QueryType.VIRTUAL_CORPUS)) {
@@ -341,7 +347,7 @@
         try {
             queryId = queryDao.createQuery(queryName, type, queryType,
                     requiredAccess, koralQuery, definition, description, status,
-                    isCached, username, query, queryLanguage);
+                    isCached, queryCreator, query, queryLanguage);
 
         }
         catch (Exception e) {
diff --git a/full/src/test/java/de/ids_mannheim/korap/service/VirtualCorpusServiceTest.java b/full/src/test/java/de/ids_mannheim/korap/service/VirtualCorpusServiceTest.java
index deb03dc..5faeb80 100644
--- a/full/src/test/java/de/ids_mannheim/korap/service/VirtualCorpusServiceTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/service/VirtualCorpusServiceTest.java
@@ -47,7 +47,7 @@
         vc.setQueryType(QueryType.VIRTUAL_CORPUS);
         
         Assert.assertThrows(KustvaktException.class,
-                () -> vcService.storeQuery(vc, "dory-vc", "dory"));
+                () -> vcService.storeQuery(vc, "dory-vc", "dory", "dory"));
     }
 
     @Test
@@ -59,7 +59,7 @@
         vc.setType(ResourceType.PUBLISHED);
         vc.setQueryType(QueryType.VIRTUAL_CORPUS);
         String username = "VirtualCorpusServiceTest";
-        vcService.storeQuery(vc, vcName, username );
+        vcService.storeQuery(vc, vcName, username, username);
 
         List<QueryAccessDto> accesses =
                 vcService.listQueryAccessByUsername("admin");
diff --git a/full/src/test/java/de/ids_mannheim/korap/web/controller/QueryReferenceControllerTest.java b/full/src/test/java/de/ids_mannheim/korap/web/controller/QueryReferenceControllerTest.java
index 260d796..1188132 100644
--- a/full/src/test/java/de/ids_mannheim/korap/web/controller/QueryReferenceControllerTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/web/controller/QueryReferenceControllerTest.java
@@ -25,19 +25,50 @@
 
     private String testUser = "qRefControllerTest";
     private String adminUser = "admin";
+    private String system = "system";
 
-    private void checkQuery (String qName, String query,
-            String username, ResourceType resourceType, CorpusAccess access)
-            throws KustvaktException {
-        JsonNode node = testRetrieveQueryByName(username, username, qName);
+    private void testRetrieveQueryByName (String qName, String query,
+            String queryCreator, String username, ResourceType resourceType,
+            CorpusAccess access) throws KustvaktException {
+        
+        ClientResponse response = resource().path(API_VERSION).path("query")
+                .path("~" + queryCreator).path(qName)
+                .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+                        .createBasicAuthorizationHeaderValue(username, "pass"))
+                .get(ClientResponse.class);
+        String entity = response.getEntity(String.class);
+        // System.out.println(entity);
+        assertEquals(Status.OK.getStatusCode(), response.getStatus());
+        
+        JsonNode node = JsonUtils.readTree(entity);
+        
         assertEquals(qName, node.at("/name").asText());
         assertEquals(resourceType.displayName(), node.at("/type").asText());
-        assertEquals(username, node.at("/createdBy").asText());
+        assertEquals(queryCreator, node.at("/createdBy").asText());
         assertEquals(query, node.at("/query").asText());
         assertEquals("poliqarp", node.at("/queryLanguage").asText());
         assertEquals(access.name(), node.at("/requiredAccess").asText());
     }
     
+    private void testUpdateQuery (String qName, String qCreator,
+            String username, ResourceType type)
+            throws UniformInterfaceException, ClientHandlerException,
+            KustvaktException {
+        String json = "{\"query\": \"Sonne\""
+                + ",\"queryLanguage\": \"poliqarp\"}";
+        
+        ClientResponse response = resource().path(API_VERSION).path("query")
+                .path("~"+qCreator).path(qName)
+                .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+                        .createBasicAuthorizationHeaderValue(username, "pass"))
+                .header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON)
+                .entity(json).put(ClientResponse.class);
+        
+        assertEquals(Status.NO_CONTENT.getStatusCode(), response.getStatus());
+        
+        testRetrieveQueryByName(qName, "Sonne", qCreator, username, type, CorpusAccess.PUB);
+    }
+    
     @Test
     public void testCreatePrivateQuery () throws KustvaktException {
         String json = "{\"type\": \"PRIVATE\"" 
@@ -55,9 +86,11 @@
 
         assertEquals(Status.CREATED.getStatusCode(), response.getStatus());
 
-        checkQuery(qName, "der", testUser, ResourceType.PRIVATE,
+        testRetrieveQueryByName(qName, "der", testUser, testUser, ResourceType.PRIVATE,
                 CorpusAccess.PUB);
-        testDeleteQueryByName(qName, testUser);
+        
+        testUpdateQuery(qName, testUser, testUser,ResourceType.PRIVATE);
+        testDeleteQueryByName(qName, testUser, testUser);
     }
 
     @Test
@@ -77,9 +110,9 @@
 
         assertEquals(Status.CREATED.getStatusCode(), response.getStatus());
 
-        checkQuery(qName, "Regen", testUser, ResourceType.PUBLISHED,
+        testRetrieveQueryByName(qName, "Regen", testUser, testUser, ResourceType.PUBLISHED,
                 CorpusAccess.PUB);
-        testDeleteQueryByName(qName, testUser);
+        testDeleteQueryByName(qName, testUser, testUser);
         // check if hidden group has been created
         
     }
@@ -100,7 +133,11 @@
                 .entity(json).put(ClientResponse.class);
 
         assertEquals(Status.CREATED.getStatusCode(), response.getStatus());
-        testDeleteQueryByName(qName, "admin");
+        
+        testRetrieveQueryByName(qName, "Sommer", "marlin", adminUser, ResourceType.PRIVATE, CorpusAccess.PUB);
+        
+        testUpdateQuery(qName, "marlin", adminUser, ResourceType.PRIVATE);
+        testDeleteQueryByName(qName, "marlin", adminUser);
     }
     
     @Test
@@ -120,29 +157,12 @@
 
         assertEquals(Status.CREATED.getStatusCode(), response.getStatus());
         
-        checkQuery(qName, "Sommer", adminUser, ResourceType.SYSTEM, CorpusAccess.PUB);
-        testUpdateQuery(qName);
+        testRetrieveQueryByName(qName, "Sommer", system, adminUser, ResourceType.SYSTEM, CorpusAccess.PUB);
+        testUpdateQuery(qName, system, adminUser, ResourceType.SYSTEM);
+        testDeleteSystemQueryUnauthorized(qName);
+        testDeleteQueryByName(qName, system, adminUser);
     }
     
-    private void testUpdateQuery (String qName)
-            throws UniformInterfaceException, ClientHandlerException,
-            KustvaktException {
-        String json = "{\"query\": \"Sonne\""
-                + ",\"queryLanguage\": \"poliqarp\"}";
-        
-        ClientResponse response = resource().path(API_VERSION).path("query")
-                .path("~admin").path(qName)
-                .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
-                        .createBasicAuthorizationHeaderValue(adminUser, "pass"))
-                .header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON)
-                .entity(json).put(ClientResponse.class);
-        
-        assertEquals(Status.NO_CONTENT.getStatusCode(), response.getStatus());
-        
-        checkQuery(qName, "Sonne", adminUser, ResourceType.SYSTEM, CorpusAccess.PUB);
-        testDeleteQueryByName(qName, adminUser);
-    }
-
     @Test
     public void testCreateSystemQueryUnauthorized () throws KustvaktException {
         String json = "{\"type\": \"SYSTEM\""
@@ -183,9 +203,9 @@
 
         assertEquals(Status.CREATED.getStatusCode(), response.getStatus());
 
-        checkQuery(qName, "Sohn", testUser, ResourceType.PRIVATE,
+        testRetrieveQueryByName(qName, "Sohn", testUser, testUser, ResourceType.PRIVATE,
                 CorpusAccess.PUB);
-        testDeleteQueryByName(qName, testUser);
+        testDeleteQueryByName(qName, testUser, testUser);
     }
     
     @Test
@@ -256,6 +276,17 @@
         assertEquals("type", node.at("/errors/0/2").asText());
     }
     
+    private void testDeleteQueryByName (String qName, String qCreator, String username)
+            throws KustvaktException {
+        ClientResponse response = resource().path(API_VERSION).path("query")
+                .path("~" + qCreator).path(qName)
+                .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+                        .createBasicAuthorizationHeaderValue(username, "pass"))
+                .delete(ClientResponse.class);
+
+        assertEquals(Status.OK.getStatusCode(), response.getStatus());
+    }
+    
     @Test
     public void testDeleteQueryUnauthorized () throws KustvaktException {
         ClientResponse response = resource().path(API_VERSION).path("query")
@@ -274,6 +305,23 @@
                 node.at("/errors/0/1").asText());
     }
     
+    private void testDeleteSystemQueryUnauthorized (String qName) throws KustvaktException {
+        ClientResponse response = resource().path(API_VERSION).path("query")
+                .path("~system").path(qName)
+                .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+                        .createBasicAuthorizationHeaderValue(testUser, "pass"))
+                .delete(ClientResponse.class);
+
+        String entity = response.getEntity(String.class);
+        JsonNode node = JsonUtils.readTree(entity);
+
+        assertEquals(Status.UNAUTHORIZED.getStatusCode(), response.getStatus());
+        assertEquals(StatusCodes.AUTHORIZATION_FAILED,
+                node.at("/errors/0/0").asInt());
+        assertEquals("Unauthorized operation for user: " + testUser,
+                node.at("/errors/0/1").asText());
+    }
+    
     @Test
     public void testDeleteNonExistingQuery () throws KustvaktException {
         ClientResponse response = resource().path(API_VERSION).path("query")
@@ -296,7 +344,7 @@
     }
 
     @Test
-    public void testAvailableQueryForDory () throws UniformInterfaceException,
+    public void testListAvailableQueryForDory () throws UniformInterfaceException,
             ClientHandlerException, KustvaktException {
         JsonNode node = testListAvailableQuery("dory");
         assertEquals(2, node.size());
@@ -336,30 +384,4 @@
         return node;
     }
     
-    private JsonNode testRetrieveQueryByName (String username, String qCreator,
-            String qName) throws UniformInterfaceException,
-            ClientHandlerException, KustvaktException {
-        ClientResponse response = resource().path(API_VERSION).path("query")
-                .path("~" + qCreator).path(qName)
-                .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
-                        .createBasicAuthorizationHeaderValue(username, "pass"))
-                .get(ClientResponse.class);
-        String entity = response.getEntity(String.class);
-        // System.out.println(entity);
-        assertEquals(Status.OK.getStatusCode(), response.getStatus());
-
-        return JsonUtils.readTree(entity);
-    }
-
-    private void testDeleteQueryByName (String qName, String username)
-            throws KustvaktException {
-        ClientResponse response = resource().path(API_VERSION).path("query")
-                .path("~" + username).path(qName)
-                .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
-                        .createBasicAuthorizationHeaderValue(username, "pass"))
-                .delete(ClientResponse.class);
-
-        assertEquals(Status.OK.getStatusCode(), response.getStatus());
-    }
-
 }
diff --git a/full/src/test/java/de/ids_mannheim/korap/web/controller/VirtualCorpusControllerAdminTest.java b/full/src/test/java/de/ids_mannheim/korap/web/controller/VirtualCorpusControllerAdminTest.java
index 590886e..d4930c6 100644
--- a/full/src/test/java/de/ids_mannheim/korap/web/controller/VirtualCorpusControllerAdminTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/web/controller/VirtualCorpusControllerAdminTest.java
@@ -89,7 +89,7 @@
             ClientHandlerException, KustvaktException {
         ClientResponse response = resource().path(API_VERSION).path("vc")
                 .path("list").path("system-admin").queryParam("type", "SYSTEM")
-                .queryParam("createdBy", admin)
+                .queryParam("createdBy", "system")
                 .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
                 .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
                         .createBasicAuthorizationHeaderValue(admin, "pass"))
@@ -108,7 +108,7 @@
                 + ",\"corpusQuery\": \"creationDate since 1820\"}";
 
         ClientResponse response = resource().path(API_VERSION).path("vc")
-                .path("~"+admin).path("new-system-vc")
+                .path("~system").path("new-system-vc")
                 .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
                         .createBasicAuthorizationHeaderValue(admin, "pass"))
                 .header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON)
@@ -117,7 +117,7 @@
         assertEquals(Status.CREATED.getStatusCode(), response.getStatus());
 
         JsonNode node = testListSystemVC();
-        assertEquals(1, node.size());
+        assertEquals(2, node.size());
 
         testDeleteSystemVC(admin, "new-system-vc");
     }
@@ -126,7 +126,7 @@
             throws UniformInterfaceException, ClientHandlerException,
             KustvaktException {
         ClientResponse response = resource().path(API_VERSION).path("vc")
-                .path("~"+vcCreator).path(vcName)
+                .path("~system").path(vcName)
                 .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
                         .createBasicAuthorizationHeaderValue(admin, "pass"))
                 .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
@@ -135,7 +135,7 @@
         assertEquals(Status.OK.getStatusCode(), response.getStatus());
 
         JsonNode node = testListSystemVC();
-        assertEquals(0, node.size());
+        assertEquals(1, node.size());
     }
 
     @Test
diff --git a/full/src/test/java/de/ids_mannheim/korap/web/controller/VirtualCorpusControllerTest.java b/full/src/test/java/de/ids_mannheim/korap/web/controller/VirtualCorpusControllerTest.java
index 3286c51..8b7b13f 100644
--- a/full/src/test/java/de/ids_mannheim/korap/web/controller/VirtualCorpusControllerTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/web/controller/VirtualCorpusControllerTest.java
@@ -86,10 +86,10 @@
         return JsonUtils.readTree(entity);
     }
 
-    private void testDeleteVC (String vcName, String username)
+    private void testDeleteVC (String vcName, String vcCreator, String username)
             throws KustvaktException {
         ClientResponse response = resource().path(API_VERSION).path("vc")
-                .path("~" + username).path(vcName)
+                .path("~" + vcCreator).path(vcName)
                 .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
                         .createBasicAuthorizationHeaderValue(username, "pass"))
                 .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
@@ -315,7 +315,7 @@
         assertEquals("new_vc", node.get(1).get("name").asText());
 
         // delete new VC
-        testDeleteVC("new_vc", testUser);
+        testDeleteVC("new_vc", testUser, testUser);
 
         // list VC
         node = testListVC(testUser);
@@ -360,7 +360,7 @@
         assertEquals("HIDDEN", node.at("/status").asText());
 
         // EM: delete vc
-        testDeleteVC(vcName, testUser);
+        testDeleteVC(vcName, testUser, testUser);
 
         // EM: check if the hidden groups are deleted as well
         node = testCheckHiddenGroup(groupName);
@@ -466,7 +466,7 @@
                 .entity(json).put(ClientResponse.class);
 
         assertEquals(Status.CREATED.getStatusCode(), response.getStatus());
-        testDeleteVC(vcName, "admin");
+        testDeleteVC(vcName, "system","admin");
     }        
     
     @Test
diff --git a/full/src/test/resources/log4j2-test.properties b/full/src/test/resources/log4j2-test.properties
index 7606051..2810e0c 100644
--- a/full/src/test/resources/log4j2-test.properties
+++ b/full/src/test/resources/log4j2-test.properties
@@ -35,9 +35,9 @@
 logger.console.appenderRef.file.ref = STDOUT
 logger.console.additivity=false
 
-loggers=console
-logger.console.name=de.ids_mannheim.korap
-logger.console.level = info
-logger.console.appenderRefs = stdout
-logger.console.appenderRef.file.ref = STDOUT
-logger.console.additivity=false
+#loggers=console
+#logger.console.name=de.ids_mannheim.korap
+#logger.console.level = info
+#logger.console.appenderRefs = stdout
+#logger.console.appenderRef.file.ref = STDOUT
+#logger.console.additivity=false