Removed old policy related and deprecated code.

Change-Id: I678fdfda188dbda14078f4ccea5070f421401d05
diff --git a/full/Changes b/full/Changes
index 7c82ed6..73efd25 100644
--- a/full/Changes
+++ b/full/Changes
@@ -1,11 +1,13 @@
 version 0.60 release
-26/02/2018
+01/03/2018
 	- set up mail settings using localhost port 25 (margaretha)
 	- added mail template in kustvakt configuration (margaretha)
 	- added mail settings to readme (margaretha)
 	- disabled email notification for auto group (margaretha)
 	- added metadata retrieval (diewald)
 	- enabled custom implementation for email address retrieval (margaretha)
+	- removed old policy and deprecated code (margaretha)
+	- moved authentication related code to /full (margaretha)
 
 version 0.59.10	
 20/02/2018 
diff --git a/full/pom.xml b/full/pom.xml
index b1b92c8..20a8572 100644
--- a/full/pom.xml
+++ b/full/pom.xml
@@ -90,15 +90,10 @@
 				<configuration>
 					<reuseForks>false</reuseForks>
 					<forkCount>2</forkCount>
-					<threadCount>10</threadCount>
-					<argLine>-Xmx1024m -XX:MaxPermSize=256m</argLine>
+					<threadCount>4</threadCount>
+					<argLine>-Xmx512m -XX:MaxPermSize=256m</argLine>
 					<excludes>
-						<!-- <exclude>de/ids_mannheim/korap/suites/*.java</exclude> -->
-						<!-- <exclude>de/ids_mannheim/korap/dao/*.java</exclude> -->
 						<exclude>de/ids_mannheim/korap/authentication/*.java</exclude>
-						<!-- <exclude>**/ResourceServiceTest.java</exclude> -->
-						<!-- <exclude>**/ResourceInfoServiceTest.java</exclude> -->
-						<exclude>**/PolicyServiceTest.java</exclude>
 					</excludes>
 					<includes>
 						<include>de/ids_mannheim/korap/**/*.java</include>
@@ -161,7 +156,7 @@
 		<dependency>
 			<groupId>de.ids_mannheim.korap</groupId>
 			<artifactId>Kustvakt-core</artifactId>
-			<version>0.59.10</version>
+			<version>0.60</version>
 			<type>jar</type>
 		</dependency>
 		<!-- LDAP -->
diff --git a/full/src/main/java/de/ids_mannheim/korap/cache/ResourceCache.java b/full/src/main/java/de/ids_mannheim/korap/cache/ResourceCache.java
new file mode 100644
index 0000000..da3e40f
--- /dev/null
+++ b/full/src/main/java/de/ids_mannheim/korap/cache/ResourceCache.java
@@ -0,0 +1,56 @@
+package de.ids_mannheim.korap.cache;
+
+import de.ids_mannheim.korap.config.KustvaktCacheable;
+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.resources.KustvaktResource;
+import de.ids_mannheim.korap.resources.Permissions;
+import de.ids_mannheim.korap.resources.ResourceFactory;
+import de.ids_mannheim.korap.user.User;
+import net.sf.ehcache.CacheManager;
+import net.sf.ehcache.Element;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.Collection;
+
+/**
+ * @author hanl
+ * @date 23/03/2014
+ * 
+ * @author margaretha
+ * @date 01/03/2018
+ * 
+ * EM: removed resource related code, keep cache
+ */
+
+//todo: use interface (maybe a cachable interface?) and bean instanceing
+// todo: if cachable, data integrity needs to be checked! either remove caching or check integrity!
+@SuppressWarnings("all")
+public class ResourceCache extends KustvaktCacheable {
+
+    private static Logger jlog = LoggerFactory.getLogger(ResourceCache.class);
+
+    public ResourceCache () {
+        super("resources", "key:resources");
+    }
+
+
+    @Deprecated
+    public <T extends KustvaktResource> T getCache (Object id, Class<T> cz) {
+        Element e = CacheManager.getInstance().getCache("resources").get(id);
+        if (e != null)
+            return (T) e.getObjectValue();
+        else
+            return null;
+    }
+
+
+    @Deprecated
+    public <R extends KustvaktResource> void cache (R resource) {
+        CacheManager.getInstance().getCache("resources")
+                .put(new Element(resource.getPersistentID(), resource));
+    }
+}
diff --git a/full/src/main/java/de/ids_mannheim/korap/config/AuthenticationMethod.java b/full/src/main/java/de/ids_mannheim/korap/config/AuthenticationMethod.java
new file mode 100644
index 0000000..afd81ed
--- /dev/null
+++ b/full/src/main/java/de/ids_mannheim/korap/config/AuthenticationMethod.java
@@ -0,0 +1,5 @@
+package de.ids_mannheim.korap.config;
+
+public enum AuthenticationMethod {
+    LDAP, SHIBBOLETH, DATABASE; 
+}
diff --git a/full/src/main/java/de/ids_mannheim/korap/config/AuthenticationScheme.java b/full/src/main/java/de/ids_mannheim/korap/config/AuthenticationScheme.java
new file mode 100644
index 0000000..6d9c58e
--- /dev/null
+++ b/full/src/main/java/de/ids_mannheim/korap/config/AuthenticationScheme.java
@@ -0,0 +1,14 @@
+package de.ids_mannheim.korap.config;
+
+import org.apache.commons.lang.WordUtils;
+
+public enum AuthenticationScheme {
+    // standard http
+    BASIC, BEARER,
+    // custom
+    SESSION, API;
+    
+    public String displayName () {
+        return WordUtils.capitalizeFully(name());
+    }
+}
diff --git a/full/src/main/java/de/ids_mannheim/korap/interfaces/AuthenticationIface.java b/full/src/main/java/de/ids_mannheim/korap/interfaces/AuthenticationIface.java
new file mode 100644
index 0000000..8d715a7
--- /dev/null
+++ b/full/src/main/java/de/ids_mannheim/korap/interfaces/AuthenticationIface.java
@@ -0,0 +1,27 @@
+package de.ids_mannheim.korap.interfaces;
+
+import java.util.Map;
+
+import de.ids_mannheim.korap.config.TokenType;
+import de.ids_mannheim.korap.exceptions.KustvaktException;
+import de.ids_mannheim.korap.user.TokenContext;
+import de.ids_mannheim.korap.user.User;
+
+public interface AuthenticationIface {
+
+    public TokenContext getTokenContext(String authToken) throws KustvaktException;
+
+
+    public TokenContext createTokenContext(User user, Map<String, Object> attr)
+            throws KustvaktException;
+
+
+    void removeUserSession (String token) throws KustvaktException;
+
+
+    public TokenContext refresh (TokenContext context) throws KustvaktException;
+
+
+    public TokenType getTokenType ();
+
+}
diff --git a/full/src/main/java/de/ids_mannheim/korap/interfaces/AuthenticationManagerIface.java b/full/src/main/java/de/ids_mannheim/korap/interfaces/AuthenticationManagerIface.java
new file mode 100644
index 0000000..f968b61
--- /dev/null
+++ b/full/src/main/java/de/ids_mannheim/korap/interfaces/AuthenticationManagerIface.java
@@ -0,0 +1,131 @@
+package de.ids_mannheim.korap.interfaces;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Set;
+
+import javax.ws.rs.core.HttpHeaders;
+
+import de.ids_mannheim.korap.config.TokenType;
+import de.ids_mannheim.korap.config.AuthenticationMethod;
+import de.ids_mannheim.korap.config.AuthenticationScheme;
+import de.ids_mannheim.korap.config.KustvaktCacheable;
+import de.ids_mannheim.korap.exceptions.KustvaktException;
+import de.ids_mannheim.korap.user.TokenContext;
+import de.ids_mannheim.korap.user.User;
+import de.ids_mannheim.korap.user.Userdata;
+
+/**
+ * @author hanl
+ * @date 15/06/2015
+ */
+public abstract class AuthenticationManagerIface extends KustvaktCacheable {
+
+    private Map<TokenType, AuthenticationIface> providers;
+
+
+    public AuthenticationManagerIface () {
+        super("id_tokens", "key:id_tokens");
+        this.providers = new HashMap<>();
+    }
+
+
+    public void setProviders (Set<AuthenticationIface> providers) {
+        for (AuthenticationIface i : providers){
+            this.providers.put(i.getTokenType(), i);
+        }
+    }
+
+
+    protected AuthenticationIface getProvider (TokenType scheme, TokenType default_iface) {
+    	
+    	// Debug FB: loop a Map
+    	
+    	 /*for (Map.Entry<String, AuthenticationIface> entry : this.providers.entrySet()) 
+    		{
+    		System.out.println("Debug: provider: Key : " + entry.getKey() + " Value : " + entry.getValue());
+    		}
+    		*/
+     // todo: configurable authentication schema
+        if (scheme == null){ 
+            return this.providers.get(default_iface);
+        }
+        else{
+            return this.providers.get(scheme);
+        }
+    }
+
+
+    public abstract TokenContext getTokenContext (TokenType type,
+            String token, String host, String useragent)
+            throws KustvaktException;
+
+
+    public abstract User getUser (String username) throws KustvaktException;
+
+    public abstract boolean isRegistered (String id);
+
+
+    public abstract User authenticate (AuthenticationMethod method, String username,
+            String password, Map<String, Object> attributes)
+            throws KustvaktException;
+
+    //    public abstract User authenticate (int type, String username,
+    //            String password, Map<String, Object> attributes)
+    //            throws KustvaktException;
+
+
+    public abstract TokenContext createTokenContext (User user,
+            Map<String, Object> attr, TokenType type)
+            throws KustvaktException;
+    
+//    public abstract TokenContext createTokenContext (User user,
+//            Map<String, Object> attr, String provider_key)
+//            throws KustvaktException;
+
+    public abstract void setAccessAndLocation (User user, HttpHeaders headers);
+
+    public abstract void logout (TokenContext context) throws KustvaktException;
+
+
+    public abstract void lockAccount (User user) throws KustvaktException;
+
+
+    public abstract User createUserAccount (Map<String, Object> attributes,
+            boolean confirmation_required) throws KustvaktException;
+
+
+    //    public abstract boolean updateAccount(User user) throws KustvaktException;
+
+    public abstract boolean deleteAccount (User user) throws KustvaktException;
+
+
+    public abstract <T extends Userdata> T getUserData (User user,
+            Class<T> clazz) throws KustvaktException;
+
+
+    public abstract void updateUserData (Userdata data)
+            throws KustvaktException;
+
+
+    public abstract Object[] validateResetPasswordRequest (String username,
+            String email) throws KustvaktException;
+
+
+    public abstract void resetPassword (String uriFragment, String username,
+            String newPassphrase) throws KustvaktException;
+
+
+    public abstract void confirmRegistration (String uriFragment,
+            String username) throws KustvaktException;
+
+
+    public String providerList () {
+        return "provider list: " + this.providers.toString();
+    }
+
+
+    public abstract User getUser (String username, String method)
+            throws KustvaktException;
+
+}
diff --git a/full/src/main/java/de/ids_mannheim/korap/rewrite/CollectionConstraint.java b/full/src/main/java/de/ids_mannheim/korap/rewrite/CollectionConstraint.java
new file mode 100644
index 0000000..5d212dd
--- /dev/null
+++ b/full/src/main/java/de/ids_mannheim/korap/rewrite/CollectionConstraint.java
@@ -0,0 +1,74 @@
+package de.ids_mannheim.korap.rewrite;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import de.ids_mannheim.korap.config.Attributes;
+import de.ids_mannheim.korap.config.KustvaktConfiguration;
+import de.ids_mannheim.korap.exceptions.KustvaktException;
+import de.ids_mannheim.korap.resource.rewrite.KoralNode;
+import de.ids_mannheim.korap.resource.rewrite.RewriteTask;
+import de.ids_mannheim.korap.resource.rewrite.KoralNode.RewriteIdentifier;
+import de.ids_mannheim.korap.resource.rewrite.RewriteTask.IterableRewritePath;
+import de.ids_mannheim.korap.resources.Corpus;
+import de.ids_mannheim.korap.resources.KustvaktResource;
+import de.ids_mannheim.korap.user.User;
+
+/**
+ * @author hanl
+ * @date 03/07/2015
+ */
+public class CollectionConstraint implements RewriteTask.IterableRewritePath {
+
+
+
+    @Override
+    public JsonNode rewriteQuery (KoralNode node, KustvaktConfiguration config,
+            User user) {
+        if (node.get("@type").equals("koral:doc")) {
+            if (node.get("key").equals(Attributes.CORPUS_SIGLE)) {
+                String id = node.get("value");
+                // EM: MH checks if user has access to corpus
+//                KustvaktResource corpus = check(id, user);
+//                if (corpus == null)
+                    node.removeNode(new KoralNode.RewriteIdentifier(
+                            Attributes.CORPUS_SIGLE, id));
+            }
+        }
+        return node.rawNode();
+    }
+
+
+    /**
+     * @param id
+     * @param user
+     * @return boolean if true access granted
+     */
+//    @Deprecated
+//    private KustvaktResource check (String id, User user) {
+//        // todo: can be used to circumvent access control if public filter not applied
+//        if (user == null)
+//            return null;
+//
+//        KustvaktResource corpus;
+//        try {
+//            SecurityManager m = SecurityManager
+//                    .findbyId(id, user, Corpus.class);
+//            corpus = m.getResource();
+//        }
+//        catch (RuntimeException | KustvaktException e) {
+//            return null;
+//        }
+//        return corpus;
+//    }
+
+
+    @Override
+    public JsonNode rewriteResult (KoralNode node) {
+        return null;
+    }
+
+
+    @Override
+    public String path () {
+        return "collection";
+    }
+}
diff --git a/full/src/main/java/de/ids_mannheim/korap/web/controller/AdminController.java b/full/src/main/java/de/ids_mannheim/korap/web/controller/AdminController.java
index fb641d5..f85016a 100644
--- a/full/src/main/java/de/ids_mannheim/korap/web/controller/AdminController.java
+++ b/full/src/main/java/de/ids_mannheim/korap/web/controller/AdminController.java
@@ -1,10 +1,8 @@
 package de.ids_mannheim.korap.web.controller;
 
-import java.util.List;
 import java.util.Locale;
 
 import javax.ws.rs.GET;
-import javax.ws.rs.POST;
 import javax.ws.rs.Path;
 import javax.ws.rs.PathParam;
 import javax.ws.rs.Produces;
@@ -19,20 +17,13 @@
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Controller;
 
-import com.sun.jersey.api.core.HttpContext;
 import com.sun.jersey.spi.container.ResourceFilters;
 
 import de.ids_mannheim.korap.auditing.AuditRecord;
 import de.ids_mannheim.korap.exceptions.KustvaktException;
 import de.ids_mannheim.korap.exceptions.StatusCodes;
 import de.ids_mannheim.korap.interfaces.db.AuditingIface;
-import de.ids_mannheim.korap.resources.KustvaktResource;
-import de.ids_mannheim.korap.resources.Permissions;
-import de.ids_mannheim.korap.resources.ResourceFactory;
-import de.ids_mannheim.korap.security.PolicyCondition;
-import de.ids_mannheim.korap.security.ac.PolicyBuilder;
 import de.ids_mannheim.korap.server.KustvaktServer;
-import de.ids_mannheim.korap.user.User;
 import de.ids_mannheim.korap.utils.JsonUtils;
 import de.ids_mannheim.korap.utils.TimeUtils;
 import de.ids_mannheim.korap.web.CoreResponseHandler;
@@ -100,80 +91,81 @@
     }
 
 
-    @POST
-    @Path("createPolicies/{id}")
-    public Response addResourcePolicy (@PathParam("id") String persistentid,
-            @QueryParam("type") String type, @QueryParam("name") String name,
-            @QueryParam("description") String description,
-            @QueryParam("group") String group,
-            @QueryParam("perm") List<String> permissions,
-            @QueryParam("loc") String loc,
-            @QueryParam("expire") String duration, @Context HttpContext context)
-            throws KustvaktException {
-
-        if (type == null | type.isEmpty()) {
-            KustvaktException e = new KustvaktException(
-                    StatusCodes.MISSING_ARGUMENT,
-                    "The value of parameter type is missing.");
-            throw kustvaktResponseHandler.throwit(e);
-        }
-        else if (name == null | name.isEmpty()) {
-            KustvaktException e = new KustvaktException(
-                    StatusCodes.MISSING_ARGUMENT,
-                    "The value of parameter name is missing.");
-            throw kustvaktResponseHandler.throwit(e);
-        }
-        else if (description == null | description.isEmpty()) {
-            KustvaktException e = new KustvaktException(
-                    StatusCodes.MISSING_ARGUMENT,
-                    "The value of parameter description is missing.");
-            throw kustvaktResponseHandler.throwit(e);
-        }
-        else if (group == null | group.isEmpty()) {
-            KustvaktException e = new KustvaktException(
-                    StatusCodes.MISSING_ARGUMENT,
-                    "The value of parameter group is missing.");
-            throw kustvaktResponseHandler.throwit(e);
-        }
-        else if (permissions == null | permissions.isEmpty()) {
-            KustvaktException e = new KustvaktException(
-                    StatusCodes.MISSING_ARGUMENT,
-                    "The value of parameter permissions is missing.");
-            throw kustvaktResponseHandler.throwit(e);
-        }
-
-
-        try {
-            KustvaktResource resource = ResourceFactory.getResource(type);
-            resource.setPersistentID(persistentid);
-            resource.setDescription(description);
-            resource.setName(name);
-
-            Permissions.Permission[] p = Permissions
-                    .read(permissions.toArray(new String[0]));
-
-            User user = (User) context.getProperties().get("user");
-
-            PolicyBuilder pb = new PolicyBuilder(user)
-                    .setConditions(new PolicyCondition(group))
-                    .setResources(resource);
-
-            if (loc != null && !loc.isEmpty()){
-                pb.setLocation(loc);
-            }
-            if (duration != null && !duration.isEmpty()){
-                long now = TimeUtils.getNow().getMillis();
-                pb.setContext(now,
-                        now + TimeUtils.convertTimeToSeconds(duration));
-            }
-            pb.setPermissions(p);
-            pb.create();
-        }
-        catch (KustvaktException e) {
-            throw kustvaktResponseHandler.throwit(e);
-        }
-
-        return Response.ok().build();
-    }
+//    @Deprecated
+//    @POST
+//    @Path("createPolicies/{id}")
+//    public Response addResourcePolicy (@PathParam("id") String persistentid,
+//            @QueryParam("type") String type, @QueryParam("name") String name,
+//            @QueryParam("description") String description,
+//            @QueryParam("group") String group,
+//            @QueryParam("perm") List<String> permissions,
+//            @QueryParam("loc") String loc,
+//            @QueryParam("expire") String duration, @Context HttpContext context)
+//            throws KustvaktException {
+//
+//        if (type == null | type.isEmpty()) {
+//            KustvaktException e = new KustvaktException(
+//                    StatusCodes.MISSING_ARGUMENT,
+//                    "The value of parameter type is missing.");
+//            throw kustvaktResponseHandler.throwit(e);
+//        }
+//        else if (name == null | name.isEmpty()) {
+//            KustvaktException e = new KustvaktException(
+//                    StatusCodes.MISSING_ARGUMENT,
+//                    "The value of parameter name is missing.");
+//            throw kustvaktResponseHandler.throwit(e);
+//        }
+//        else if (description == null | description.isEmpty()) {
+//            KustvaktException e = new KustvaktException(
+//                    StatusCodes.MISSING_ARGUMENT,
+//                    "The value of parameter description is missing.");
+//            throw kustvaktResponseHandler.throwit(e);
+//        }
+//        else if (group == null | group.isEmpty()) {
+//            KustvaktException e = new KustvaktException(
+//                    StatusCodes.MISSING_ARGUMENT,
+//                    "The value of parameter group is missing.");
+//            throw kustvaktResponseHandler.throwit(e);
+//        }
+//        else if (permissions == null | permissions.isEmpty()) {
+//            KustvaktException e = new KustvaktException(
+//                    StatusCodes.MISSING_ARGUMENT,
+//                    "The value of parameter permissions is missing.");
+//            throw kustvaktResponseHandler.throwit(e);
+//        }
+//
+//
+//        try {
+//            KustvaktResource resource = ResourceFactory.getResource(type);
+//            resource.setPersistentID(persistentid);
+//            resource.setDescription(description);
+//            resource.setName(name);
+//
+//            Permissions.Permission[] p = Permissions
+//                    .read(permissions.toArray(new String[0]));
+//
+//            User user = (User) context.getProperties().get("user");
+//
+//            PolicyBuilder pb = new PolicyBuilder(user)
+//                    .setConditions(new PolicyCondition(group))
+//                    .setResources(resource);
+//
+//            if (loc != null && !loc.isEmpty()){
+//                pb.setLocation(loc);
+//            }
+//            if (duration != null && !duration.isEmpty()){
+//                long now = TimeUtils.getNow().getMillis();
+//                pb.setContext(now,
+//                        now + TimeUtils.convertTimeToSeconds(duration));
+//            }
+//            pb.setPermissions(p);
+//            pb.create();
+//        }
+//        catch (KustvaktException e) {
+//            throw kustvaktResponseHandler.throwit(e);
+//        }
+//
+//        return Response.ok().build();
+//    }
 
 }
diff --git a/full/src/main/java/de/ids_mannheim/korap/web/controller/OAuthController.java b/full/src/main/java/de/ids_mannheim/korap/web/controller/OAuthController.java
index a1cd54d..b43893b 100644
--- a/full/src/main/java/de/ids_mannheim/korap/web/controller/OAuthController.java
+++ b/full/src/main/java/de/ids_mannheim/korap/web/controller/OAuthController.java
@@ -44,7 +44,6 @@
 import de.ids_mannheim.korap.config.Attributes;
 import de.ids_mannheim.korap.config.AuthCodeInfo;
 import de.ids_mannheim.korap.config.AuthenticationMethod;
-import de.ids_mannheim.korap.config.AuthenticationScheme;
 import de.ids_mannheim.korap.config.BeansFactory;
 import de.ids_mannheim.korap.config.ClientInfo;
 import de.ids_mannheim.korap.config.KustvaktConfiguration;
@@ -91,8 +90,8 @@
     public OAuthController () {
         this.handler = new OAuth2Handler(BeansFactory.getKustvaktContext()
                 .getPersistenceClient());
-        this.controller = BeansFactory.getKustvaktContext()
-                .getAuthenticationManager();
+//        this.controller = BeansFactory.getKustvaktContext()
+//                .getAuthenticationManager();
         this.crypto = BeansFactory.getKustvaktContext().getEncryption();
         this.config = BeansFactory.getKustvaktContext().getConfiguration();
     }
diff --git a/full/src/main/java/de/ids_mannheim/korap/web/controller/SearchController.java b/full/src/main/java/de/ids_mannheim/korap/web/controller/SearchController.java
index 857dfbf..27b17e1 100644
--- a/full/src/main/java/de/ids_mannheim/korap/web/controller/SearchController.java
+++ b/full/src/main/java/de/ids_mannheim/korap/web/controller/SearchController.java
@@ -10,7 +10,6 @@
 import java.util.regex.Pattern;
 
 import javax.annotation.PostConstruct;
-import javax.ws.rs.DELETE;
 import javax.ws.rs.GET;
 import javax.ws.rs.POST;
 import javax.ws.rs.Path;
@@ -35,6 +34,7 @@
 import com.sun.jersey.core.util.MultivaluedMapImpl;
 import com.sun.jersey.spi.container.ResourceFilters;
 
+import de.ids_mannheim.korap.cache.ResourceCache;
 import de.ids_mannheim.korap.config.Attributes;
 import de.ids_mannheim.korap.config.FullConfiguration;
 import de.ids_mannheim.korap.config.KustvaktConfiguration;
@@ -49,9 +49,6 @@
 import de.ids_mannheim.korap.resources.ResourceFactory;
 import de.ids_mannheim.korap.resources.VirtualCollection;
 import de.ids_mannheim.korap.rewrite.FullRewriteHandler;
-import de.ids_mannheim.korap.security.ac.ResourceFinder;
-import de.ids_mannheim.korap.security.ac.ResourceHandler;
-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;
@@ -67,12 +64,12 @@
 import de.ids_mannheim.korap.web.filter.PiwikFilter;
 
 /**
- * EM: To Do: restructure codes regarding service and controller
- * layers
  * 
  * @author hanl, margaretha
  * @date 29/01/2014
- * @lastUpdate 06/2017
+ * @lastUpdate 01/2018
+ * 
+ * removed deprecated codes
  */
 @Controller
 @Path("/")
@@ -85,10 +82,10 @@
             LoggerFactory.getLogger(SearchController.class);
 
     @Autowired
-    CoreResponseHandler responseHandler;
+    private CoreResponseHandler responseHandler;
     @Autowired
     private SearchKrill searchKrill;
-    private ResourceHandler resourceHandler;
+    private ResourceCache resourceHandler;
     @Autowired
     private AuthenticationManagerIface controller;
     private ClientsHandler graphDBhandler;
@@ -99,7 +96,7 @@
 
 
     public SearchController () {
-        this.resourceHandler = new ResourceHandler();
+        this.resourceHandler = new ResourceCache();
         UriBuilder builder = UriBuilder.fromUri("http://10.0.10.13").port(9997);
         this.graphDBhandler = new ClientsHandler(builder.build());
     }
@@ -224,7 +221,6 @@
     }
 
 
-    /* EM: potentially an unused service! */
     /** Builds a json query serialization from the given parameters.
      * 
      * @param locale
@@ -519,65 +515,6 @@
 
     }
 
-    @Deprecated
-    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 responseHandler.throwit(e);
-        }
-        try {
-            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 responseHandler.throwit(StatusCodes.ILLEGAL_ARGUMENT,
-                        "Type parameter not supported", type);
-            }
-        }
-        catch (KustvaktException e) {
-            throw responseHandler.throwit(e);
-        }
-    }
 
     /**
      * @param context
@@ -630,298 +567,6 @@
     }
 
 
-    // EM: this handles layer id containing a slash. 
-    // Probably better to restrict the id not to contain any slash instead.
-    @Deprecated
-    @POST
-    @Path("{type}/{id}/{child}")
-    public Response updateResource (@Context SecurityContext context,
-            @Context Locale locale, @PathParam("type") String type,
-            @PathParam("id") String id, @PathParam("child") String child,
-            @QueryParam("name") String name,
-            @QueryParam("description") String description) {
-        return updateResource(context, locale, type,
-                StringUtils.joinResources(id, child), name, description);
-    }
-
-
-    @Deprecated
-    @POST
-    @Path("{type}/{id}")
-    public Response updateResource (@Context SecurityContext context,
-            @Context Locale locale, @PathParam("type") String type,
-            @PathParam("id") String id, @QueryParam("name") String name,
-            @QueryParam("description") String description) {
-        TokenContext ctx = (TokenContext) context.getUserPrincipal();
-        User user;
-        try {
-            user = controller.getUser(ctx.getUsername());
-            KustvaktResource resource = this.resourceHandler.findbyStrId(id,
-                    user, ResourceFactory.getResourceClass(type));
-
-            if (name != null && !name.isEmpty()) {
-                if (description == null) {
-                    if (name.equals(resource.getName())) {
-                        throw new KustvaktException(StatusCodes.NOTHING_CHANGED,
-                                "No change has found.");
-                    }
-                    resource.setName(name);
-                }
-                else if (name.equals(resource.getName())
-                        && description.equals(resource.getDescription())) {
-                    throw new KustvaktException(StatusCodes.NOTHING_CHANGED,
-                            "No change has found.");
-                }
-                else {
-                    resource.setName(name);
-                    resource.setDescription(description);
-                }
-            }
-            else if (description != null && !description.isEmpty()) {
-                resource.setDescription(description);
-            }
-            else {
-                throw new KustvaktException(StatusCodes.NOTHING_CHANGED,
-                        "The given resource name and description are the same as already stored.");
-            }
-
-
-            this.resourceHandler.updateResources(user, resource);
-        }
-        catch (KustvaktException e) {
-            jlog.error("Exception encountered: {}", e.string());
-            throw responseHandler.throwit(e);
-        }
-        return Response.ok().build();
-    }
-
-    @Deprecated
-    // todo: change or deprecate
-    @POST
-    @Path("nv/{type}")
-    public Response storeResource (@Context SecurityContext context,
-            @Context Locale locale, @PathParam("type") String type,
-            @QueryParam("name") String name,
-            @QueryParam("description") String description,
-            // deprecate -> if you want to store a resource based on another,
-            // build the query first yourself or via a function
-            @QueryParam("ref") String reference,
-            @QueryParam("cache") Boolean cache,
-            @QueryParam("query") String query) {
-        TokenContext ctx = (TokenContext) context.getUserPrincipal();
-        cache = cache != null ? cache : false;
-        type = StringUtils.normalize(type);
-        reference = StringUtils.decodeHTML(reference);
-        Map vals = new HashMap();
-        User user;
-        Class ctype;
-        try {
-            ctype = ResourceFactory.getResourceClass(type);
-            user = controller.getUser(ctx.getUsername());
-        }
-        catch (KustvaktException e) {
-            jlog.error("Exception encountered: {}", e.string());
-            throw responseHandler.throwit(e);
-        }
-        if (VirtualCollection.class.equals(ctype)) {
-            VirtualCollection cachetmp, collection;
-
-            JsonNode base = null;
-            if (reference != null && !reference.equals("null")) {
-                try {
-                    base = resourceHandler.findbyStrId(reference, user,
-                            VirtualCollection.class).getData();
-                }
-                catch (KustvaktException e) {
-                    throw responseHandler.throwit(e);
-                }
-
-            }
-            else if (query != null)
-                try {
-                    base = JsonUtils.readTree(query);
-                }
-                catch (KustvaktException e) {
-                    responseHandler.throwit(e);
-                }
-            else
-                // todo: throw exception response for no resource to save!
-                return null;
-
-            KoralCollectionQueryBuilder cquery =
-                    new KoralCollectionQueryBuilder();
-            cquery.setBaseQuery(base);
-
-            try {
-                cachetmp = ResourceFactory.getCachedCollection(cquery.toJSON());
-
-                // see if collection was cached!
-                VirtualCollection tmp = resourceHandler
-                        .getCache(cachetmp.getId(), VirtualCollection.class);
-                // if not cached, fill with stats values
-                if (tmp == null) {
-                    String stats = searchKrill.getStatistics(cquery.toJSON());
-                    cachetmp.setStats(
-                            JsonUtils.convertToClass(stats, Map.class));
-                }
-
-                if (!cache) {
-                    collection = ResourceFactory.getPermanentCollection(
-                            cachetmp, name, description);
-                    vals = collection.toMap();
-                    resourceHandler.storeResources(user, collection);
-                }
-                else {
-                    resourceHandler.cache(cachetmp);
-                    vals = cachetmp.toMap();
-                }
-
-            }
-            catch (KustvaktException e) {
-                throw responseHandler.throwit(e);
-            }
-        }
-        try {
-            return Response.ok(JsonUtils.toJSON(vals)).build();
-        }
-        catch (KustvaktException e) {
-            throw responseHandler.throwit(e);
-        }
-    }
-
-
-    /**
-     * EM: store a virtual collection in resource_store, but
-     * not in the policy_store table as well.
-     * 
-     * Retrieve cached entry first and then store collection
-     * 
-     * @param context
-     * @param locale
-     * @param query
-     * @return
-     * @throws KustvaktException
-     */
-    @Deprecated
-    @POST
-    @Path("{type}")
-    public Response storeResource (@Context SecurityContext context,
-            @Context Locale locale, @PathParam("type") String type,
-            @QueryParam("filter") Boolean filter,
-            @QueryParam("name") String name,
-            @QueryParam("description") String description,
-            @QueryParam("ref") String reference,
-            @QueryParam("cache") Boolean cache,
-            @QueryParam("query") String query) throws KustvaktException {
-        TokenContext ctx = (TokenContext) context.getUserPrincipal();
-        filter = filter != null ? filter : false;
-        cache = cache != null ? cache : false;
-        type = StringUtils.normalize(type);
-        reference = StringUtils.decodeHTML(reference);
-        Map vals = new HashMap();
-        User user;
-        Class<KustvaktResource> ctype;
-        try {
-            ctype = ResourceFactory.getResourceClass(type);
-
-            user = controller.getUser(ctx.getUsername());
-        }
-        catch (KustvaktException e) {
-            jlog.error("Exception encountered: {}", e.string());
-            throw responseHandler.throwit(e);
-        }
-
-        if (VirtualCollection.class.equals(ctype)) {
-            VirtualCollection cachetmp, collection;
-
-            KoralCollectionQueryBuilder cquery =
-                    new KoralCollectionQueryBuilder();
-            if (reference != null && !reference.equals("null")) {
-                try {
-                    cquery.setBaseQuery(resourceHandler.findbyStrId(reference,
-                            user, VirtualCollection.class).getData());
-
-                }
-                catch (KustvaktException e) {
-                    throw responseHandler.throwit(e);
-                }
-            }
-            if (query != null && !query.isEmpty()) cquery.with(query);
-
-            cachetmp = ResourceFactory.getCachedCollection(cquery.toJSON());
-
-            // see if vc was cached!
-            VirtualCollection tmp = resourceHandler.getCache(cachetmp.getId(),
-                    VirtualCollection.class);
-
-            // if not cached, fill with stats values
-            if (tmp == null) {
-                String stats = searchKrill.getStatistics(cquery.toJSON());
-                cachetmp.setStats(JsonUtils.convertToClass(stats, Map.class));
-                if (query != null && !query.isEmpty())
-                    cachetmp.setFields(cquery.toJSON());
-            }
-
-            if (!cache && !User.UserFactory.isDemo(ctx.getUsername())) {
-                collection = ResourceFactory.getPermanentCollection(cachetmp,
-                        name, description);
-                vals = collection.toMap();
-                try {
-                    resourceHandler.storeResources(user, collection);
-                }
-                catch (KustvaktException e) {
-                    jlog.error("Exception encountered: {}", e.string());
-                    throw responseHandler.throwit(e);
-                }
-            }
-            else {
-                resourceHandler.cache(cachetmp);
-                vals = cachetmp.toMap();
-            }
-        }
-        else {
-            throw responseHandler.throwit(
-                    new KustvaktException(StatusCodes.UNSUPPORTED_RESOURCE,
-                            "Unsupported operation for the given resource type.",
-                            type));
-        }
-        return Response.ok(JsonUtils.toJSON(vals)).build();
-    }
-
-
-    @DELETE
-    @Path("{type}/{id}/{child}")
-    public Response deleteResourceChild (@Context SecurityContext context,
-            @Context Locale locale, @PathParam("type") String type,
-            @PathParam("id") String id, @PathParam("child") String child) {
-        return deleteResource(context, locale, type,
-                StringUtils.joinResources(id, child));
-    }
-
-    @Deprecated
-    @DELETE
-    @Path("{type}/{id}")
-    public Response deleteResource (@Context SecurityContext context,
-            @Context Locale locale, @PathParam("type") String type,
-            @PathParam("id") String id) {
-        TokenContext ctx = (TokenContext) context.getUserPrincipal();
-        type = StringUtils.normalizeHTML(type);
-        id = StringUtils.decodeHTML(id);
-        try {
-            User user = controller.getUser(ctx.getUsername());
-            KustvaktResource r = ResourceFactory.getResource(type);
-            r.setPersistentID(id);
-            // todo: eliminate the need to find the resource first!
-            resourceHandler.deleteResources(user, r);
-        }
-        catch (KustvaktException e) {
-            jlog.error("Exception encountered: {}", e.string());
-            throw responseHandler.throwit(e);
-        }
-
-        return Response.ok().build();
-    }
-
     @GET
     @Path("/corpus/{corpusId}/{docId}/{textId}/{matchId}/matchInfo")
     public Response getMatchInfo (@Context SecurityContext ctx,
@@ -1026,59 +671,4 @@
         return Response.ok(results).build();
     }
 
-
-    // todo:?!
-    @POST
-    @Path("match/{id}")
-    @Deprecated
-    public Response save (@PathParam("{id}") String id,
-            @QueryParam("d") String description,
-            @Context SecurityContext context) {
-        TokenContext ctx = (TokenContext) context.getUserPrincipal();
-        // save match for user and later retrieval!
-
-        // KustvaktResource match = new QueryMatch(id);
-        // match.setDescription(description);
-        // match.setCreated(TimeUtils.getNow().getMillis());
-        // try {
-        // this.resourceHandler.storeResources(controller.getUser(ctx), match);
-        // } catch (KustvaktException | NotAuthorizedException e) {
-        // throw MappedHTTPResponse.throwit(e);
-        // }
-
-        return Response.ok().build();
-    }
-
-
-    @GET
-    @Path("matches")
-    @Deprecated
-    public Response get (@Context SecurityContext context) {
-        TokenContext ctx = (TokenContext) context.getUserPrincipal();
-        // todo save match for user and later retrieval!
-        // todo: retrieve matches in range! --choices: date, document, id
-        // (matchid)
-        return Response.ok().build();
-    }
-
-
-    @DELETE
-    @Path("match/{id}")
-    @Deprecated
-    public Response remove (@PathParam("{id}") String id,
-            @Context SecurityContext context) {
-        TokenContext ctx = (TokenContext) context.getUserPrincipal();
-        // save match for user and later retrieval!
-        try {
-            this.resourceHandler.deleteResources(
-                    this.controller.getUser(ctx.getUsername()), id);
-        }
-        catch (KustvaktException e) {
-            jlog.error("Exception encountered: {}", e.string());
-            throw responseHandler.throwit(e);
-        }
-
-        return Response.ok().build();
-    }
-
 }
diff --git a/full/src/main/resources/default-config.xml b/full/src/main/resources/default-config.xml
index 5d3f9e9..594084a 100644
--- a/full/src/main/resources/default-config.xml
+++ b/full/src/main/resources/default-config.xml
@@ -199,10 +199,6 @@
 		<constructor-arg ref="kustvakt_db" />
 	</bean>
 
-	<bean id="kustvakt_policies" class="de.ids_mannheim.korap.security.ac.PolicyDao">
-		<constructor-arg ref="kustvakt_db" />
-	</bean>
-
 	<bean name="kustvakt_encryption"
 		class="de.ids_mannheim.korap.interfaces.defaults.KustvaktEncryption">
 		<constructor-arg ref="kustvakt_config" />
diff --git a/full/src/test/java/de/ids_mannheim/korap/config/ClassLoaderTest.java b/full/src/test/java/de/ids_mannheim/korap/config/ClassLoaderTest.java
index e56d309..022913a 100644
--- a/full/src/test/java/de/ids_mannheim/korap/config/ClassLoaderTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/config/ClassLoaderTest.java
@@ -26,13 +26,14 @@
     }
 
 
-    @Test
-    public void testDefaultCreation2ThrowsNoException () {
-        AuthenticationManagerIface iface = helper().getContext()
-                .getAuthenticationManager();
-        assertNotNull(iface);
-        assertTrue(iface instanceof KustvaktAuthenticationManager);
-    }
+//    @Test
+//    @Deprecated
+//    public void testDefaultCreation2ThrowsNoException () {
+//        AuthenticationManagerIface iface = helper().getContext()
+//                .getAuthenticationManager();
+//        assertNotNull(iface);
+//        assertTrue(iface instanceof KustvaktAuthenticationManager);
+//    }
 
 
     @Test
diff --git a/full/src/test/java/de/ids_mannheim/korap/resource/rewrite/CollectionRewriteTest.java b/full/src/test/java/de/ids_mannheim/korap/resource/rewrite/CollectionRewriteTest.java
index 38cc04e..48a5e7d 100644
--- a/full/src/test/java/de/ids_mannheim/korap/resource/rewrite/CollectionRewriteTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/resource/rewrite/CollectionRewriteTest.java
@@ -3,9 +3,6 @@
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertNotNull;
 
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
 import org.junit.Test;
 
 import com.fasterxml.jackson.databind.JsonNode;
@@ -15,6 +12,7 @@
 import de.ids_mannheim.korap.config.TestVariables;
 import de.ids_mannheim.korap.exceptions.KustvaktException;
 import de.ids_mannheim.korap.query.serialize.QuerySerializer;
+import de.ids_mannheim.korap.rewrite.CollectionConstraint;
 import de.ids_mannheim.korap.rewrite.CollectionRewrite;
 import de.ids_mannheim.korap.user.User;
 import de.ids_mannheim.korap.utils.JsonUtils;
@@ -35,19 +33,6 @@
     }
 
 
-    @Deprecated
-    @Test
-    public void test2 () {
-        Pattern p = Pattern.compile("([\\.\\w]+)\\((.+)\\)");
-        String cl = de.ids_mannheim.korap.security.ac.SecurityManager.class
-                .getCanonicalName();
-        Matcher m = p.matcher(cl);
-        while (m.find())
-            System.out.println("group 1 " + m.group(1));
-
-    }
-
-
     @Test
     public void testCollectionNodeRemoveCorpusIdNoErrors ()
             throws KustvaktException {
diff --git a/full/src/test/java/de/ids_mannheim/korap/security/PolicyDaoTest.java b/full/src/test/java/de/ids_mannheim/korap/security/PolicyDaoTest.java
deleted file mode 100644
index 6f7136b..0000000
--- a/full/src/test/java/de/ids_mannheim/korap/security/PolicyDaoTest.java
+++ /dev/null
@@ -1,253 +0,0 @@
-package de.ids_mannheim.korap.security;
-
-import static org.junit.Assert.assertNotEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-
-import java.util.Collection;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-
-import org.junit.Ignore;
-import org.junit.Test;
-
-import de.ids_mannheim.korap.config.Attributes;
-import de.ids_mannheim.korap.config.BeanConfigTest;
-import de.ids_mannheim.korap.exceptions.KustvaktException;
-import de.ids_mannheim.korap.interfaces.db.PolicyHandlerIface;
-import de.ids_mannheim.korap.resources.Corpus;
-import de.ids_mannheim.korap.resources.KustvaktResource;
-import de.ids_mannheim.korap.resources.Permissions;
-import de.ids_mannheim.korap.resources.VirtualCollection;
-import de.ids_mannheim.korap.security.ac.PolicyBuilder;
-import de.ids_mannheim.korap.user.User;
-import edu.emory.mathcs.backport.java.util.Arrays;
-
-/** EM: needs reimplementation
- * 
- * @author hanl
- * @date 09/02/2016
- */
-@Ignore
-public class PolicyDaoTest extends BeanConfigTest {
-
-
-    @Override
-    public void initMethod () throws KustvaktException {
-        helper().setupAccount();
-//        helper().runBootInterfaces();
-        helper().setupResource(new Corpus("WPD_1"));
-    }
-
-
-    @Test
-    public void testPoliciesGet () throws KustvaktException {
-        User user = helper().getUser();
-        SecurityPolicy policy = new SecurityPolicy();
-        policy.addNewCondition(new PolicyCondition("test_1"));
-        policy.setCreator(user.getId());
-        policy.setTarget(new Corpus("WPD_1"));
-        policy.addPermission(Permissions.Permission.READ);
-
-        PolicyHandlerIface dao = helper().getContext().getPolicyDbProvider();
-        assertTrue(dao.createPolicy(policy, user) > 0);
-        dao.getPolicies("WPD_1", user, Permissions.Permission.READ.toByte());
-    }
-
-
-    @Test
-    public void testPolicyCreate () throws KustvaktException {
-        User user = helper().getUser();
-        SecurityPolicy policy = new SecurityPolicy();
-        policy.addNewCondition(new PolicyCondition("test_1"));
-        policy.setCreator(user.getId());
-        policy.setTarget(new Corpus("WPD_1"));
-        policy.addPermission(Permissions.Permission.READ);
-
-        PolicyHandlerIface dao = helper().getContext().getPolicyDbProvider();
-
-        assertTrue(dao.createPolicy(policy, user) > 0);
-        assertTrue(dao.deleteResourcePolicies("WPD_1", user) > 0);
-    }
-
-
-    @Test
-    public void testMappingConditions () {
-
-    }
-
-
-    @Test
-    public void failAddToConditionEqual () throws KustvaktException {
-        User user = helper().getUser();
-        SecurityPolicy policy = new SecurityPolicy();
-        policy.addNewCondition(new PolicyCondition("test_1"));
-        policy.setCreator(user.getId());
-        policy.setTarget(new Corpus("WPD_1"));
-        policy.addPermission(Permissions.Permission.READ);
-
-        PolicyHandlerIface dao = helper().getContext().getPolicyDbProvider();
-
-        assertTrue(dao.createPolicy(policy, user) > 0);
-
-        dao.addToCondition(user.getUsername(), new PolicyCondition("test_1"),
-                true);
-        assertTrue(dao.deleteResourcePolicies("WPD_1", user) > 0);
-
-    }
-
-
-    @Test
-    public void failAddToConditionUnEqual () throws KustvaktException {
-        User user = helper().getUser();
-        SecurityPolicy policy = new SecurityPolicy();
-        policy.addNewCondition(new PolicyCondition("test_1"));
-        policy.setCreator(user.getId());
-        policy.setTarget(new Corpus("WPD_1"));
-        policy.addPermission(Permissions.Permission.READ);
-
-        PolicyHandlerIface dao = helper().getContext().getPolicyDbProvider();
-        assertTrue(dao.createPolicy(policy, user) > 0);
-
-        dao.addToCondition(user.getUsername(), new PolicyCondition("test_1"),
-                false);
-
-        assertTrue(dao.deleteResourcePolicies("WPD_1", user) > 0);
-
-    }
-
-
-    @Test
-    public void removeUserFromCondition () throws KustvaktException {
-        User user = helper().getUser();
-        PolicyHandlerIface dao = helper().getContext().getPolicyDbProvider();
-
-        SecurityPolicy policy = new SecurityPolicy();
-        policy.addNewCondition(new PolicyCondition("test_1"));
-        policy.setCreator(user.getId());
-        policy.setTarget(new Corpus("WPD_1"));
-        policy.addPermission(Permissions.Permission.READ);
-
-        assertTrue(dao.createPolicy(policy, user) > 0);
-        dao.removeFromCondition(
-                Arrays.asList(new String[] { user.getUsername() }),
-                new PolicyCondition("test_1"));
-        assertTrue(dao.deleteResourcePolicies("WPD_1", user) > 0);
-    }
-
-
-    @Test
-    public void testPolicyHierarchySelfSameType () throws KustvaktException {
-        String res = "WPD_child";
-        User user = helper().getUser();
-        Corpus c = new Corpus(res);
-        c.setParentID("WPD_1");
-        helper().setupResource(c);
-        PolicyHandlerIface dao = helper().getContext().getPolicyDbProvider();
-
-        List[] pol = dao.getPolicies("WPD_child", user,
-                Permissions.Permission.READ.toByte());
-        assertNotNull(pol);
-        assertNotNull(pol[0]);
-        assertTrue(pol[0].get(0) instanceof SecurityPolicy.OwnerPolicy);
-        assertTrue(pol[1].get(0) instanceof SecurityPolicy.OwnerPolicy);
-
-        helper().dropResource(res);
-    }
-
-
-    @Test
-    @Ignore
-    public void testPolicyHierarchySelfDifferentType ()
-            throws KustvaktException {
-        String res = "WPD_child";
-        User user = helper().getUser();
-        VirtualCollection c = new VirtualCollection(res);
-        c.setParentID(helper().getResource("WPD_1").getPersistentID());
-        helper().setupResource(c);
-
-        PolicyHandlerIface dao = helper().getContext().getPolicyDbProvider();
-
-        List[] pol = dao.getPolicies("WPD_child", user,
-                Permissions.Permission.READ.toByte());
-        assertNotNull(pol);
-        assertNotNull(pol[0]);
-        assertTrue(pol[0].get(0) instanceof SecurityPolicy.OwnerPolicy);
-        assertTrue(pol[1].get(0) instanceof SecurityPolicy.OwnerPolicy);
-        helper().dropResource(res);
-    }
-
-
-    @Test
-    public void testPolicyHierarchyPublic () {
-
-    }
-
-
-    @Test
-    @Deprecated
-    @Ignore
-    public void testPoliciesPublic () {
-        PolicyHandlerIface dao = helper().getContext().getPolicyDbProvider();
-        Collection<SecurityPolicy> policies = dao.getPolicies(
-                new PolicyCondition("public"), Corpus.class,
-                Permissions.Permission.READ.toByte());
-        assertNotEquals(0, policies.size());
-    }
-
-
-    @Test
-    @Ignore
-    public void testPoliciesPublicGeneric () {
-        PolicyHandlerIface dao = helper().getContext().getPolicyDbProvider();
-        Collection<SecurityPolicy> policies = dao.getPolicies(
-                new PolicyCondition("public"), KustvaktResource.class,
-                Permissions.Permission.READ.toByte());
-        assertNotEquals(0, policies.size());
-    }
-
-
-    @Test
-    public void searchResourcePoliciesPublic () throws KustvaktException {
-        User user = helper().getUser();
-        new PolicyBuilder(user).setConditions(new PolicyCondition("public"))
-                .setPermissions(Permissions.Permission.READ)
-                .setResources(new VirtualCollection("new_corpus")).create();
-
-        PolicyHandlerIface dao = helper().getContext().getPolicyDbProvider();
-        List<SecurityPolicy> list = dao.getPolicies(new PolicyCondition(
-                Attributes.PUBLIC_GROUP), VirtualCollection.class,
-                Permissions.Permission.READ.toByte());
-        assertNotEquals(0, list.size());
-        Set<String> ids = new HashSet<>();
-        for (SecurityPolicy p : list)
-            ids.add(p.getTarget());
-        assertNotEquals(0, ids.size());
-    }
-
-
-    @Test
-    public void testPolicyHierarchyRestricted () {
-
-    }
-
-
-    @Test
-    public void testSelfPolicies () {
-
-    }
-
-
-    @Test
-    public void testPublicPolicies () {
-
-    }
-
-
-    @Test
-    public void testConditions () {
-
-    }
-
-}
diff --git a/full/src/test/java/de/ids_mannheim/korap/security/ResourceFinderTest.java b/full/src/test/java/de/ids_mannheim/korap/security/ResourceFinderTest.java
deleted file mode 100644
index 47f7c33..0000000
--- a/full/src/test/java/de/ids_mannheim/korap/security/ResourceFinderTest.java
+++ /dev/null
@@ -1,62 +0,0 @@
-package de.ids_mannheim.korap.security;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotEquals;
-
-import java.util.Set;
-
-import org.junit.Ignore;
-import org.junit.Test;
-
-import de.ids_mannheim.korap.config.BeanConfigTest;
-import de.ids_mannheim.korap.exceptions.KustvaktException;
-import de.ids_mannheim.korap.resources.Corpus;
-import de.ids_mannheim.korap.resources.VirtualCollection;
-import de.ids_mannheim.korap.security.ac.ResourceFinder;
-
-/**
- * @author hanl
- * @date 06/02/2016
- */
-@Deprecated
-@Ignore
-public class ResourceFinderTest extends BeanConfigTest {
-
-    @Test
-    public void searchResources () throws KustvaktException {
-        Set<VirtualCollection> resources = ResourceFinder
-                .searchPublic(VirtualCollection.class);
-        assertFalse(resources.isEmpty());
-        assertEquals(1, resources.size());
-    }
-
-
-    @Test
-    public void searchResourcesDemo () throws KustvaktException {
-        Set<Corpus> resources = ResourceFinder.searchPublic(Corpus.class);
-        assertNotEquals(0, resources.size());
-    }
-
-
-    @Test
-    @Deprecated
-    public void testResourcesDemoFiltered () throws KustvaktException {
-        Set<Corpus> resources = ResourceFinder.searchPublicFiltered(
-                Corpus.class, "WPD13");
-        assertNotEquals(0, resources.size());
-        assertEquals(1, resources.size());
-
-        resources = ResourceFinder.searchPublicFiltered(Corpus.class, "WPD13",
-                "GOE");
-        assertNotEquals(0, resources.size());
-        assertEquals(2, resources.size());
-    }
-
-
-    @Override
-    public void initMethod () throws KustvaktException {
-        helper().setupAccount();
-//        helper().runBootInterfaces();
-    }
-}
diff --git a/full/src/test/java/de/ids_mannheim/korap/security/ResourcesTest.java b/full/src/test/java/de/ids_mannheim/korap/security/ResourcesTest.java
deleted file mode 100644
index 1794109..0000000
--- a/full/src/test/java/de/ids_mannheim/korap/security/ResourcesTest.java
+++ /dev/null
@@ -1,143 +0,0 @@
-package de.ids_mannheim.korap.security;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-
-import java.util.Set;
-
-import org.hamcrest.core.StringStartsWith;
-import org.joda.time.DateTime;
-import org.junit.Ignore;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.ExpectedException;
-
-import de.ids_mannheim.korap.config.BeanConfigTest;
-import de.ids_mannheim.korap.config.ContextHolder;
-import de.ids_mannheim.korap.config.KustvaktConfiguration;
-import de.ids_mannheim.korap.exceptions.KustvaktException;
-import de.ids_mannheim.korap.interfaces.db.EntityHandlerIface;
-import de.ids_mannheim.korap.resources.Corpus;
-import de.ids_mannheim.korap.resources.Foundry;
-import de.ids_mannheim.korap.resources.KustvaktResource;
-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.User;
-import de.ids_mannheim.korap.utils.TimeUtils;
-
-/**
- * @author hanl, margaretha
- * @date 20/11/2015
- */
-@Deprecated
-@Ignore
-// todo: run functions without data to check for nullpointers!
-public class ResourcesTest extends BeanConfigTest {
-
-    private static Corpus c1;
-
-    @Rule
-    public ExpectedException exception = ExpectedException.none();
-
-    @Test
-    public void testCreate () throws KustvaktException {
-        ResourceHandler h = new ResourceHandler();
-        Corpus ncorps = new Corpus("new_wiki");
-        h.storeResources(helper().getUser(), ncorps);
-    }
-
-
-    @Test
-    public void testGet () throws KustvaktException {
-        DateTime beg = new DateTime();
-        ResourceHandler h = new ResourceHandler();
-        Corpus c = h.findbyStrId(c1.getPersistentID(), helper().getUser(),
-                Corpus.class);
-        float end = TimeUtils.floating(beg, new DateTime());
-        System.out.println("END ----------------- : " + end);
-        assertNotNull(c);
-    }
-
-
-    @Test(expected = KustvaktException.class)
-    public void testGetthrowsUnauthorizedException () throws KustvaktException {
-        DateTime beg = new DateTime();
-        ResourceHandler h = new ResourceHandler();
-        Corpus c = h.findbyStrId(c1.getPersistentID(),
-                User.UserFactory.getDemoUser(), Corpus.class);
-        float end = TimeUtils.floating(beg, new DateTime());
-        System.out.println("END ----------------- : " + end);
-        assertNotNull(c);
-    }
-
-
-    // in case of null, should not return nullpointer!
-    @Test(expected = KustvaktException.class)
-    @Ignore
-    public void testCollectionGet () throws KustvaktException {
-        //todo: do use test user!
-        User user = User.UserFactory
-                .toUser(KustvaktConfiguration.KUSTVAKT_USER);
-        EntityHandlerIface ice = helper()
-                .getBean(ContextHolder.KUSTVAKT_USERDB);
-        User test = ice.getAccount(user.getUsername());
-        assertNotNull(test);
-        Set<KustvaktResource> resources = ResourceFinder.search(user,
-                ResourceFactory.getResourceClass("collection"));
-
-        assertFalse(resources.isEmpty());
-        KustvaktResource r = (KustvaktResource) resources.toArray()[0];
-
-        assertNotNull(r);
-        ResourceHandler h = new ResourceHandler();
-        h.findbyStrId(r.getPersistentID(), user, VirtualCollection.class);
-    }
-
-
-    // securitymanager does not allow for anonymous retrieval, only resourcefinder!
-    @Test 
-    @Ignore
-    public void getResource () throws KustvaktException {
-        
-        exception.expect(KustvaktException.class);
-        exception.expectMessage(StringStartsWith.startsWith("Permission denied"));
-        
-        User user = User.UserFactory.getDemoUser();
-        SecurityManager m = SecurityManager.findbyId(2, user,
-                Permissions.Permission.READ);
-        m.getResource();
-    }
-
-
-    @Test
-    @Deprecated
-    @Ignore
-    public void getDemoResources () throws KustvaktException {
-        Set s = ResourceFinder.searchPublic(Corpus.class);
-        assertEquals(2, s.size());
-        s = ResourceFinder.searchPublic(Foundry.class);
-        assertEquals(10, s.size());
-    }
-
-
-    @Test
-    @Deprecated
-    @Ignore
-    public void getDemoResourceFiltered () throws KustvaktException {
-        Set s = ResourceFinder.searchPublicFiltered(Corpus.class, "WPD13");
-        assertEquals(1, s.size());
-    }
-
-
-    @Override
-    public void initMethod () throws KustvaktException {
-        helper().setupAccount();
-        c1 = new Corpus("WPD_test");
-        helper().setupResource(c1);
-    }
-}
diff --git a/full/src/test/java/de/ids_mannheim/korap/security/auth/KustvaktAuthenticationManagerTest.java b/full/src/test/java/de/ids_mannheim/korap/security/auth/KustvaktAuthenticationManagerTest.java
index 5d4a59d..efdb76e 100644
--- a/full/src/test/java/de/ids_mannheim/korap/security/auth/KustvaktAuthenticationManagerTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/security/auth/KustvaktAuthenticationManagerTest.java
@@ -6,6 +6,7 @@
 import org.junit.After;
 import org.junit.Ignore;
 import org.junit.Test;
+import org.springframework.beans.factory.annotation.Autowired;
 
 import de.ids_mannheim.korap.config.Attributes;
 import de.ids_mannheim.korap.config.BeanConfigTest;
@@ -28,16 +29,17 @@
 @Ignore
 public class KustvaktAuthenticationManagerTest extends BeanConfigTest {
 
+    @Autowired
+    private AuthenticationManagerIface authManager;
+    
     @After
     public void after () {
         try {
-            User user = helper()
-                    .getContext()
-                    .getAuthenticationManager()
+            User user = authManager
                     .getUser(
                             (String) KustvaktConfiguration.KUSTVAKT_USER
                                     .get(Attributes.USERNAME));
-            helper().getContext().getAuthenticationManager()
+            authManager
                     .deleteAccount(user);
         }
         catch (KustvaktException e) {}
@@ -47,7 +49,7 @@
     @Test
     @Ignore
     public void testCreateUser () throws KustvaktException {
-        User user = helper().getContext().getAuthenticationManager()
+        User user = authManager
                 .createUserAccount(KustvaktConfiguration.KUSTVAKT_USER, false);
 
         EntityHandlerIface dao = helper().getContext().getUserDBHandler();
@@ -61,8 +63,8 @@
     public void testBatchStore () {
         int i = 6;
 
-        AuthenticationManagerIface manager = helper().getContext()
-                .getAuthenticationManager();
+//        AuthenticationManagerIface manager = helper().getContext()
+//                .getAuthenticationManager();
         for (int ix = 0; ix < i; ix++) {}
 
     }
@@ -72,14 +74,12 @@
     @Ignore
     public void testUserdetailsGet () throws KustvaktException {
         testCreateUser();
-        AuthenticationManagerIface manager = helper().getContext()
-                .getAuthenticationManager();
 
-        User user = manager
+        User user = authManager
                 .getUser((String) KustvaktConfiguration.KUSTVAKT_USER
                         .get(Attributes.USERNAME));
 
-        Userdata data = manager.getUserData(user, UserDetails.class);
+        Userdata data = authManager.getUserData(user, UserDetails.class);
         assertNotNull(data);
     }
 
@@ -88,14 +88,12 @@
     @Ignore
     public void testUsersettingsGet () throws KustvaktException {
         testCreateUser();
-        AuthenticationManagerIface manager = helper().getContext()
-                .getAuthenticationManager();
 
-        User user = manager
+        User user = authManager
                 .getUser((String) KustvaktConfiguration.KUSTVAKT_USER
                         .get(Attributes.USERNAME));
 
-        Userdata data = manager.getUserData(user, UserSettings.class);
+        Userdata data = authManager.getUserData(user, UserSettings.class);
         assertNotNull(data);
     }
 
@@ -103,30 +101,24 @@
     @Test(expected = KustvaktException.class)
     public void testUserDetailsGetNonExistent () throws KustvaktException {
         testCreateUser();
-        AuthenticationManagerIface manager = helper().getContext()
-                .getAuthenticationManager();
 
         User user = new KorAPUser(10, "random");
-        manager.getUserData(user, UserDetails.class);
+        authManager.getUserData(user, UserDetails.class);
     }
 
 
     @Test(expected = KustvaktException.class)
     public void testUserSettingsGetNonExistent () throws KustvaktException {
         testCreateUser();
-        AuthenticationManagerIface manager = helper().getContext()
-                .getAuthenticationManager();
 
         User user = new KorAPUser(10, "random");
-        manager.getUserData(user, UserSettings.class);
+        authManager.getUserData(user, UserSettings.class);
     }
 
     @Test
     @Ignore
     public void testUserUpdate() throws KustvaktException {
         testCreateUser();
-        AuthenticationManagerIface manager = helper().getContext()
-                .getAuthenticationManager();
         // todo:
     }
 
diff --git a/full/src/test/java/de/ids_mannheim/korap/web/controller/SearchControllerTest.java b/full/src/test/java/de/ids_mannheim/korap/web/controller/SearchControllerTest.java
index b27e1bf..5814029 100644
--- a/full/src/test/java/de/ids_mannheim/korap/web/controller/SearchControllerTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/web/controller/SearchControllerTest.java
@@ -5,9 +5,6 @@
 import static org.junit.Assert.assertNotNull;
 import static org.junit.Assert.assertTrue;
 
-import java.util.Iterator;
-import java.util.Set;
-
 import javax.ws.rs.core.MediaType;
 
 import org.junit.Ignore;
@@ -20,13 +17,8 @@
 
 import de.ids_mannheim.korap.authentication.http.HttpAuthorizationHandler;
 import de.ids_mannheim.korap.config.Attributes;
-import de.ids_mannheim.korap.config.ContextHolder;
 import de.ids_mannheim.korap.exceptions.KustvaktException;
-import de.ids_mannheim.korap.interfaces.db.EntityHandlerIface;
 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.user.User;
 import de.ids_mannheim.korap.utils.JsonUtils;
 import de.ids_mannheim.korap.web.FastJerseyTest;
 
@@ -302,45 +294,6 @@
         assertEquals(1, node.at("/meta/totalResults").asInt());
     }
 
-    // EM: non practical use-case
-    @Test
-    @Ignore
-    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("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:docGroup", node.at("/collection/@type").asText());
-        assertEquals("operation:and",
-                node.at("/collection/operation").asText());
-        assertEquals("availability",
-                node.at("/collection/operands/0/key").asText());
-        assertEquals("CC-BY.*",
-                node.at("/collection/operands/0/value").asText());
-        assertEquals("corpusSigle",
-                node.at("/collection/operands/1/key").asText());
-        assertEquals("GOE", node.at("/collection/operands/1/value").asText());
-        assertNotEquals(0, node.path("matches").size());
-    }
-
-
     @Test
     @Ignore
     public void testSearchForCorpusWithStringIdUnauthorized () throws KustvaktException {
@@ -385,46 +338,6 @@
     }
 
 
-    @Test
-    @Ignore
-    public void testSearchForOwnersCorpusWithIntegerId ()
-            throws KustvaktException {
-
-        User kustvaktUser = ((EntityHandlerIface) helper()
-                .getBean(ContextHolder.KUSTVAKT_USERDB)).getAccount("kustvakt");
-        Set<Corpus> userCorpora = ResourceFinder.search(kustvaktUser,
-                Corpus.class);
-        Iterator<Corpus> i = userCorpora.iterator();
-        String id = null;
-        while (i.hasNext()) {
-            Corpus c = i.next();
-            if (c.getPersistentID().equals("GOE")) {
-                id = c.getId().toString();
-                //                System.out.println("Corpus "+id);
-            }
-        }
-        ClientResponse response = resource()
-                .path("corpus").path(id).path("search")
-                .queryParam("q", "[orth=das]").queryParam("ql", "poliqarp")
-                .header(Attributes.AUTHORIZATION,
-                        handler.createBasicAuthorizationHeaderValue("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:docGroup", node.at("/collection/@type").asText());
-        assertEquals("operation:and",
-                node.at("/collection/operation").asText());
-        assertEquals("availability",
-                node.at("/collection/operands/0/key").asText());
-        assertEquals("CC-BY.*",
-                node.at("/collection/operands/0/value").asText());
-        assertEquals("corpusSigle",
-                node.at("/collection/operands/1/key").asText());
-        assertEquals("GOE", node.at("/collection/operands/1/value").asText());
-    }
 
 
     @Test
diff --git a/full/src/test/resources/test-config.xml b/full/src/test/resources/test-config.xml
index 22da89a..9ac801c 100644
--- a/full/src/test/resources/test-config.xml
+++ b/full/src/test/resources/test-config.xml
@@ -194,10 +194,6 @@
 		<constructor-arg ref="kustvakt_db" />
 	</bean>
 
-	<bean id="kustvakt_policies" class="de.ids_mannheim.korap.security.ac.PolicyDao">
-		<constructor-arg ref="kustvakt_db" />
-	</bean>
-
 	<bean name="kustvakt_encryption"
 		class="de.ids_mannheim.korap.interfaces.defaults.KustvaktEncryption">
 		<constructor-arg ref="kustvakt_config" />