Fixed the search service with type and id path parameters.

Change-Id: I685535e1a015827e6f03e60d58b2aa88733fcfde
diff --git a/src/main/java/de/ids_mannheim/korap/security/ac/ResourceFinder.java b/src/main/java/de/ids_mannheim/korap/security/ac/ResourceFinder.java
index 06acf52..380481d 100644
--- a/src/main/java/de/ids_mannheim/korap/security/ac/ResourceFinder.java
+++ b/src/main/java/de/ids_mannheim/korap/security/ac/ResourceFinder.java
@@ -102,7 +102,37 @@
         return searchPublicFiltered(clazz);
     }
 
-
+    public static <T extends KustvaktResource> Set<T> searchPublicFilteredIntId (
+            Class<T> clazz, int ... ids) throws KustvaktException {
+        
+        overrideProviders(null);
+        Set<T> sets = new HashSet<>();
+       
+        List<SecurityPolicy> policies = policydao.getPolicies(
+                new PolicyCondition(Attributes.PUBLIC_GROUP), clazz,
+                Permissions.Permission.READ.toByte());
+        ArrayList<Integer> id_set = new ArrayList<>(ids.length);
+        for(int id : ids){
+            id_set.add(id);
+        }
+        
+        for (SecurityPolicy policy : policies) {
+            jlog.debug("PolicyID retrieved: "+policy.getID()+" "+policy.getTarget());
+            if (id_set.isEmpty() || id_set.contains(policy.getID())) {
+                @SuppressWarnings("unchecked")
+                T r = (T) resourcedaos.get(KustvaktResource.class).findbyId(
+                        policy.getID(), User.UserFactory.getDemoUser());
+                sets.add(r);
+            }
+        }
+        
+        if (sets.isEmpty()){
+            throw new KustvaktException(StatusCodes.NO_VALUE_FOUND, 
+                    "Cannot found public resources with ids: "+id_set.toString());
+        }
+        return sets;
+    }
+    
     public static <T extends KustvaktResource> Set<T> searchPublicFiltered (
             Class<T> clazz, String ... ids) throws KustvaktException {
         overrideProviders(null);
diff --git a/src/main/java/de/ids_mannheim/korap/web/service/full/ResourceService.java b/src/main/java/de/ids_mannheim/korap/web/service/full/ResourceService.java
index d7be4e0..4f384c7 100644
--- a/src/main/java/de/ids_mannheim/korap/web/service/full/ResourceService.java
+++ b/src/main/java/de/ids_mannheim/korap/web/service/full/ResourceService.java
@@ -31,6 +31,7 @@
 import de.ids_mannheim.korap.config.Attributes;
 import de.ids_mannheim.korap.config.BeansFactory;
 import de.ids_mannheim.korap.config.KustvaktConfiguration;
+import de.ids_mannheim.korap.config.KustvaktConfiguration.BACKENDS;
 import de.ids_mannheim.korap.exceptions.EmptyResultException;
 import de.ids_mannheim.korap.exceptions.KustvaktException;
 import de.ids_mannheim.korap.exceptions.NotAuthorizedException;
@@ -48,8 +49,10 @@
 import de.ids_mannheim.korap.security.ac.ResourceFinder;
 import de.ids_mannheim.korap.security.ac.ResourceHandler;
 import de.ids_mannheim.korap.security.ac.SecurityManager;
+import de.ids_mannheim.korap.user.DemoUser;
 import de.ids_mannheim.korap.user.TokenContext;
 import de.ids_mannheim.korap.user.User;
+import de.ids_mannheim.korap.user.User.UserFactory;
 import de.ids_mannheim.korap.utils.JsonUtils;
 import de.ids_mannheim.korap.utils.KoralCollectionQueryBuilder;
 import de.ids_mannheim.korap.utils.KustvaktLogger;
@@ -310,6 +313,7 @@
         return Response.ok(result).build();
     }
 
+
     // ref query parameter removed!
     @TRACE
     @Path("search")
@@ -345,7 +349,7 @@
 
     /**
      * currently only supports either no reference at all in which
-     * case all corpora are retrieved or a corpus name like "WPD". 
+     * case all corpora are retrieved or a corpus name like "WPD".
      * No virtual collections supported!
      * 
      * @param locale
@@ -362,17 +366,14 @@
     @TRACE
     @Path("{type}/{id}/search")
     public Response buildQueryWithId (@Context Locale locale,
-            @Context SecurityContext securityContext, 
-            @QueryParam("q") String q,
-            @QueryParam("ql") String ql, 
-            @QueryParam("v") String v,
+            @Context SecurityContext securityContext, @QueryParam("q") String q,
+            @QueryParam("ql") String ql, @QueryParam("v") String v,
             @QueryParam("context") String context,
             @QueryParam("cutoff") Boolean cutoff,
             @QueryParam("count") Integer pageLength,
             @QueryParam("offset") Integer pageIndex,
             @QueryParam("page") Integer startPage,
-            @PathParam("type") String type, 
-            @PathParam("id") String id) {
+            @PathParam("type") String type, @PathParam("id") String id) {
         TokenContext ctx = (TokenContext) securityContext.getUserPrincipal();
         type = StringUtils.normalize(type);
         id = StringUtils.decodeHTML(id);
@@ -461,6 +462,7 @@
     }
 
 
+    @SuppressWarnings("unchecked")
     @GET
     @Path("search")
     public Response searchbyNameAll (@Context SecurityContext securityContext,
@@ -480,16 +482,37 @@
             user = controller.getUser(context.getUsername());
         }
         catch (KustvaktException e) {
-            jlog.error("Exception encountered: {}", e.string());
+            jlog.error("Failed retrieving user in the search service: {}",
+                    e.string());
             throw KustvaktResponseHandler.throwit(e);
         }
-        String result;
+
         QuerySerializer serializer = new QuerySerializer();
         serializer.setQuery(q, ql, v);
-
         if (cq != null)
             serializer.setCollection(cq);
 
+        MetaQueryBuilder meta = createMetaQuery(pageIndex, pageInteger, ctx,
+                pageLength, cutoff);
+        serializer.setMeta(meta.raw());
+
+        String query;
+        try {
+            query = this.processor.processQuery(serializer.toJSON(), user);
+            jlog.info("the serialized query {}", query);
+        }
+        catch (KustvaktException e) {
+            throw KustvaktResponseHandler.throwit(e);
+        }
+
+        String result = doSearch(eng, query, pageLength, meta);
+        return Response.ok(result).build();
+    }
+
+
+    private MetaQueryBuilder createMetaQuery (Integer pageIndex,
+            Integer pageInteger, String ctx, Integer pageLength,
+            Boolean cutoff) {
         MetaQueryBuilder meta = new MetaQueryBuilder();
         meta.addEntry("startIndex", pageIndex);
         meta.addEntry("startPage", pageInteger);
@@ -500,40 +523,48 @@
         // meta.addMeta(pageIndex, pageInteger, pageLength, ctx, cutoff);
         // fixme: should only apply to CQL queries per default!
         // meta.addEntry("itemsPerResource", 1);
-        serializer.setMeta(meta.raw());
-        String query;
+        return meta;
+    }
+
+
+    private String doSearch (BACKENDS eng, String query, Integer pageLength,
+            MetaQueryBuilder meta) {
+        String result;
+        if (eng.equals(KustvaktConfiguration.BACKENDS.NEO4J)) {
+            result = searchNeo4J(query, pageLength, meta,false);
+        }
+        else {
+            result = searchKrill.search(query);
+        }
+        KustvaktLogger.QUERY_LOGGER.trace("The result set: {}", result);
+        return result;
+
+    }
+
+    private String searchNeo4J (String query, int pageLength,
+            MetaQueryBuilder meta, boolean raw) {
+        
+        if (raw){
+            throw KustvaktResponseHandler.throwit(
+                    StatusCodes.ILLEGAL_ARGUMENT,
+                    "raw not supported!", null);
+        }
+        
+        MultivaluedMap<String, String> map = new MultivaluedMapImpl();
+        map.add("q", query);
+        map.add("count", String.valueOf(pageLength));
+        map.add("lctxs", String.valueOf(meta.getSpanContext().getLeftSize()));
+        map.add("rctxs", String.valueOf(meta.getSpanContext().getRightSize()));
         try {
-            query = this.processor.processQuery(serializer.toJSON(), user);
+            return this.graphDBhandler.getResponse(map, "distKwic");
         }
         catch (KustvaktException e) {
+            jlog.error("Failed searching in Neo4J: {}", e.string());
             throw KustvaktResponseHandler.throwit(e);
         }
 
-        jlog.info("the serialized query {}", query);
-
-        if (eng.equals(KustvaktConfiguration.BACKENDS.NEO4J)) {
-            MultivaluedMap map = new MultivaluedMapImpl();
-            map.add("q", query);
-            map.add("count", String.valueOf(pageLength));
-            map.add("lctxs",
-                    String.valueOf(meta.getSpanContext().getLeftSize()));
-            map.add("rctxs",
-                    String.valueOf(meta.getSpanContext().getRightSize()));
-            try {
-                result = this.graphDBhandler.getResponse(map, "distKwic");
-            }
-            catch (KustvaktException e) {
-                jlog.error("Exception encountered: {}", e.string());
-                throw KustvaktResponseHandler.throwit(e);
-            }
-        }
-        else
-            result = searchKrill.search(query);
-        KustvaktLogger.QUERY_LOGGER.trace("The result set: {}", result);
-        return Response.ok(result).build();
     }
 
-
     /**
      * String search, String ql, List<String> parents, String cli,
      * String cri,
@@ -573,74 +604,37 @@
 
         try {
             User user = controller.getUser(context.getUsername());
-            MetaQueryBuilder meta = new MetaQueryBuilder();
+            MetaQueryBuilder meta;
 
+            // EM: shouldnt this be the same as buildQueryWithId() ?
             if (!raw) {
+                meta = createMetaQuery(pageIndex, pageInteger, ctx, pageLength,
+                        cutoff);
+                
                 QuerySerializer s = new QuerySerializer();
                 s.setQuery(query, ql, v);
-
+                
+                // add collection query
                 KoralCollectionQueryBuilder builder = new KoralCollectionQueryBuilder();
-
-                KustvaktResource resource;
-                if (StringUtils.isInteger(id))
-                    resource = this.resourceHandler
-                            .findbyIntId(Integer.valueOf(id), user);
-                else
-                    resource = this.resourceHandler.findbyStrId(id, user,
-                            ResourceFactory.getResourceClass(type));
-
-                if (resource instanceof VirtualCollection)
-                    builder.setBaseQuery(resource.getData());
-                else if (resource instanceof Corpus)
-                    builder.with(Attributes.CORPUS_SIGLE
-                            + resource.getPersistentID());
-                else
-                    throw KustvaktResponseHandler.throwit(
-                            StatusCodes.ILLEGAL_ARGUMENT,
-                            "Type parameter not supported", type);
-
-                meta.addEntry("startIndex", pageIndex);
-                meta.addEntry("startPage", pageInteger);
-                meta.setSpanContext(ctx);
-                meta.addEntry("count", pageLength);
-                // todo: what happened to cutoff?
-                meta.addEntry("cutoff", cutoff);
-                // should only apply to CQL queries
-                // meta.addEntry("itemsPerResource", 1);
-                s.setMeta(meta.raw());
-
-                query = s.toJSON();
+                builder.setBaseQuery(s.toJSON());
+                query = createQuery(user, type, id, builder);
+                
             }
-            String result;
-            try {
+            else {
+                meta = new MetaQueryBuilder();
+            }
 
+            try {
                 // rewrite process
                 query = this.processor.processQuery(query, user);
-
-                if (eng.equals(KustvaktConfiguration.BACKENDS.NEO4J)) {
-                    if (raw)
-                        throw KustvaktResponseHandler.throwit(
-                                StatusCodes.ILLEGAL_ARGUMENT,
-                                "raw not supported!", null);
-                    MultivaluedMap map = new MultivaluedMapImpl();
-                    map.add("q", query);
-                    map.add("count", String.valueOf(pageLength));
-                    map.add("lctxs", String
-                            .valueOf(meta.getSpanContext().getLeftSize()));
-                    map.add("rctxs", String
-                            .valueOf(meta.getSpanContext().getRightSize()));
-                    result = this.graphDBhandler.getResponse(map, "distKwic");
-                }
-                else
-                    result = searchKrill.search(query);
-
             }
-            catch (Exception e) {
-                jlog.error("Exception for serialized query: " + query, e);
+            catch (KustvaktException e) {
+                jlog.error("Failed in rewriting query: " + query, e);
                 throw KustvaktResponseHandler.throwit(500, e.getMessage(),
                         null);
             }
 
+            String result = doSearch(eng, query, pageLength, meta);
             KustvaktLogger.QUERY_LOGGER.trace("The result set: {}", result);
             return Response.ok(result).build();
         }
@@ -652,6 +646,59 @@
     }
 
 
+    private String createQuery (User user, String type, String id,
+            KoralCollectionQueryBuilder builder) {
+        KustvaktResource resource = null;
+        try {
+            // EM: this doesn't look like very useful since the id is :
+            // 1. auto-generated 
+            // 2. random
+            // 3. not really known.
+            if (user instanceof DemoUser) {
+                Set<KustvaktResource> set = null;
+                if (StringUtils.isInteger(id)) {
+                    set = ResourceFinder.searchPublicFilteredIntId(
+                            ResourceFactory.getResourceClass(type),
+                            Integer.parseInt(id));
+                }
+                else {
+                    set = ResourceFinder.searchPublicFiltered(
+                            ResourceFactory.getResourceClass(type), id);
+                }
+                resource = (KustvaktResource) set.toArray()[0];
+            }
+            else if (StringUtils.isInteger(id)) {
+                resource = this.resourceHandler.findbyIntId(Integer.valueOf(id),
+                        user);
+            }
+            else {
+                resource = this.resourceHandler.findbyStrId(id, user,
+                        ResourceFactory.getResourceClass(type));
+            }
+        }
+        catch (KustvaktException e) {
+            jlog.error("Failed retrieving resource: {}", e.string());
+            throw KustvaktResponseHandler.throwit(e);
+        }
+
+        if (resource instanceof VirtualCollection) {
+            // test this
+            //builder.setBaseQuery(resource.getData());
+            return JsonUtils
+                    .toJSON(builder.and().mergeWith(resource.getData()));
+        }
+        else if (resource instanceof Corpus) {
+            builder.and().with(Attributes.CORPUS_SIGLE, "=",
+                    resource.getPersistentID());
+            return builder.toJSON();
+        }
+        else {
+            throw KustvaktResponseHandler.throwit(StatusCodes.ILLEGAL_ARGUMENT,
+                    "Type parameter not supported", type);
+        }
+    }
+
+
     @POST
     @Path("stats")
     public Response getStats (@Context SecurityContext context,
@@ -1032,19 +1079,19 @@
     @GET
     @Path("/corpus/{corpusId}/{docId}/{textId}/{matchId}/matchInfo")
     public Response getMatchInfo (@Context SecurityContext ctx,
-            @Context Locale locale, 
-            @PathParam("corpusId") String corpusId,
+            @Context Locale locale, @PathParam("corpusId") String corpusId,
             @PathParam("docId") String docId,
-            @PathParam("textId") String textId, 
+            @PathParam("textId") String textId,
             @PathParam("matchId") String matchId,
             @QueryParam("foundry") Set<String> foundries,
             @QueryParam("layer") Set<String> layers,
             @QueryParam("spans") Boolean spans) throws KustvaktException {
-        
+
         TokenContext tokenContext = (TokenContext) ctx.getUserPrincipal();
         spans = spans != null ? spans : false;
-        
-        String matchid = searchKrill.getMatchId(corpusId, docId, textId, matchId);
+
+        String matchid = searchKrill.getMatchId(corpusId, docId, textId,
+                matchId);
         if (layers == null || layers.isEmpty())
             layers = new HashSet<>();
 
@@ -1055,7 +1102,8 @@
             user = controller.getUser(tokenContext.getUsername());
         }
         catch (KustvaktException e) {
-            jlog.error("Failed getting user in the matchInfo service: {}", e.string());
+            jlog.error("Failed getting user in the matchInfo service: {}",
+                    e.string());
             throw KustvaktResponseHandler.throwit(e);
         }
 
@@ -1069,8 +1117,8 @@
 
             for (String spl : new ArrayList<>(foundries)) {
                 try {
-                    SecurityManager<?> manager = SecurityManager
-                            .init(spl, user, Permissions.Permission.READ);
+                    SecurityManager<?> manager = SecurityManager.init(spl, user,
+                            Permissions.Permission.READ);
                     if (!manager.isAllowed())
                         continue;
 
@@ -1085,7 +1133,8 @@
                 }
                 catch (NotAuthorizedException e) {
                     throw KustvaktResponseHandler.throwit(
-                            StatusCodes.ACCESS_DENIED, "Permission denied", matchid);
+                            StatusCodes.ACCESS_DENIED, "Permission denied",
+                            matchid);
                 }
 
             }
diff --git a/src/test/java/de/ids_mannheim/korap/web/service/full/MatchInfoServiceTest.java b/src/test/java/de/ids_mannheim/korap/web/service/full/MatchInfoServiceTest.java
index 4e2f9d2..c3f3724 100644
--- a/src/test/java/de/ids_mannheim/korap/web/service/full/MatchInfoServiceTest.java
+++ b/src/test/java/de/ids_mannheim/korap/web/service/full/MatchInfoServiceTest.java
@@ -68,7 +68,7 @@
         assertEquals(ClientResponse.Status.OK.getStatusCode(),
                 response.getStatus());
         String entity = response.getEntity(String.class);
-        System.out.println(entity);
+//        System.out.println(entity);
         JsonNode node = JsonUtils.readTree(entity);
         assertNotNull(node);
         assertEquals("WPD15/B07/51608", node.at("/textSigle").asText());
diff --git a/src/test/java/de/ids_mannheim/korap/web/service/full/QuerySerializationServiceTest.java b/src/test/java/de/ids_mannheim/korap/web/service/full/QuerySerializationServiceTest.java
index 9b77a8b..5fa2cd0 100644
--- a/src/test/java/de/ids_mannheim/korap/web/service/full/QuerySerializationServiceTest.java
+++ b/src/test/java/de/ids_mannheim/korap/web/service/full/QuerySerializationServiceTest.java
@@ -204,7 +204,7 @@
     public void testQuerySerializationOfVirtualCollection () {
         ClientResponse response = resource()
                 .path(getAPIVersion())
-                .path("collection/WPD15-VC/search")
+                .path("collection/GOE-VC/search")
                 .queryParam("q", "[orth=der]")
                 .queryParam("ql", "poliqarp")
                 .queryParam("context", "base/s:s")
@@ -217,11 +217,11 @@
         assertEquals("koral:doc", node.at("/collection/operands/0/@type")
                 .asText());
         assertEquals("corpusSigle", node.at("/collection/operands/0/key").asText());
-        assertEquals("WPD15", node.at("/collection/operands/0/value").asText());
+        assertEquals("GOE", node.at("/collection/operands/0/value").asText());
         assertEquals("koral:doc", node.at("/collection/operands/1/@type")
                 .asText());
         assertEquals("creationDate", node.at("/collection/operands/1/key").asText());
-        assertEquals("2014-04-01", node.at("/collection/operands/1/value").asText());
+        assertEquals("1810-01-01", node.at("/collection/operands/1/value").asText());
 
     }
     
diff --git a/src/test/java/de/ids_mannheim/korap/web/service/full/ResourceInfoServiceTest.java b/src/test/java/de/ids_mannheim/korap/web/service/full/ResourceInfoServiceTest.java
index 2dba542..a7689ca 100644
--- a/src/test/java/de/ids_mannheim/korap/web/service/full/ResourceInfoServiceTest.java
+++ b/src/test/java/de/ids_mannheim/korap/web/service/full/ResourceInfoServiceTest.java
@@ -43,8 +43,8 @@
                 .path("collection").get(ClientResponse.class);
         assertEquals(ClientResponse.Status.OK.getStatusCode(),
                 response.getStatus());
-
-        JsonNode node = JsonUtils.readTree(response.getEntity(String.class));
+        String entity = response.getEntity(String.class);
+        JsonNode node = JsonUtils.readTree(entity);
         assertNotNull(node);
         assertEquals(1, node.size());
     }
@@ -63,27 +63,41 @@
         JsonNode node = JsonUtils.readTree(response.getEntity(String.class));
         assertNotNull(node);
         assertTrue(node.isArray());
-        assertEquals(2, node.size());
+        assertEquals(3, node.size());
     }
 
 
     @Test
     public void testGetVirtualCollectionInfoById () {
         ClientResponse response = resource().path(getAPIVersion())
-                .path("collection").path("WPD15-VC").get(ClientResponse.class);
+                .path("collection").path("GOE-VC").get(ClientResponse.class);
         assertEquals(ClientResponse.Status.OK.getStatusCode(),
                 response.getStatus());
         String ent = response.getEntity(String.class);
         JsonNode node = JsonUtils.readTree(ent);
         assertNotNull(node);
         assertNotEquals(0, node.size());
-        assertEquals("Wikipedia Virtual Collection",
+        assertEquals("Goethe Virtual Collection",
                 node.path("name").asText());
-        assertEquals("German Wikipedia 2015",
+        assertEquals("Goethe works from 1810",
                 node.path("description").asText());
     }
-
-
+    
+    @Test
+    public void testGetVirtualCollectionInfoByIdUnauthorized () {
+        ClientResponse response = resource().path(getAPIVersion())
+                .path("collection").path("WPD15-VC").get(ClientResponse.class);
+        assertEquals(ClientResponse.Status.BAD_REQUEST.getStatusCode(),
+                response.getStatus());
+        String ent = response.getEntity(String.class);
+        JsonNode node = JsonUtils.readTree(ent);
+        assertNotNull(node);
+        assertNotEquals(0, node.size());
+        assertEquals(101, node.at("/errors/0/0").asInt());
+        assertEquals("[Cannot found public resources with ids: [WPD15-VC]]",
+                node.at("/errors/0/2").asText());
+    }
+    
     @Test
     public void testGetPublicCorporaInfo () {
         ClientResponse response = resource().path(getAPIVersion())
@@ -106,7 +120,7 @@
         assertEquals(ClientResponse.Status.OK.getStatusCode(),
                 response.getStatus());
         String ent = response.getEntity(String.class);
-        System.out.println(ent);
+//        System.out.println(ent);
         JsonNode node = JsonUtils.readTree(ent);
         assertNotNull(node);
         assertTrue(node.isObject());
@@ -163,10 +177,12 @@
         assertEquals(ClientResponse.Status.BAD_REQUEST.getStatusCode(),
                 response.getStatus());
         String ent = response.getEntity(String.class);
-        JsonNode error = JsonUtils.readTree(ent).get("errors").get(0);
-        assertEquals(101, error.get(0).asInt());
+        JsonNode node = JsonUtils.readTree(ent);
+        assertNotNull(node);
+        assertNotEquals(0, node.size());
+        assertEquals(101, node.at("/errors/0/0").asInt());
         assertEquals("[Cannot found public resources with ids: [ZUW19]]",
-                error.get(2).asText());
+                node.at("/errors/0/2").asText());
     }
 
 
@@ -179,10 +195,12 @@
         assertEquals(ClientResponse.Status.BAD_REQUEST.getStatusCode(),
                 response.getStatus());
         String ent = response.getEntity(String.class);
-        JsonNode error = JsonUtils.readTree(ent).get("errors").get(0);
-        assertEquals(101, error.get(0).asInt());
+        JsonNode node = JsonUtils.readTree(ent);
+        assertNotNull(node);
+        assertNotEquals(0, node.size());
+        assertEquals(101, node.at("/errors/0/0").asInt());
         assertEquals("[Cannot found public resources with ids: [BRZ10]]",
-                error.get(2).asText());
+                node.at("/errors/0/2").asText());
     }
 
 
diff --git a/src/test/java/de/ids_mannheim/korap/web/service/full/SearchServiceTest.java b/src/test/java/de/ids_mannheim/korap/web/service/full/SearchServiceTest.java
index a6f6edd..bad37ca 100644
--- a/src/test/java/de/ids_mannheim/korap/web/service/full/SearchServiceTest.java
+++ b/src/test/java/de/ids_mannheim/korap/web/service/full/SearchServiceTest.java
@@ -4,6 +4,9 @@
 import static org.junit.Assert.assertNotEquals;
 import static org.junit.Assert.assertNotNull;
 
+import java.util.Iterator;
+import java.util.Set;
+
 import org.junit.BeforeClass;
 import org.junit.Ignore;
 import org.junit.Test;
@@ -14,13 +17,15 @@
 import de.ids_mannheim.korap.config.Attributes;
 import de.ids_mannheim.korap.exceptions.KustvaktException;
 import de.ids_mannheim.korap.query.serialize.QuerySerializer;
+import de.ids_mannheim.korap.resources.Corpus;
+import de.ids_mannheim.korap.security.ac.ResourceFinder;
 import de.ids_mannheim.korap.security.auth.BasicHttpAuth;
 import de.ids_mannheim.korap.utils.JsonUtils;
 import de.ids_mannheim.korap.web.service.FastJerseyTest;
 
 /**
  * @author hanl, margaretha
- * @lastUpdate 19/04/2017
+ * @lastUpdate 21/04/2017
  *
  */
 public class SearchServiceTest extends FastJerseyTest {
@@ -38,7 +43,6 @@
                 "de.ids_mannheim.korap.web.utils");
     }
 
-
     @Test
     public void testSearchQueryPublicCorpora () {
         ClientResponse response = resource().path(getAPIVersion())
@@ -57,9 +61,8 @@
         assertEquals(6218, node.at("/meta/totalResults").asInt());
     }
 
-
     @Test
-    public void testSearchSimpleAuthorized () {
+    public void testSearchQueryAuthorized () {
         ClientResponse response = resource().path(getAPIVersion())
                 .path("search").queryParam("q", "[orth=die]")
                 .queryParam("ql", "poliqarp")
@@ -79,7 +82,7 @@
 
 
     @Test
-    public void testSearchSimpleWithCQAuthorized () {
+    public void testSearchQueryWithCollectionQueryAuthorized () {
         ClientResponse response = resource().path(getAPIVersion())
                 .path("search").queryParam("q", "[orth=das]")
                 .queryParam("ql", "poliqarp")
@@ -100,26 +103,8 @@
         assertEquals("koral:token", node.at("/query/@type").asText());
     }
 
-
     @Test
-    public void testSearchSimpleDemo () {
-        ClientResponse response = resource().path(getAPIVersion())
-                .path("search").queryParam("q", "[orth=der]")
-                .queryParam("ql", "poliqarp").get(ClientResponse.class);
-        assertEquals(ClientResponse.Status.OK.getStatusCode(),
-                response.getStatus());
-        String ent = response.getEntity(String.class);
-        JsonNode node = JsonUtils.readTree(ent);
-        assertNotNull(node);
-        assertNotEquals(0, node.path("matches").size());
-        assertEquals("corpusSigle([GOE, WPD13])",
-                node.at("/collection/rewrites/0/scope").asText());
-    }
-
-
-    @Test
-    @Ignore
-    public void testSearchPublicCorpusWithID () {
+    public void testSearchForPublicCorpusWithStringId () {
         ClientResponse response = resource().path(getAPIVersion())
                 .path("corpus").path("GOE").path("search")
                 .queryParam("q", "blau").queryParam("ql", "poliqarp")
@@ -129,14 +114,132 @@
         String ent = response.getEntity(String.class);
         JsonNode node = JsonUtils.readTree(ent);
         assertNotNull(node);
+        assertEquals("koral:doc", node.at("/collection/@type").asText());
+        assertEquals("corpusSigle", node.at("/collection/key").asText());
+        assertEquals("GOE", node.at("/collection/value").asText());
+        assertNotEquals(0, node.path("matches").size());
+        assertEquals(32, node.at("/meta/totalResults").asInt());
+    }
+    
+    @Test
+    public void testSearchForVirtualCollectionWithStringId () {
+        ClientResponse response = resource().path(getAPIVersion())
+                .path("collection").path("GOE-VC").path("search")
+                .queryParam("q", "blau").queryParam("ql", "poliqarp")
+                .get(ClientResponse.class);
+        assertEquals(ClientResponse.Status.OK.getStatusCode(),
+                response.getStatus());
+        String ent = response.getEntity(String.class);
+        System.out.println(ent);
+        JsonNode node = JsonUtils.readTree(ent);
+        assertNotNull(node);
         assertEquals("koral:docGroup", node.at("/collection/@type").asText());
-        assertEquals("operation:or", node.at("/collection/operation").asText());
+        assertEquals("operation:and", node.at("/collection/operation").asText());
         assertNotEquals(0, node.at("/collection/operands").size());
-        assertEquals("corpusSigle([GOE])",
-                node.at("/collection/rewrites/0/scope").asText());
-        assertEquals(6218, node.at("/meta/totalResults").asInt());
+        assertEquals("corpusSigle",
+                node.at("/collection/operands/0/key").asText());
+        assertEquals("GOE",
+                node.at("/collection/operands/0/value").asText());
+        assertEquals("creationDate",
+                node.at("/collection/operands/1/key").asText());
+        assertEquals("1810-01-01",
+                node.at("/collection/operands/1/value").asText());
+        assertEquals(1, node.at("/meta/totalResults").asInt());
     }
 
+    
+    @Test
+    public void testSearchForPublicCorpusWithIntegerId () throws KustvaktException {
+        Set<Corpus> publicCorpora = ResourceFinder.searchPublic(Corpus.class);
+        Iterator<Corpus> i = publicCorpora.iterator();
+        String id = null;
+        while (i.hasNext()){
+            Corpus c = i.next();
+            if (c.getName().equals("Goethe")){
+                id =c.getId().toString();
+            }
+        }
+            
+        ClientResponse response = resource().path(getAPIVersion())
+                .path("corpus").path(id).path("search")
+                .queryParam("q", "blau").queryParam("ql", "poliqarp")
+                .get(ClientResponse.class);
+        
+        String ent = response.getEntity(String.class);
+        assertEquals(ClientResponse.Status.OK.getStatusCode(),
+                response.getStatus());
+        
+        JsonNode node = JsonUtils.readTree(ent);
+        assertNotNull(node);
+        assertEquals("koral:doc", node.at("/collection/@type").asText());
+        assertEquals("corpusSigle", node.at("/collection/key").asText());
+        assertEquals("GOE", node.at("/collection/value").asText());
+        assertNotEquals(0, node.path("matches").size());
+    }
+    
+    @Test
+    public void testSearchForCorpusWithStringIdUnauthorized () {
+        ClientResponse response = resource().path(getAPIVersion())
+                .path("corpus").path("WPD15").path("search")
+                .queryParam("q", "blau").queryParam("ql", "poliqarp")
+                .get(ClientResponse.class);
+        assertEquals(ClientResponse.Status.BAD_REQUEST.getStatusCode(),
+                response.getStatus());
+        String ent = response.getEntity(String.class);
+        JsonNode error = JsonUtils.readTree(ent).get("errors").get(0);
+        assertEquals(101, error.get(0).asInt());
+        assertEquals("[Cannot found public resources with ids: [WPD15]]",
+                error.get(2).asText());
+    }
+    
+    @Test
+    public void testSearchForOwnersCorpusWithStringId () {
+        ClientResponse response = resource().path(getAPIVersion())
+                .path("corpus").path("WPD15").path("search")
+                .queryParam("q", "[orth=das]")
+                .queryParam("ql", "poliqarp")
+                .header(Attributes.AUTHORIZATION,
+                        BasicHttpAuth.encode("kustvakt", "kustvakt2015"))
+                .get(ClientResponse.class);
+        assertEquals(ClientResponse.Status.OK.getStatusCode(),
+                response.getStatus());
+        String entity = response.getEntity(String.class);
+        JsonNode node = JsonUtils.readTree(entity);
+        assertNotNull(node);
+        assertEquals("koral:doc", node.at("/collection/@type").asText());
+        assertEquals("corpusSigle", node.at("/collection/key").asText());
+        assertEquals("WPD15", node.at("/collection/value").asText());
+        assertNotEquals(0, node.path("matches").size());
+    }
+    
+    @Test
+    public void testSearchForOwnersCorpusWithIntegerId () throws KustvaktException {
+        Set<Corpus> publicCorpora = ResourceFinder.searchPublic(Corpus.class);
+        Iterator<Corpus> i = publicCorpora.iterator();
+        String id = null;
+        while (i.hasNext()){
+            Corpus c = i.next();
+            if (c.getPersistentID().equals("WPD15")){
+                id =c.getId().toString();
+            }
+        }
+        ClientResponse response = resource().path(getAPIVersion())
+                .path("corpus").path("5").path("search")
+                .queryParam("q", "[orth=das]")
+                .queryParam("ql", "poliqarp")
+                .header(Attributes.AUTHORIZATION,
+                        BasicHttpAuth.encode("kustvakt", "kustvakt2015"))
+                .get(ClientResponse.class);
+        assertEquals(ClientResponse.Status.OK.getStatusCode(),
+                response.getStatus());
+        String entity = response.getEntity(String.class);
+        JsonNode node = JsonUtils.readTree(entity);
+        assertNotNull(node);
+        assertEquals("koral:doc", node.at("/collection/@type").asText());
+        assertEquals("corpusSigle", node.at("/collection/key").asText());
+        assertEquals("WPD15", node.at("/collection/value").asText());
+        assertNotEquals(0, node.path("matches").size());
+    }
 
     @Test
     public void testSearchSentenceMeta () {
diff --git a/src/test/resources/policy-test.conf b/src/test/resources/policy-test.conf
index a4c49bd..35b0fd9 100644
--- a/src/test/resources/policy-test.conf
+++ b/src/test/resources/policy-test.conf
@@ -1,12 +1,12 @@
 # type	id	name	description	condition	permissions	collectionQuery
 
-virtualcollection	WPD15-VC	Wikipedia Virtual Collection	German Wikipedia 2015	public	read	corpusSigle=WPD15 & creationDate since 2014-04-01	
+virtualcollection	WPD15-VC	Wikipedia Virtual Collection	German Wikipedia 2015	ids	read	corpusSigle=WPD15 & creationDate since 2014-04-01	
+virtualcollection	GOE-VC	Goethe Virtual Collection	Goethe works from 1810	public	read	corpusSigle=GOE & creationDate since 1810-01-01
 virtualcollection	BRZ10-PC	Braunschweiger Collection	Selected Braunschweiger Zeitung	ids	read	corpusSigle=BRZ10 & foundries ~ Connexor
 corpus	WPD13	Wikipedia 2013	Public German Wikipedia 2013	public	read
 corpus	WPD15	Wikipedia 2015	IDS German Wikipedia 2015	ids	read
 corpus	GOE	Goethe	Goethe corpus	public	read
 corpus	BRZ10	Braunschweiger	Braunschweiger Zeitung 2010	ids	read
-type	id	name	description	condition	permissions
 foundry	base	base	Base foundry	public	read
 foundry	dereko	dereko	DeReKo foundry	public	read
 foundry	corenlp	corenlp	CoreNLP parser	public	read