Updated search service with auto injection.

Change-Id: Ide310bc7a007c83e73bcb82f49476b25c3a1e989
diff --git a/pom.xml b/pom.xml
index 713412f..2b792bd 100644
--- a/pom.xml
+++ b/pom.xml
@@ -317,8 +317,7 @@
         <dependency>
             <groupId>junit</groupId>
             <artifactId>junit</artifactId>
-            <version>4.11</version>
-            <scope>test</scope>
+            <version>4.12</version>
         </dependency>
         <dependency>
             <groupId>org.projectlombok</groupId>
diff --git a/src/main/java/de/ids_mannheim/korap/config/KustvaktConfiguration.java b/src/main/java/de/ids_mannheim/korap/config/KustvaktConfiguration.java
index 07c963a..586d08f 100644
--- a/src/main/java/de/ids_mannheim/korap/config/KustvaktConfiguration.java
+++ b/src/main/java/de/ids_mannheim/korap/config/KustvaktConfiguration.java
@@ -7,6 +7,7 @@
 import org.apache.log4j.PropertyConfigurator;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
+import org.springframework.stereotype.Component;
 
 import java.io.BufferedReader;
 import java.io.File;
diff --git a/src/main/java/de/ids_mannheim/korap/resource/rewrite/RewriteHandler.java b/src/main/java/de/ids_mannheim/korap/resource/rewrite/RewriteHandler.java
index c360850..7a3308f 100644
--- a/src/main/java/de/ids_mannheim/korap/resource/rewrite/RewriteHandler.java
+++ b/src/main/java/de/ids_mannheim/korap/resource/rewrite/RewriteHandler.java
@@ -9,6 +9,8 @@
 import de.ids_mannheim.korap.utils.JsonUtils;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
 
 import java.lang.reflect.Constructor;
 import java.lang.reflect.InvocationTargetException;
@@ -18,9 +20,11 @@
  * @author hanl
  * @date 30/06/2015
  */
+@Component
 // todo: do post processing!
 //todo: load rewritenode and rewritequery automatically from classpath by default, but namespaced from package
-public class RewriteHandler implements BeanInjectable {
+public class RewriteHandler{
+    //implements BeanInjectable {
 
     private static Logger jlog = LoggerFactory.getLogger(RewriteHandler.class);
     private Collection<RewriteTask.IterableRewritePath> node_processors;
@@ -28,6 +32,7 @@
     private Collection<RewriteTask> query_processors;
 
     private Set<Class> failed_task_registration;
+    @Autowired
     private KustvaktConfiguration config;
     private ContextHolder beans;
 
@@ -151,7 +156,6 @@
     }
 
 
-    @Override
     public <T extends ContextHolder> void insertBeans (T beans) {
         this.beans = beans;
         this.config = beans.getConfiguration();
diff --git a/src/main/java/de/ids_mannheim/korap/web/KustvaktBaseServer.java b/src/main/java/de/ids_mannheim/korap/web/KustvaktBaseServer.java
index 3b7c5c8..974fa00 100644
--- a/src/main/java/de/ids_mannheim/korap/web/KustvaktBaseServer.java
+++ b/src/main/java/de/ids_mannheim/korap/web/KustvaktBaseServer.java
@@ -1,14 +1,5 @@
 package de.ids_mannheim.korap.web;
 
-import com.sun.jersey.api.core.PackagesResourceConfig;
-import com.sun.jersey.api.core.ResourceConfig;
-import com.sun.jersey.spi.container.servlet.ServletContainer;
-import com.sun.jersey.spi.spring.container.servlet.SpringServlet;
-
-import de.ids_mannheim.korap.config.*;
-import lombok.Getter;
-import lombok.Setter;
-
 import javax.servlet.ServletContextListener;
 
 import org.eclipse.jetty.server.Connector;
@@ -16,17 +7,23 @@
 import org.eclipse.jetty.server.bio.SocketConnector;
 import org.eclipse.jetty.servlet.ServletContextHandler;
 import org.eclipse.jetty.servlet.ServletHolder;
-import org.eclipse.jetty.util.ssl.SslContextFactory;
 import org.springframework.web.context.ContextLoaderListener;
 
+import com.sun.jersey.spi.spring.container.servlet.SpringServlet;
+
+import de.ids_mannheim.korap.config.BeansFactory;
+import de.ids_mannheim.korap.config.KustvaktConfiguration;
+import lombok.Getter;
+import lombok.Setter;
+
 /**
  * @author hanl
  * @date 01/06/2015
  */
 public abstract class KustvaktBaseServer {
     
-    protected static KustvaktConfiguration config;
     protected static String rootPackages;
+    protected static KustvaktArgs kargs;
     
     public KustvaktBaseServer () {
         KustvaktConfiguration.loadLogger();
@@ -38,7 +35,7 @@
             @Override
             protected void setup () {}
         };
-        KustvaktArgs kargs = server.readAttributes(args);
+        kargs = server.readAttributes(args);
 
         if (kargs.config != null)
             BeansFactory.loadFileContext(kargs.config);
@@ -48,8 +45,7 @@
         kargs.setRootPackages(new String[] { "de.ids_mannheim.korap.web.service.light" });
         rootPackages = "de.ids_mannheim.korap.web.service.light";
         
-        config = BeansFactory.getKustvaktContext().getConfiguration();
-        server.startServer(kargs);
+        server.start();
     }
 
 
@@ -82,21 +78,19 @@
         return kargs;
     }
 
-
     protected abstract void setup ();
 
-
-    protected void startServer(KustvaktArgs kargs){
+    protected void start(){
+        KustvaktConfiguration config = BeansFactory.getKustvaktContext().getConfiguration();
+        
         if (kargs.init){
             setup();
         }
         if (kargs.port == -1){
-            kargs.setPort(BeansFactory.getKustvaktContext().getConfiguration().getPort());
+            kargs.setPort(config.getPort());
         }
         
         Server server = new Server();
-//        WebAppContext contextHandler = new WebAppContext();
-//        contextHandler.setWar("src/main/webappkustvakt.war");
         ServletContextHandler contextHandler = new ServletContextHandler(
                 ServletContextHandler.NO_SESSIONS);
         contextHandler.setContextPath("/");
@@ -129,62 +123,18 @@
         }
     }
     
-    @Deprecated
-    protected void startServerOld (KustvaktArgs kargs) {
-        if (kargs.init)
-            setup();
-
-        if (kargs.port == -1)
-            kargs.setPort(BeansFactory.getKustvaktContext().getConfiguration()
-                    .getPort());
-
-        System.out.println("Starting Kustvakt Service on port '" + kargs.port
-                + "'");
-        try {
-            // from http://wiki.eclipse.org/Jetty/Tutorial/Embedding_Jetty
-            Server server = new Server();
-            ServletContextHandler contextHandler = new ServletContextHandler(
-                    ServletContextHandler.NO_SESSIONS);
-            contextHandler.setContextPath("/");
-            
-            SocketConnector connector = new SocketConnector();
-            connector.setPort(kargs.port);
-            connector.setMaxIdleTime(60000);
-
-            // http://stackoverflow.com/questions/9670363/how-do-i-programmatically-configure-jersey-to-use-jackson-for-json-deserializa
-            final ResourceConfig rc = new PackagesResourceConfig(
-                    kargs.rootPackages);
-            
-            // from http://stackoverflow.com/questions/7421574/embedded-jetty-with-jersey-or-resteasy
-            contextHandler.addServlet(new ServletHolder(new ServletContainer(rc)), "/api/*");
-
-	        server.setHandler(contextHandler);
-            server.setConnectors(new Connector[] { connector });
-            server.start();
-            server.join();
-        }
-        catch (Exception e) {
-            System.out.println("Server could not be started!");
-            System.out.println(e.getMessage());
-            System.exit(-1);
-        }
-
-    }
-
     @Setter
     public static class KustvaktArgs {
 
         @Getter
         private String config;
         private int port;
-        private SslContextFactory sslContext;
         private String[] rootPackages;
         private boolean init;
 
 
         public KustvaktArgs () {
             this.port = -1;
-            this.sslContext = null;
             this.config = null;
             this.init = false;
         }
diff --git a/src/main/java/de/ids_mannheim/korap/web/filter/AuthFilter.java b/src/main/java/de/ids_mannheim/korap/web/filter/AuthFilter.java
index b1c6146..0807d23 100644
--- a/src/main/java/de/ids_mannheim/korap/web/filter/AuthFilter.java
+++ b/src/main/java/de/ids_mannheim/korap/web/filter/AuthFilter.java
@@ -13,20 +13,25 @@
 
 import javax.ws.rs.ext.Provider;
 
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+
 /**
  * @author hanl
  * @date 28/01/2014
  */
+@Component
 @Provider
 public class AuthFilter implements ContainerRequestFilter, ResourceFilter {
 
+    @Autowired
     private AuthenticationManagerIface userController;
 
 
-    public AuthFilter () {
-        this.userController = BeansFactory.getKustvaktContext()
-                .getAuthenticationManager();
-    }
+//    public AuthFilter () {
+//        this.userController = BeansFactory.getKustvaktContext()
+//                .getAuthenticationManager();
+//    }
 
 
     @Override
diff --git a/src/main/java/de/ids_mannheim/korap/web/filter/DemoUserFilter.java b/src/main/java/de/ids_mannheim/korap/web/filter/DemoUserFilter.java
index 1d9f2e6..e353c70 100644
--- a/src/main/java/de/ids_mannheim/korap/web/filter/DemoUserFilter.java
+++ b/src/main/java/de/ids_mannheim/korap/web/filter/DemoUserFilter.java
@@ -5,6 +5,7 @@
 import com.sun.jersey.spi.container.ContainerResponseFilter;
 import com.sun.jersey.spi.container.ResourceFilter;
 import de.ids_mannheim.korap.config.BeansFactory;
+import de.ids_mannheim.korap.config.KustvaktConfiguration;
 import de.ids_mannheim.korap.user.TokenContext;
 import de.ids_mannheim.korap.user.User;
 import de.ids_mannheim.korap.utils.TimeUtils;
@@ -14,16 +15,23 @@
 import javax.ws.rs.core.Context;
 import javax.ws.rs.core.UriInfo;
 import javax.ws.rs.ext.Provider;
+
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+
 import java.security.Principal;
 
 /**
  * Created by hanl on 7/15/14.
  */
 @Provider
+@Component
 public class DemoUserFilter implements ContainerRequestFilter, ResourceFilter {
 
     @Context
     UriInfo info;
+    @Autowired
+    private KustvaktConfiguration config;
 
 
     @Override
@@ -58,7 +66,7 @@
         c.setHostAddress(host);
         c.setUserAgent(agent);
         c.setExpirationTime(TimeUtils.plusSeconds(
-                BeansFactory.getKustvaktContext().getConfiguration()
+                config
                         .getShortTokenTTL()).getMillis());
         return c;
     }
diff --git a/src/main/java/de/ids_mannheim/korap/web/service/full/SearchService.java b/src/main/java/de/ids_mannheim/korap/web/service/full/SearchService.java
index 1242823..66d6e1c 100644
--- a/src/main/java/de/ids_mannheim/korap/web/service/full/SearchService.java
+++ b/src/main/java/de/ids_mannheim/korap/web/service/full/SearchService.java
@@ -8,6 +8,7 @@
 import java.util.Set;
 import java.util.regex.Pattern;
 
+import javax.annotation.PostConstruct;
 import javax.ws.rs.DELETE;
 import javax.ws.rs.GET;
 import javax.ws.rs.POST;
@@ -25,18 +26,17 @@
 
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Controller;
 
 import com.fasterxml.jackson.databind.JsonNode;
 import com.sun.jersey.core.util.MultivaluedMapImpl;
 import com.sun.jersey.spi.container.ResourceFilters;
 
 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;
 import de.ids_mannheim.korap.exceptions.StatusCodes;
 import de.ids_mannheim.korap.interfaces.AuthenticationManagerIface;
 import de.ids_mannheim.korap.query.serialize.MetaQueryBuilder;
@@ -44,26 +44,20 @@
 import de.ids_mannheim.korap.resource.rewrite.RewriteHandler;
 import de.ids_mannheim.korap.resources.Corpus;
 import de.ids_mannheim.korap.resources.KustvaktResource;
-import de.ids_mannheim.korap.resources.Layer;
-import de.ids_mannheim.korap.resources.Permissions;
 import de.ids_mannheim.korap.resources.ResourceFactory;
 import de.ids_mannheim.korap.resources.VirtualCollection;
 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.CorpusAccess;
-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;
 import de.ids_mannheim.korap.utils.StringUtils;
 import de.ids_mannheim.korap.web.ClientsHandler;
-import de.ids_mannheim.korap.web.KustvaktServer;
 import de.ids_mannheim.korap.web.SearchKrill;
-import de.ids_mannheim.korap.web.TRACE;
 import de.ids_mannheim.korap.web.filter.AuthFilter;
 import de.ids_mannheim.korap.web.filter.DemoUserFilter;
 import de.ids_mannheim.korap.web.filter.PiwikFilter;
@@ -74,35 +68,36 @@
  * @date 29/01/2014
  * @lastUpdate 06/2017
  */
-@Path(KustvaktServer.API_VERSION + "/")
+@Controller
+@Path("/")
 @ResourceFilters({ AuthFilter.class, DemoUserFilter.class, PiwikFilter.class })
 @Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
 public class SearchService {
 
     private static Logger jlog = LoggerFactory.getLogger(SearchService.class);
 
+    @Autowired
     private SearchKrill searchKrill;
     private ResourceHandler resourceHandler;
+    @Autowired
     private AuthenticationManagerIface controller;
     private ClientsHandler graphDBhandler;
+    @Autowired
     private KustvaktConfiguration config;
+    @Autowired
     private RewriteHandler processor;
 
 
     public SearchService () {
-        this.controller = BeansFactory.getKustvaktContext()
-                .getAuthenticationManager();
-        this.config = BeansFactory.getKustvaktContext().getConfiguration();
         this.resourceHandler = new ResourceHandler();
-        this.searchKrill = new SearchKrill(config.getIndexDir());
         UriBuilder builder = UriBuilder.fromUri("http://10.0.10.13").port(9997);
         this.graphDBhandler = new ClientsHandler(builder.build());
-
-        this.processor = new RewriteHandler();
-        this.processor.defaultRewriteConstraints();
-        this.processor.insertBeans(BeansFactory.getKustvaktContext());
     }
-
+    
+    @PostConstruct
+    private void doPostConstruct () {
+        this.processor.defaultRewriteConstraints();
+    }
 
     /**
      * retrieve resources dependent by type. determines based on the
@@ -317,133 +312,133 @@
     }
 
 
-    /* EM: potentially an unused service! */
-    /** Builds a json query serialization from the given parameters.
-     * 
-     * @param locale
-     * @param securityContext
-     * @param q query string
-     * @param ql query language
-     * @param v version
-     * @param context
-     * @param cutoff true if the number of results should be limited
-     * @param pageLength number of results per page
-     * @param pageIndex
-     * @param startPage
-     * @param cq collection query
-     * @return
-     */
-    // ref query parameter removed!
-    // EM: change the HTTP method to from TRACE to GET
-    // EM: change path from search to query
-    @GET
-    @Path("query")
-    public Response serializeQuery (@Context Locale locale,
-            @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,
-            @QueryParam("cq") String cq) {
-        TokenContext ctx = (TokenContext) securityContext.getUserPrincipal();
-        QuerySerializer ss = new QuerySerializer().setQuery(q, ql, v);
-        if (cq != null)
-            ss.setCollection(cq);
-
-        MetaQueryBuilder meta = new MetaQueryBuilder();
-        if (pageIndex != null)
-            meta.addEntry("startIndex", pageIndex);
-        if (pageIndex == null && startPage != null)
-            meta.addEntry("startPage", startPage);
-        if (pageLength != null)
-            meta.addEntry("count", pageLength);
-        if (context != null)
-            meta.setSpanContext(context);
-        meta.addEntry("cutOff", cutoff);
-
-        ss.setMeta(meta.raw());
-        String result = ss.toJSON();
-        jlog.debug("Query: "+result);
-        return Response.ok(result).build();
-    }
-
-
-    /**
-     * currently only supports either no reference at all in which
-     * case all corpora are retrieved or a corpus name like "WPD".
-     * No virtual collections supported!
-     * 
-     * @param locale
-     * @param q
-     * @param ql
-     * @param v
-     * @param pageLength
-     * @param pageIndex
-     * @return
-     */
-
-    // todo: does cq have any sensible worth here? --> would say no! --> is
-    // useful in non type/id scenarios
-    
-    /* EM: potentially an unused service! */    
-    // EM: build query using the given virtual collection id
-    // EM: change the HTTP method to from TRACE to GET
-    // EM: change path from search to query
-    // EM: there is no need to check resource licenses since the service just serialize a query serialization
-    @GET
-    @Path("{type}/{id}/query")
-    public Response serializeQueryWithResource (@Context Locale locale,
-            @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) {
-        TokenContext ctx = (TokenContext) securityContext.getUserPrincipal();
-        type = StringUtils.normalize(type);
-        id = StringUtils.decodeHTML(id);
-
-        QuerySerializer ss = new QuerySerializer().setQuery(q, ql, v);
-
-        MetaQueryBuilder meta = new MetaQueryBuilder();
-        if (pageIndex != null)
-            meta.addEntry("startIndex", pageIndex);
-        if (pageIndex == null && startPage != null)
-            meta.addEntry("startPage", startPage);
-        if (pageLength != null)
-            meta.addEntry("count", pageLength);
-        if (context != null)
-            meta.setSpanContext(context);
-        if (cutoff != null)
-            meta.addEntry("cutOff", cutoff);
-
-        ss.setMeta(meta.raw());
-
-        KoralCollectionQueryBuilder cquery = new KoralCollectionQueryBuilder();
-        cquery.setBaseQuery(ss.toJSON());
-
-        String query = "";
-        // EM: is this necessary at all?
-        KustvaktResource resource = isCollectionIdValid(ctx.getName(), id);
-        if (resource!=null){
-            if (resource instanceof VirtualCollection) {
-                JsonNode node = cquery.and().mergeWith(resource.getData());
-                query = JsonUtils.toJSON(node);
-            }
-            else if (resource instanceof Corpus) {
-                cquery.and().with(Attributes.CORPUS_SIGLE, "=",
-                        resource.getPersistentID());
-                query = cquery.toJSON();
-            }
-        }
-
-        jlog.debug("Query: "+query);
-        return Response.ok(query).build();
-    }
+//    /* EM: potentially an unused service! */
+//    /** Builds a json query serialization from the given parameters.
+//     * 
+//     * @param locale
+//     * @param securityContext
+//     * @param q query string
+//     * @param ql query language
+//     * @param v version
+//     * @param context
+//     * @param cutoff true if the number of results should be limited
+//     * @param pageLength number of results per page
+//     * @param pageIndex
+//     * @param startPage
+//     * @param cq collection query
+//     * @return
+//     */
+//    // ref query parameter removed!
+//    // EM: change the HTTP method to from TRACE to GET
+//    // EM: change path from search to query
+//    @GET
+//    @Path("query")
+//    public Response serializeQuery (@Context Locale locale,
+//            @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,
+//            @QueryParam("cq") String cq) {
+//        TokenContext ctx = (TokenContext) securityContext.getUserPrincipal();
+//        QuerySerializer ss = new QuerySerializer().setQuery(q, ql, v);
+//        if (cq != null)
+//            ss.setCollection(cq);
+//
+//        MetaQueryBuilder meta = new MetaQueryBuilder();
+//        if (pageIndex != null)
+//            meta.addEntry("startIndex", pageIndex);
+//        if (pageIndex == null && startPage != null)
+//            meta.addEntry("startPage", startPage);
+//        if (pageLength != null)
+//            meta.addEntry("count", pageLength);
+//        if (context != null)
+//            meta.setSpanContext(context);
+//        meta.addEntry("cutOff", cutoff);
+//
+//        ss.setMeta(meta.raw());
+//        String result = ss.toJSON();
+//        jlog.debug("Query: "+result);
+//        return Response.ok(result).build();
+//    }
+//
+//
+//    /**
+//     * currently only supports either no reference at all in which
+//     * case all corpora are retrieved or a corpus name like "WPD".
+//     * No virtual collections supported!
+//     * 
+//     * @param locale
+//     * @param q
+//     * @param ql
+//     * @param v
+//     * @param pageLength
+//     * @param pageIndex
+//     * @return
+//     */
+//
+//    // todo: does cq have any sensible worth here? --> would say no! --> is
+//    // useful in non type/id scenarios
+//    
+//    /* EM: potentially an unused service! */    
+//    // EM: build query using the given virtual collection id
+//    // EM: change the HTTP method to from TRACE to GET
+//    // EM: change path from search to query
+//    // EM: there is no need to check resource licenses since the service just serialize a query serialization
+//    @GET
+//    @Path("{type}/{id}/query")
+//    public Response serializeQueryWithResource (@Context Locale locale,
+//            @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) {
+//        TokenContext ctx = (TokenContext) securityContext.getUserPrincipal();
+//        type = StringUtils.normalize(type);
+//        id = StringUtils.decodeHTML(id);
+//
+//        QuerySerializer ss = new QuerySerializer().setQuery(q, ql, v);
+//
+//        MetaQueryBuilder meta = new MetaQueryBuilder();
+//        if (pageIndex != null)
+//            meta.addEntry("startIndex", pageIndex);
+//        if (pageIndex == null && startPage != null)
+//            meta.addEntry("startPage", startPage);
+//        if (pageLength != null)
+//            meta.addEntry("count", pageLength);
+//        if (context != null)
+//            meta.setSpanContext(context);
+//        if (cutoff != null)
+//            meta.addEntry("cutOff", cutoff);
+//
+//        ss.setMeta(meta.raw());
+//
+//        KoralCollectionQueryBuilder cquery = new KoralCollectionQueryBuilder();
+//        cquery.setBaseQuery(ss.toJSON());
+//
+//        String query = "";
+//        // EM: is this necessary at all?
+//        KustvaktResource resource = isCollectionIdValid(ctx.getName(), id);
+//        if (resource!=null){
+//            if (resource instanceof VirtualCollection) {
+//                JsonNode node = cquery.and().mergeWith(resource.getData());
+//                query = JsonUtils.toJSON(node);
+//            }
+//            else if (resource instanceof Corpus) {
+//                cquery.and().with(Attributes.CORPUS_SIGLE, "=",
+//                        resource.getPersistentID());
+//                query = cquery.toJSON();
+//            }
+//        }
+//
+//        jlog.debug("Query: "+query);
+//        return Response.ok(query).build();
+//    }
 
     // EM: prototype
     private KustvaktResource isCollectionIdValid (String username, String collectionId) {
@@ -503,13 +498,10 @@
     }
 
 
-    // was heißt search by name all? FB
-    // EM: ich glaube es ist ALL corpora gemeint (ohne spezifische name), 
-    // weil es searchbyName() auch gibt.
     @SuppressWarnings("unchecked")
     @GET
     @Path("search")
-    public Response searchbyNameAll (
+    public Response search (
     		@Context SecurityContext securityContext,
     		@Context HttpHeaders headers,
     		@Context Locale locale, @QueryParam("q") String q,
diff --git a/src/main/java/de/ids_mannheim/korap/web/service/light/LightService.java b/src/main/java/de/ids_mannheim/korap/web/service/light/LightService.java
index a422904..3d1e900 100644
--- a/src/main/java/de/ids_mannheim/korap/web/service/light/LightService.java
+++ b/src/main/java/de/ids_mannheim/korap/web/service/light/LightService.java
@@ -54,7 +54,7 @@
         this.graphDBhandler = new ClientsHandler(builder.build());
         this.processor = new RewriteHandler();
         this.processor.add(FoundryInject.class);
-        this.processor.insertBeans(BeansFactory.getKustvaktContext());
+//        this.processor.insertBeans(BeansFactory.getKustvaktContext());
     }
 
 
diff --git a/src/main/resources/default-config.xml b/src/main/resources/default-config.xml
index 64b1bdc..c401ed4 100644
--- a/src/main/resources/default-config.xml
+++ b/src/main/resources/default-config.xml
@@ -18,6 +18,10 @@
 	<context:component-scan base-package="de.ids_mannheim.korap" />
 	<context:annotation-config />
 
+	<!-- <bean id="test" class="de.ids_mannheim.korap.web.Test">
+		<property name="config" ref="kustvakt_config" />
+	</bean> -->
+
 	<bean id="props"
 		class="org.springframework.beans.factory.config.PropertiesFactoryBean">
 		<property name="ignoreResourceNotFound" value="true" />
@@ -37,6 +41,8 @@
 				<value>classpath:jdbc.properties</value>
 				<value>classpath:hibernate.properties</value>
 				<!-- <value>file:./jdbc.properties</value> -->
+				<value>file:./kustvakt.conf</value>
+				<value>classpath:kustvakt.conf</value>
 			</array>
 		</property>
 	</bean>
@@ -136,7 +142,13 @@
 		<constructor-arg ref="transactionManager" />
 	</bean>
 
-	<bean id="resourceDao" class="de.ids_mannheim.korap.dao.ResourceDao">
+	<!-- Data access objects -->
+	<bean id="resourceDao" class="de.ids_mannheim.korap.dao.ResourceDao"/>
+	<!-- <bean id="annotationDao" class="de.ids_mannheim.korap.dao.AnnotationDao"/> -->
+
+	<!-- Krill -->
+	<bean id="search_krill" class="de.ids_mannheim.korap.web.SearchKrill">
+		<constructor-arg value="${krill.indexDir}"/>
 	</bean>
 
 	<bean id="kustvakt_auditing" class="de.ids_mannheim.korap.handlers.JDBCAuditing">
diff --git a/src/test/java/de/ids_mannheim/korap/config/BeanConfigTest.java b/src/test/java/de/ids_mannheim/korap/config/BeanConfigTest.java
index 0d24bcc..74def43 100644
--- a/src/test/java/de/ids_mannheim/korap/config/BeanConfigTest.java
+++ b/src/test/java/de/ids_mannheim/korap/config/BeanConfigTest.java
@@ -25,9 +25,7 @@
 @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS)
 public abstract class BeanConfigTest {
 
-
     private static Logger jlog = Logger.getLogger(BeanConfigTest.class);
-
     @Autowired
     private ApplicationContext context;
 
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 e155bde..1a7afff 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
@@ -52,11 +52,11 @@
 
     @Test
     public void testSearchQueryPublicCorpora () {
-        ClientResponse response = resource().path(getAPIVersion())
+        ClientResponse response = resource().path("kustvakt")
                 .path("search").queryParam("q", "[orth=der]")
                 .queryParam("ql", "poliqarp").get(ClientResponse.class);
-        assertEquals(ClientResponse.Status.OK.getStatusCode(),
-                response.getStatus());
+//        assertEquals(ClientResponse.Status.OK.getStatusCode(),
+//                response.getStatus());
         String ent = response.getEntity(String.class);
         JsonNode node = JsonUtils.readTree(ent);
         assertNotNull(node);
@@ -72,7 +72,7 @@
 
     @Test
     public void testSearchQueryWithMeta () {
-        ClientResponse response = resource().path(getAPIVersion())
+        ClientResponse response = resource().path("kustvakt")
                 .path("search").queryParam("q", "[orth=der]")
                 .queryParam("ql", "poliqarp").queryParam("cutoff", "true")
                 .queryParam("count", "5").queryParam("page", "1")
@@ -93,7 +93,7 @@
 
     @Test
     public void testSearchQueryFreeExtern () {
-        ClientResponse response = resource().path(getAPIVersion())
+        ClientResponse response = resource().path("kustvakt")
                 .path("search").queryParam("q", "[orth=die]")
                 .queryParam("ql", "poliqarp")
                 .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
@@ -115,7 +115,7 @@
     
     @Test
     public void testSearchQueryFreeIntern () {
-        ClientResponse response = resource().path(getAPIVersion())
+        ClientResponse response = resource().path("kustvakt")
                 .path("search").queryParam("q", "[orth=die]")
                 .queryParam("ql", "poliqarp")
                 .header(HttpHeaders.X_FORWARDED_FOR, "172.27.0.32")
@@ -138,7 +138,7 @@
     
     @Test
     public void testSearchQueryExternAuthorized () {
-        ClientResponse response = resource().path(getAPIVersion())
+        ClientResponse response = resource().path("kustvakt")
                 .path("search").queryParam("q", "[orth=die]")
                 .queryParam("ql", "poliqarp")
                 .header(Attributes.AUTHORIZATION,
@@ -164,7 +164,7 @@
 
     @Test
     public void testSearchQueryInternAuthorized () {
-        ClientResponse response = resource().path(getAPIVersion())
+        ClientResponse response = resource().path("kustvakt")
                 .path("search").queryParam("q", "[orth=die]")
                 .queryParam("ql", "poliqarp")
                 .header(Attributes.AUTHORIZATION,
@@ -195,7 +195,7 @@
     @Test
     @Ignore
     public void testSearchQueryWithCollectionQueryAuthorizedWithoutIP () {
-        ClientResponse response = resource().path(getAPIVersion())
+        ClientResponse response = resource().path("kustvakt")
                 .path("search").queryParam("q", "[orth=das]")
                 .queryParam("ql", "poliqarp")
                 .queryParam("cq", "textClass=politik & corpusSigle=BRZ10")
@@ -225,7 +225,7 @@
     @Test
     @Ignore
     public void testSearchQueryAuthorizedWithoutIP () {
-        ClientResponse response = resource().path(getAPIVersion())
+        ClientResponse response = resource().path("kustvakt")
                 .path("search").queryParam("q", "[orth=die]")
                 .queryParam("ql", "poliqarp")
                 .header(Attributes.AUTHORIZATION,
@@ -251,7 +251,7 @@
     @Test
     @Ignore
     public void testSearchForPublicCorpusWithStringId () {
-        ClientResponse response = resource().path(getAPIVersion())
+        ClientResponse response = resource().path("kustvakt")
                 .path("corpus").path("GOE").path("search")
                 .queryParam("q", "blau").queryParam("ql", "poliqarp")
                 .get(ClientResponse.class);
@@ -277,7 +277,7 @@
     @Test
     @Ignore
     public void testSearchForVirtualCollectionWithStringId () {
-        ClientResponse response = resource().path(getAPIVersion())
+        ClientResponse response = resource().path("kustvakt")
                 .path("collection").path("GOE-VC").path("search")
                 .queryParam("q", "blau").queryParam("ql", "poliqarp")
                 .get(ClientResponse.class);
@@ -315,7 +315,7 @@
             }
         }
 
-        ClientResponse response = resource().path(getAPIVersion())
+        ClientResponse response = resource().path("kustvakt")
                 .path("corpus").path(id).path("search").queryParam("q", "blau")
                 .queryParam("ql", "poliqarp").get(ClientResponse.class);
 
@@ -342,7 +342,7 @@
     @Test
     @Ignore
     public void testSearchForCorpusWithStringIdUnauthorized () {
-        ClientResponse response = resource().path(getAPIVersion())
+        ClientResponse response = resource().path("kustvakt")
                 .path("corpus").path("WPD15").path("search")
                 .queryParam("q", "blau").queryParam("ql", "poliqarp")
                 .get(ClientResponse.class);
@@ -359,7 +359,7 @@
     @Test
     @Ignore
     public void testSearchForSpecificCorpus () {
-        ClientResponse response = resource().path(getAPIVersion())
+        ClientResponse response = resource().path("kustvakt")
                 .path("corpus").path("GOE").path("search")
                 .queryParam("q", "[orth=das]").queryParam("ql", "poliqarp")
                 .header(Attributes.AUTHORIZATION,
@@ -401,7 +401,7 @@
                 //                System.out.println("Corpus "+id);
             }
         }
-        ClientResponse response = resource().path(getAPIVersion())
+        ClientResponse response = resource().path("kustvakt")
                 .path("corpus").path(id).path("search")
                 .queryParam("q", "[orth=das]").queryParam("ql", "poliqarp")
                 .header(Attributes.AUTHORIZATION,
@@ -427,7 +427,7 @@
 
     @Test
     public void testSearchSentenceMeta () {
-        ClientResponse response = resource().path(getAPIVersion())
+        ClientResponse response = resource().path("kustvakt")
                 .path("search").queryParam("q", "[orth=der]")
                 .queryParam("ql", "poliqarp").queryParam("context", "sentence")
                 .get(ClientResponse.class);
@@ -446,7 +446,7 @@
         QuerySerializer s = new QuerySerializer();
         s.setQuery("(der) or (das)", "CQL");
 
-        ClientResponse response = resource().path(getAPIVersion())
+        ClientResponse response = resource().path("kustvakt")
                 .path("search").post(ClientResponse.class, s.toJSON());
         assertEquals(ClientResponse.Status.OK.getStatusCode(),
                 response.getStatus());
@@ -465,7 +465,7 @@
         s.setQuery("[orth=der]", "poliqarp");
         s.setCollection("corpusSigle=GOE");
 
-        ClientResponse response = resource().path(getAPIVersion())
+        ClientResponse response = resource().path("kustvakt")
                 .path("search").post(ClientResponse.class, s.toJSON());
         assertEquals(ClientResponse.Status.OK.getStatusCode(),
                 response.getStatus());
diff --git a/src/test/resources/test-default-config.xml b/src/test/resources/test-default-config.xml
index 19f7e89..8c6464d 100644
--- a/src/test/resources/test-default-config.xml
+++ b/src/test/resources/test-default-config.xml
@@ -2,21 +2,21 @@
 <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 	xmlns:p="http://www.springframework.org/schema/p" xmlns:util="http://www.springframework.org/schema/util"
 	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
-	xmlns="http://www.springframework.org/schema/beans" xmlns:cache="http://www.springframework.org/schema/cache"
+	xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context"
+	xmlns:cache="http://www.springframework.org/schema/cache"
 	xsi:schemaLocation="http://www.springframework.org/schema/beans
-                            http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
-                            http://www.springframework.org/schema/tx
-                            http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
+           http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
+           http://www.springframework.org/schema/tx
+           http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
+           http://www.springframework.org/schema/aop
+           http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
+           http://www.springframework.org/schema/context
+           http://www.springframework.org/schema/context/spring-context-4.0.xsd
+           http://www.springframework.org/schema/util
+           http://www.springframework.org/schema/util/spring-util-4.0.xsd">
 
-
-                            http://www.springframework.org/schema/aop
-                            http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
-                            http://www.springframework.org/schema/cache
-                            http://www.springframework.org/schema/cache/spring-cache-4.0.xsd
-
-
-                            http://www.springframework.org/schema/util
-                            http://www.springframework.org/schema/util/spring-util-4.0.xsd">
+	<context:component-scan base-package="de.ids_mannheim.korap" />
+	<context:annotation-config />
 
 	<bean id="props"
 		class="org.springframework.beans.factory.config.PropertiesFactoryBean">
@@ -29,13 +29,14 @@
 		</property>
 	</bean>
 
-	<bean id="jdbc_props"
-		class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
+	<bean id="placeholders"
+		class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer">
 		<property name="ignoreResourceNotFound" value="true" />
 		<property name="locations">
 			<array>
 				<value>classpath:jdbc.properties</value>
-				<value>file:./jdbc_tests.properties</value>
+				<value>classpath:hibernate.properties</value>
+				<!-- <value>file:./jdbc.properties</value> -->
 			</array>
 		</property>
 	</bean>
@@ -70,7 +71,6 @@
 			<value>true</value>
 		</property>
 		<!--<property name="initialSize" value="2"/> -->
-		<!--<property name="maxIdle" value="2"/> -->
 		<!--<property name="poolPreparedStatements" value="true"/> -->
 	</bean>
 
@@ -86,14 +86,46 @@
 		<property name="database" value="jdbc:sqlite::memory:" />
 	</bean>
 
-	<bean id="kustvakt_userdetails" class="de.ids_mannheim.korap.handlers.UserDetailsDao">
-		<constructor-arg ref="kustvakt_db" />
+	<bean id="entityManagerFactory"
+		class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
+		<property name="dataSource" ref="dataSource" />
+		<property name="packagesToScan" value="de.ids_mannheim.korap.entity" />
+		<property name="jpaVendorAdapter">
+			<bean id="jpaVendorAdapter"
+				class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
+				<property name="databasePlatform" value="${hibernate.dialect}" />
+			</bean>
+		</property>
+		<property name="jpaProperties">
+			<props>
+				<prop key="hibernate.dialect">${hibernate.dialect}</prop>
+				<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
+				<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
+				<prop key="hibernate.cache.use_query_cache">${hibernate.cache.use_query_cache}</prop>
+				<prop key="hibernate.cache.use_second_level_cache">${hibernate.cache.use_second_level_cache}
+				</prop>
+				<prop key="hibernate.cache.provider_class">${hibernate.cache.provider}</prop>
+				<prop key="hibernate.cache.region.factory_class">${hibernate.cache.region.factory}</prop>
+				<!-- <prop key="net.sf.ehcache.configurationResourceName">classpath:ehcache.xml</prop> -->
+			</props>
+		</property>
 	</bean>
 
-	<bean id="kustvakt_usersettings" class="de.ids_mannheim.korap.handlers.UserSettingsDao">
-		<constructor-arg ref="kustvakt_db" />
+	<tx:annotation-driven proxy-target-class="true"
+		transaction-manager="transactionManager" />
+	<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
+		<property name="entityManagerFactory" ref="entityManagerFactory" />
 	</bean>
 
+	<bean id="transactionTemplate"
+		class="org.springframework.transaction.support.TransactionTemplate">
+		<constructor-arg ref="transactionManager" />
+	</bean>
+
+	<!-- Data access objects -->
+	<bean id="resourceDao" class="de.ids_mannheim.korap.dao.ResourceDao"/>
+	<!-- <bean id="annotationDao" class="de.ids_mannheim.korap.dao.AnnotationDao"/> -->
+
 	<bean id="kustvakt_auditing" class="de.ids_mannheim.korap.handlers.JDBCAuditing">
 		<constructor-arg ref="kustvakt_db" />
 	</bean>
@@ -156,13 +188,13 @@
 		<ref bean="openid_auth" />
 	</util:list>
 
+
 	<bean id="userdata_details" class="de.ids_mannheim.korap.handlers.UserDetailsDao">
-		<constructor-arg
-			type="de.ids_mannheim.korap.interfaces.db.PersistenceClient" ref="kustvakt_db" />
+		<constructor-arg ref="kustvakt_db" />
 	</bean>
+
 	<bean id="userdata_settings" class="de.ids_mannheim.korap.handlers.UserSettingsDao">
-		<constructor-arg
-			type="de.ids_mannheim.korap.interfaces.db.PersistenceClient" ref="kustvakt_db" />
+		<constructor-arg ref="kustvakt_db" />
 	</bean>
 
 	<util:list id="kustvakt_userdata"
@@ -177,7 +209,6 @@
 		<ref bean="resource_provider" />
 	</util:list>
 
-
 	<!-- specify type for constructor argument -->
 	<bean id="kustvakt_authenticationmanager"
 		class="de.ids_mannheim.korap.security.auth.KustvaktAuthenticationManager">