Added foundry rewrite with user default setting.

Change-Id: Ibc09468b6851af359eaf18df140fc973ab9dce69
diff --git a/full/Changes b/full/Changes
index fe15ea8..e9c1ada 100644
--- a/full/Changes
+++ b/full/Changes
@@ -30,7 +30,11 @@
 24/01/2019
    - Added default setting key validation & fixed UserdataTest (margaretha)
 25/01/2019   
-   - Added VC reference and MapUtil tests (margaretha)  
+   - Added VC reference and MapUtil tests (margaretha)
+28/01/2019
+   - Fixed username verification in DefaultSettingService (margaretha)
+   - Added foundry rewrite with user default setting (margaretha)
+   - Added default foundry for morphology layer (margaretha)
 
 # version 0.61.4
 14/11/2018
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
index 0b5caba..1ce9893 100644
--- a/full/src/main/java/de/ids_mannheim/korap/rewrite/CollectionConstraint.java
+++ b/full/src/main/java/de/ids_mannheim/korap/rewrite/CollectionConstraint.java
@@ -6,7 +6,9 @@
 import de.ids_mannheim.korap.config.KustvaktConfiguration;
 import de.ids_mannheim.korap.user.User;
 
-/**
+/** EM: not used anymore. This rewrite was meant to remove doc from 
+ * a collection by checking user access to the doc.  
+ * 
  * @author hanl
  * @date 03/07/2015
  */
diff --git a/full/src/main/java/de/ids_mannheim/korap/rewrite/FoundryRewrite.java b/full/src/main/java/de/ids_mannheim/korap/rewrite/FoundryRewrite.java
new file mode 100644
index 0000000..60beaaf
--- /dev/null
+++ b/full/src/main/java/de/ids_mannheim/korap/rewrite/FoundryRewrite.java
@@ -0,0 +1,33 @@
+package de.ids_mannheim.korap.rewrite;
+
+import org.springframework.beans.factory.annotation.Autowired;
+
+import de.ids_mannheim.korap.config.KustvaktConfiguration;
+import de.ids_mannheim.korap.exceptions.KustvaktException;
+import de.ids_mannheim.korap.service.DefaultSettingService;
+import de.ids_mannheim.korap.user.User;
+import de.ids_mannheim.korap.user.UserSettingProcessor;
+
+/**
+ * @author margaretha
+ *
+ */
+public class FoundryRewrite extends FoundryInject {
+
+    @Autowired
+    private DefaultSettingService settingService;
+
+    @Override
+    public KoralNode rewriteQuery (KoralNode node, KustvaktConfiguration config,
+            User user) throws KustvaktException {
+        String username = user.getUsername();
+        String jsonSettings =
+                settingService.retrieveDefaultSettings(username);
+        if (jsonSettings != null) {
+            UserSettingProcessor processor =
+                    new UserSettingProcessor(jsonSettings);
+            user.setUserSettingProcessor(processor);
+        }
+        return super.rewriteQuery(node, config, user);
+    }
+}
diff --git a/full/src/main/java/de/ids_mannheim/korap/rewrite/FullRewriteHandler.java b/full/src/main/java/de/ids_mannheim/korap/rewrite/FullRewriteHandler.java
deleted file mode 100644
index 092fe9e..0000000
--- a/full/src/main/java/de/ids_mannheim/korap/rewrite/FullRewriteHandler.java
+++ /dev/null
@@ -1,29 +0,0 @@
-package de.ids_mannheim.korap.rewrite;
-
-import org.springframework.beans.factory.annotation.Autowired;
-
-import de.ids_mannheim.korap.config.FullConfiguration;
-
-/**
- * Defines rewrite handling methods, relevant only in full version.
- * 
- * @author margaretha
- *
- */
-public class FullRewriteHandler extends RewriteHandler {
-
-    @Autowired
-    private VirtualCorpusRewrite vcRewrite;
-
-    public FullRewriteHandler (FullConfiguration config) {
-        super(config);
-    }
-
-    public void defaultRewriteConstraints () {
-        super.defaultRewriteConstraints();
-        this.addProcessor(vcRewrite);
-        this.add(CollectionRewrite.class);
-        // this.add(IdWriter.class);
-        this.add(CollectionCleanRewrite.class);
-    }
-}
diff --git a/full/src/main/java/de/ids_mannheim/korap/service/DefaultSettingService.java b/full/src/main/java/de/ids_mannheim/korap/service/DefaultSettingService.java
index bd28723..d5f0b1e 100644
--- a/full/src/main/java/de/ids_mannheim/korap/service/DefaultSettingService.java
+++ b/full/src/main/java/de/ids_mannheim/korap/service/DefaultSettingService.java
@@ -30,7 +30,7 @@
 
     private String verifiyUsername (String username, String contextUsername)
             throws KustvaktException {
-        username = username.substring(0);
+        username = username.substring(1);
         if (!username.equals(contextUsername)) {
             throw new KustvaktException(StatusCodes.INVALID_ARGUMENT,
                     "Username verification failed. Path parameter username "
@@ -93,10 +93,17 @@
             String contextUsername) throws KustvaktException {
 
         username = verifiyUsername(username, contextUsername);
+        return retrieveDefaultSettings(username);
+    }
+    
+    public String retrieveDefaultSettings (String username) throws KustvaktException {
         DefaultSetting defaultSetting =
                 settingDao.retrieveDefautlSetting(username);
+        if (defaultSetting == null) {
+            return null;
+        }
         return defaultSetting.getSettings();
-    }
+    }    
 
     public void deleteKey (String username, String contextUsername, String key)
             throws KustvaktException {
diff --git a/full/src/main/java/de/ids_mannheim/korap/web/controller/UserSettingController.java b/full/src/main/java/de/ids_mannheim/korap/web/controller/UserSettingController.java
index 5f24f00..4cb0cc9 100644
--- a/full/src/main/java/de/ids_mannheim/korap/web/controller/UserSettingController.java
+++ b/full/src/main/java/de/ids_mannheim/korap/web/controller/UserSettingController.java
@@ -21,6 +21,7 @@
 
 import de.ids_mannheim.korap.constant.OAuth2Scope;
 import de.ids_mannheim.korap.exceptions.KustvaktException;
+import de.ids_mannheim.korap.exceptions.StatusCodes;
 import de.ids_mannheim.korap.oauth2.service.OAuth2ScopeService;
 import de.ids_mannheim.korap.security.context.TokenContext;
 import de.ids_mannheim.korap.service.DefaultSettingService;
@@ -111,6 +112,11 @@
                     OAuth2Scope.READ_DEFAULT_SETTING);
             String settings = settingService.retrieveDefaultSettings(username,
                     tokenContext.getUsername());
+            if (settings == null){
+                username = tokenContext.getUsername();
+                throw new KustvaktException(StatusCodes.NO_RESULT_FOUND,
+                        "No setting is found for " + username, username);
+            }
             return Response.ok(settings).build();
         }
         catch (KustvaktException e) {
diff --git a/full/src/main/resources/db/predefined/V3.2__insert_predefined_roles.sql b/full/src/main/resources/db/predefined/V2.1__insert_predefined_roles.sql
similarity index 100%
rename from full/src/main/resources/db/predefined/V3.2__insert_predefined_roles.sql
rename to full/src/main/resources/db/predefined/V2.1__insert_predefined_roles.sql
diff --git a/full/src/main/resources/db/insert/V3.1__insert_virtual_corpus.sql b/full/src/main/resources/db/test/V3.1__insert_virtual_corpus.sql
similarity index 100%
rename from full/src/main/resources/db/insert/V3.1__insert_virtual_corpus.sql
rename to full/src/main/resources/db/test/V3.1__insert_virtual_corpus.sql
diff --git a/full/src/main/resources/db/insert/V3.3__insert_member_roles.sql b/full/src/main/resources/db/test/V3.3__insert_member_roles.sql
similarity index 100%
rename from full/src/main/resources/db/insert/V3.3__insert_member_roles.sql
rename to full/src/main/resources/db/test/V3.3__insert_member_roles.sql
diff --git a/full/src/main/resources/db/insert/V3.4__insert_admins.sql b/full/src/main/resources/db/test/V3.4__insert_admins.sql
similarity index 100%
rename from full/src/main/resources/db/insert/V3.4__insert_admins.sql
rename to full/src/main/resources/db/test/V3.4__insert_admins.sql
diff --git a/full/src/main/resources/db/insert/V3.5__insert_oauth2_clients.sql b/full/src/main/resources/db/test/V3.5__insert_oauth2_clients.sql
similarity index 100%
rename from full/src/main/resources/db/insert/V3.5__insert_oauth2_clients.sql
rename to full/src/main/resources/db/test/V3.5__insert_oauth2_clients.sql
diff --git a/full/src/main/resources/db/test/V3.6__insert_default_settings.sql b/full/src/main/resources/db/test/V3.6__insert_default_settings.sql
new file mode 100644
index 0000000..5bd5264
--- /dev/null
+++ b/full/src/main/resources/db/test/V3.6__insert_default_settings.sql
@@ -0,0 +1,2 @@
+INSERT INTO default_setting(username,settings) 
+	VALUES ("bubbles",'{"pos-foundry":"corenlp", "lemma-foundry":"opennlp"}');
diff --git a/full/src/main/resources/default-config.xml b/full/src/main/resources/default-config.xml
index c8fd658..a3de4ac 100644
--- a/full/src/main/resources/default-config.xml
+++ b/full/src/main/resources/default-config.xml
@@ -215,8 +215,19 @@
 	</bean>
 	
 	<!-- Rewrite -->
-	<bean id="rewriteHandler" class="de.ids_mannheim.korap.rewrite.FullRewriteHandler">
-		<constructor-arg ref="kustvakt_config" />
+	<bean id="foundryRewrite" class="de.ids_mannheim.korap.rewrite.FoundryRewrite"/>
+	<bean id="collectionRewrite" class="de.ids_mannheim.korap.rewrite.CollectionRewrite"/>
+	<bean id="virtualCorpusRewrite" class="de.ids_mannheim.korap.rewrite.VirtualCorpusRewrite"/>
+	
+	<util:list id="rewriteTasks"
+		value-type="de.ids_mannheim.korap.rewrite.RewriteTask">
+		<ref bean="foundryRewrite" />
+		<ref bean="collectionRewrite" />
+		<ref bean="virtualCorpusRewrite" />
+	</util:list>
+	
+	<bean id="rewriteHandler" class="de.ids_mannheim.korap.rewrite.RewriteHandler">
+		<constructor-arg ref="rewriteTasks"/>
 	</bean>
 
 	<bean id="kustvakt_auditing" class="de.ids_mannheim.korap.handlers.JDBCAuditing">
diff --git a/full/src/main/resources/kustvakt.conf b/full/src/main/resources/kustvakt.conf
index a26cb2d..ec540f9 100644
--- a/full/src/main/resources/kustvakt.conf
+++ b/full/src/main/resources/kustvakt.conf
@@ -29,12 +29,13 @@
 ## mail.templates
 template.group.invitation = notification.vm
 
-## default layers
-default.layer.partOfSpeech = tt
-default.layer.lemma = tt
-default.layer.orthography = opennlp
-default.layer.dependency = mate
-default.layer.constituent = corenlp
+## default foundries for specific layers
+default.foundry.partOfSpeech = tt
+default.foundry.lemma = tt
+default.foundry.orthography = opennlp
+default.foundry.dependency = malt
+default.foundry.constituent = corenlp
+default.foundry.morphology = marmot
 
 ## delete configuration (default hard)
 # delete.auto.group = hard
diff --git a/full/src/test/java/de/ids_mannheim/korap/config/TestHelper.java b/full/src/test/java/de/ids_mannheim/korap/config/TestHelper.java
index 4a66f9c..efe2fd8 100644
--- a/full/src/test/java/de/ids_mannheim/korap/config/TestHelper.java
+++ b/full/src/test/java/de/ids_mannheim/korap/config/TestHelper.java
@@ -50,9 +50,9 @@
         data.put(Attributes.LASTNAME, "user");
         data.put(Attributes.EMAIL, "test@ids-mannheim.de");
         data.put(Attributes.ADDRESS, "Mannheim");
-        data.put(Attributes.DEFAULT_LEMMA_FOUNDRY, "test_l");
-        data.put(Attributes.DEFAULT_POS_FOUNDRY, "test_p");
-        data.put(Attributes.DEFAULT_CONST_FOUNDRY, "test_const");
+        data.put(Attributes.DEFAULT_FOUNDRY_LEMMA, "test_l");
+        data.put(Attributes.DEFAULT_FOUNDRY_POS, "test_p");
+        data.put(Attributes.DEFAULT_FOUNDRY_CONSTITUENT, "test_const");
     }
 
     private ContextHolder beansHolder;
diff --git a/full/src/test/java/de/ids_mannheim/korap/rewrite/CollectionRewriteTest.java b/full/src/test/java/de/ids_mannheim/korap/rewrite/CollectionRewriteTest.java
index 630d290..e820f28 100644
--- a/full/src/test/java/de/ids_mannheim/korap/rewrite/CollectionRewriteTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/rewrite/CollectionRewriteTest.java
@@ -13,10 +13,6 @@
 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.CollectionCleanRewrite;
-import de.ids_mannheim.korap.rewrite.CollectionConstraint;
-import de.ids_mannheim.korap.rewrite.CollectionRewrite;
-import de.ids_mannheim.korap.rewrite.RewriteHandler;
 import de.ids_mannheim.korap.user.User;
 import de.ids_mannheim.korap.utils.JsonUtils;
 
@@ -108,7 +104,6 @@
         JsonNode node = JsonUtils.readTree(handler.processQuery(result,
                 User.UserFactory.getUser("test_user")));
 
-
         assertNotNull(node);
         assertEquals("koral:docGroup", node.at("/collection/@type").asText());
         assertEquals(2, node.at("/collection/operands").size());
@@ -233,7 +228,6 @@
                 node.at("/collection/operands/1/operands/0/key").asText());
         assertEquals("textClass",
                 node.at("/collection/operands/1/operands/1/key").asText());
-        System.out.println(node);
         assertEquals("koral:rewrite", node.at("/collection/rewrites/0/@type")
                 .asText());
         assertEquals("availability(FREE)", node.at("/collection/rewrites/0/scope")
diff --git a/full/src/test/java/de/ids_mannheim/korap/rewrite/FoundryRewriteTest.java b/full/src/test/java/de/ids_mannheim/korap/rewrite/FoundryRewriteTest.java
index dc80bbb..ee86fc2 100644
--- a/full/src/test/java/de/ids_mannheim/korap/rewrite/FoundryRewriteTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/rewrite/FoundryRewriteTest.java
@@ -5,42 +5,113 @@
 import static org.junit.Assert.assertNotNull;
 import static org.junit.Assert.assertTrue;
 
+import javax.ws.rs.core.MediaType;
+
 import org.junit.Test;
 import org.springframework.beans.factory.annotation.Autowired;
 
 import com.fasterxml.jackson.databind.JsonNode;
+import com.sun.jersey.api.client.ClientResponse;
+import com.sun.jersey.api.client.ClientResponse.Status;
 
+import de.ids_mannheim.korap.authentication.http.HttpAuthorizationHandler;
+import de.ids_mannheim.korap.config.Attributes;
 import de.ids_mannheim.korap.config.KustvaktConfiguration;
 import de.ids_mannheim.korap.config.SpringJerseyTest;
 import de.ids_mannheim.korap.exceptions.KustvaktException;
 import de.ids_mannheim.korap.query.serialize.QuerySerializer;
-import de.ids_mannheim.korap.rewrite.LayerMapper;
-import de.ids_mannheim.korap.rewrite.RewriteHandler;
 import de.ids_mannheim.korap.user.KorAPUser;
 import de.ids_mannheim.korap.utils.JsonUtils;
 
 /**
- * @author hanl
+ * @author hanl, margaretha
  * @date 18/06/2015
  */
-//todo: check position and information of rewrites!
+//MH todo: check position and information of rewrites!
 public class FoundryRewriteTest extends SpringJerseyTest {
 
-    private static String simple_add_query = "[pos=ADJA]";
-    private static String simple_rewrite_query = "[base=Haus]";
-    private static String complex_rewrite_query = "<c=INFC>";
-    private static String complex_rewrite_query2 = "[orth=laufe/i & base!=Lauf]";
-    private static String complex_rewrite_query3 = "[(base=laufen | base=gehen) & tt/pos=VVFIN]";
+//    private static String simple_add_query = "[pos=ADJA]";
+//    private static String simple_rewrite_query = "[base=Haus]";
+//    private static String complex_rewrite_query = "<c=INFC>";
+//    private static String complex_rewrite_query2 = "[orth=laufe/i & base!=Lauf]";
+//    private static String complex_rewrite_query3 = "[(base=laufen | base=gehen) & tt/pos=VVFIN]";
 
     @Autowired
     public KustvaktConfiguration config;
     @Autowired
     public RewriteHandler handler; 
+    @Autowired
+    private LayerMapper m;
+    
+    @Test
+    public void testSearchRewriteFoundryWithUserSetting () throws KustvaktException {
+        // create user setting
+        String json = "{\"pos-foundry\":\"opennlp\"}";
+        String username = "foundryRewriteTest";
+        String pathUsername = "~" + username;
+        ClientResponse response = resource().path(API_VERSION)
+                .path(pathUsername).path("setting")
+                .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+                        .createBasicAuthorizationHeaderValue(username, "pass"))
+                .type(MediaType.APPLICATION_JSON).entity(json)
+                .put(ClientResponse.class);
+
+        assertEquals(Status.CREATED.getStatusCode(), response.getStatus());
+
+        // search
+        response = resource().path(API_VERSION).path("search")
+                .queryParam("q", "[pos=ADJA]").queryParam("ql", "poliqarp")
+                .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+                        .createBasicAuthorizationHeaderValue(username, "pass"))
+                .accept(MediaType.APPLICATION_JSON).get(ClientResponse.class);
+        
+        assertEquals(ClientResponse.Status.OK.getStatusCode(),
+                response.getStatus());
+        String ent = response.getEntity(String.class);
+        JsonNode node = JsonUtils.readTree(ent);
+        assertEquals("opennlp", node.at("/query/wrap/foundry").asText());
+        assertEquals("foundry",
+                node.at("/query/wrap/rewrites/0/scope").asText());
+
+    }
+
+    @Test
+    public void testRewritePosFoundryWithUserSetting ()
+            throws KustvaktException {
+        // EM: see
+        // full/src/main/resources/db/insert/V3.6__insert_default_settings.sql
+
+        String username = "bubbles";
+        QuerySerializer s = new QuerySerializer();
+        s.setQuery("[pos=ADJA]", "poliqarp");
+        String result =
+                handler.processQuery(s.toJSON(), new KorAPUser(username));
+        JsonNode node = JsonUtils.readTree(result);
+        assertEquals("corenlp", node.at("/query/wrap/foundry").asText());
+        assertEquals("foundry",
+                node.at("/query/wrap/rewrites/0/scope").asText());
+
+    }
+
+    @Test
+    public void testRewriteLemmaFoundryWithUserSetting ()
+            throws KustvaktException {
+        String username = "bubbles";
+        QuerySerializer s = new QuerySerializer();
+        s.setQuery("[base=Haus]", "poliqarp");
+        String result =
+                handler.processQuery(s.toJSON(), new KorAPUser(username));
+        JsonNode node = JsonUtils.readTree(result);
+        // EM: only for testing, in fact, opennlp lemma does not
+        // exist!
+        assertEquals("opennlp", node.at("/query/wrap/foundry").asText());
+        assertEquals("foundry",
+                node.at("/query/wrap/rewrites/0/scope").asText());
+    }
+    
     
     @Test
     public void testDefaultLayerMapperThrowsNoException () {
-        LayerMapper m = new LayerMapper(config);
-
         assertEquals(config.getDefault_lemma(), m.findFoundry("lemma"));
         assertEquals(config.getDefault_pos(), m.findFoundry("pos"));
         assertEquals(config.getDefault_token(), m.findFoundry("surface"));
@@ -48,14 +119,13 @@
         assertEquals(config.getDefault_const(), m.findFoundry("c"));
     }
 
-
     @Test
     public void testDefaultFoundryInjectLemmaThrowsNoError ()
             throws KustvaktException {
 
         QuerySerializer s = new QuerySerializer();
         s.setQuery("[base=Haus]", "poliqarp");
-        String result = handler.processQuery(s.toJSON(), new KorAPUser());
+        String result = handler.processQuery(s.toJSON(), new KorAPUser("test"));
         JsonNode node = JsonUtils.readTree(result);
         assertNotNull(node);
         assertFalse(node.at("/query/wrap/foundry").isMissingNode());
@@ -73,7 +143,7 @@
 
         QuerySerializer s = new QuerySerializer();
         s.setQuery("[pos=ADJA]", "poliqarp");
-        String result = handler.processQuery(s.toJSON(), new KorAPUser());
+        String result = handler.processQuery(s.toJSON(), new KorAPUser("test"));
         JsonNode node = JsonUtils.readTree(result);
 
         assertNotNull(node);
@@ -86,79 +156,14 @@
                 .asText());
 
     }
-
-    // EM: Fix me usersetting
-//    @Test
-//    @Ignore
-//    public void testRewriteFoundryInjectPOSThrowsNoError ()
-//            throws KustvaktException {
-//        User user = helper().getUser();
-//
-//        RewriteHandler handler = new RewriteHandler();
-//        handler.insertBeans(helper().getContext());
-//        handler.add(FoundryInject.class);
-//        QuerySerializer s = new QuerySerializer();
-//        s.setQuery("[pos=ADJA]", "poliqarp");
-//        String result = handler.processQuery(s.toJSON(), user);
-//        JsonNode node = JsonUtils.readTree(result);
-//
-//        UserDataDbIface dao = BeansFactory.getTypeFactory()
-//                .getTypeInterfaceBean(
-//                        helper().getContext().getUserDataProviders(),
-//                        UserSettings.class);
-//        UserSettings settings = (UserSettings) dao.get(user);
-//        assertTrue(settings.isValid());
-//        String pos = (String) settings.get(Attributes.DEFAULT_POS_FOUNDRY);
-//
-//        assertNotNull(node);
-//        assertEquals("pos", node.at("/query/wrap/layer").asText());
-//        assertEquals(pos, node.at("/query/wrap/foundry").asText());
-//        assertFalse(node.at("/query/wrap/rewrites").isMissingNode());
-//        assertEquals("koral:rewrite", node.at("/query/wrap/rewrites/0/@type")
-//                .asText());
-//    }
-
-    // EM: Fix me usersetting
-//    @Test
-//    @Ignore
-//    public void testRewriteFoundryInjectLemmaThrowsNoError ()
-//            throws KustvaktException {
-//        KustvaktConfiguration c = helper().getBean(
-//                ContextHolder.KUSTVAKT_CONFIG);
-//        User user = helper().getUser();
-//
-//        RewriteHandler handler = new RewriteHandler();
-//        handler.insertBeans(helper().getContext());
-//        handler.add(FoundryInject.class);
-//        QuerySerializer s = new QuerySerializer();
-//        s.setQuery("[base=Haus]", "poliqarp");
-//        String result = handler.processQuery(s.toJSON(), user);
-//        JsonNode node = JsonUtils.readTree(result);
-//
-//        UserDataDbIface dao = BeansFactory.getTypeFactory()
-//                .getTypeInterfaceBean(
-//                        helper().getContext().getUserDataProviders(),
-//                        UserSettings.class);
-//        UserSettings settings = (UserSettings) dao.get(user);
-//        assertTrue(settings.isValid());
-//        String lemma = (String) settings.get(Attributes.DEFAULT_LEMMA_FOUNDRY);
-//
-//        assertNotNull(node);
-//        assertEquals("lemma", node.at("/query/wrap/layer").asText());
-//        assertEquals(lemma, node.at("/query/wrap/foundry").asText());
-//        assertFalse(node.at("/query/wrap/rewrites").isMissingNode());
-//        assertEquals("koral:rewrite", node.at("/query/wrap/rewrites/0/@type")
-//                .asText());
-//    }
-
-
+    
     @Test
     public void testFoundryInjectJoinedQueryNoErrors ()
             throws KustvaktException {
 
         QuerySerializer s = new QuerySerializer();
         s.setQuery("[orth=laufe/i & base!=Lauf]", "poliqarp");
-        String result = handler.processQuery(s.toJSON(), new KorAPUser());
+        String result = handler.processQuery(s.toJSON(), new KorAPUser("test"));
         JsonNode node = JsonUtils.readTree(result);
 
         assertNotNull(node);
@@ -175,9 +180,9 @@
             throws KustvaktException {
         QuerySerializer s = new QuerySerializer();
         s.setQuery("[(base=laufen | tt/pos=VVFIN)]", "poliqarp");
-        String result = handler.processQuery(s.toJSON(), new KorAPUser());
+        String result = handler.processQuery(s.toJSON(), new KorAPUser("test"));
         JsonNode node = JsonUtils.readTree(result);
-//        System.out.println("NODDE "+ node);
+
         assertNotNull(node);
         assertEquals("koral:termGroup", node.at("/query/wrap/@type").asText());
         assertFalse(node.at("/query/wrap/operands/0/foundry")
@@ -192,10 +197,9 @@
     public void testFoundryBaseRewrite() throws KustvaktException {
         QuerySerializer s = new QuerySerializer();
         s.setQuery("[orth=laufen]", "poliqarp");
-        String result = handler.processQuery(s.toJSON(), new KorAPUser());
+        String result = handler.processQuery(s.toJSON(), new KorAPUser("test"));
         JsonNode node = JsonUtils.readTree(result);
-        System.out.println("NODE "+ node);
-//        assertNotNull(node);
+
         assertEquals("koral:term", node.at("/query/wrap/@type").asText());
         assertFalse(node.at("/query/wrap/foundry")
                 .isMissingNode());
diff --git a/full/src/test/java/de/ids_mannheim/korap/rewrite/RewriteHandlerTest.java b/full/src/test/java/de/ids_mannheim/korap/rewrite/RewriteHandlerTest.java
index 9c33f31..135e209 100644
--- a/full/src/test/java/de/ids_mannheim/korap/rewrite/RewriteHandlerTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/rewrite/RewriteHandlerTest.java
@@ -1,23 +1,14 @@
 package de.ids_mannheim.korap.rewrite;
 
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
 import static org.junit.Assert.assertTrue;
 
 import org.junit.Test;
 import org.springframework.beans.factory.annotation.Autowired;
 
-import com.fasterxml.jackson.databind.JsonNode;
-
 import de.ids_mannheim.korap.config.KustvaktConfiguration;
 import de.ids_mannheim.korap.config.SpringJerseyTest;
 import de.ids_mannheim.korap.exceptions.KustvaktException;
 import de.ids_mannheim.korap.query.serialize.QuerySerializer;
-import de.ids_mannheim.korap.rewrite.CollectionCleanRewrite;
-import de.ids_mannheim.korap.rewrite.FoundryInject;
-import de.ids_mannheim.korap.rewrite.IdWriter;
-import de.ids_mannheim.korap.rewrite.RewriteHandler;
-import de.ids_mannheim.korap.utils.JsonUtils;
 
 /** EM: to do: Fix tests
  *  New DB does not save users.
@@ -49,31 +40,32 @@
         handler.processQuery(s.toJSON(), null);
     }
 
-
-    @Test
-    public void testRewriteNoBeanInject () throws KustvaktException {
-        RewriteHandler handler = new RewriteHandler(config);
-        QuerySerializer s = new QuerySerializer();
-        s.setQuery("[(base=laufen | base=gehen) & tt/pos=VVFIN]", "poliqarp");
-        assertTrue(handler.add(FoundryInject.class));
-        String res = handler.processQuery(s.toJSON(), null);
-        assertNotNull(res);
-    }
-    
-    @Test
-    public void testRewriteBeanInject () throws KustvaktException {
-        RewriteHandler handler = new RewriteHandler(config);
-        QuerySerializer s = new QuerySerializer();
-        s.setQuery("[base=laufen | tt/pos=VVFIN]", "poliqarp");
-        assertTrue(handler.add(FoundryInject.class));
-        String res = handler.processQuery(s.toJSON(), null);
-        JsonNode node = JsonUtils.readTree(res);
-        assertNotNull(node);
-        assertEquals("tt", node.at("/query/wrap/operands/0/foundry")
-                .asText());
-        assertEquals("tt", node.at("/query/wrap/operands/1/foundry")
-                .asText());
-    }
+//    @Deprecated
+//    @Test
+//    public void testRewriteNoBeanInject () throws KustvaktException {
+//        RewriteHandler handler = new RewriteHandler(config);
+//        QuerySerializer s = new QuerySerializer();
+//        s.setQuery("[(base=laufen | base=gehen) & tt/pos=VVFIN]", "poliqarp");
+//        assertTrue(handler.add(FoundryInject.class));
+//        String res = handler.processQuery(s.toJSON(), null);
+//        assertNotNull(res);
+//    }
+//    
+//    @Deprecated
+//    @Test
+//    public void testRewriteBeanInject () throws KustvaktException {
+//        RewriteHandler handler = new RewriteHandler(config);
+//        QuerySerializer s = new QuerySerializer();
+//        s.setQuery("[base=laufen | tt/pos=VVFIN]", "poliqarp");
+//        assertTrue(handler.add(FoundryInject.class));
+//        String res = handler.processQuery(s.toJSON(), null);
+//        JsonNode node = JsonUtils.readTree(res);
+//        assertNotNull(node);
+//        assertEquals("tt", node.at("/query/wrap/operands/0/foundry")
+//                .asText());
+//        assertEquals("tt", node.at("/query/wrap/operands/1/foundry")
+//                .asText());
+//    }
 
     // EM: Fix me usersetting
 //    @Test
diff --git a/full/src/test/java/de/ids_mannheim/korap/user/UserdataTest.java b/full/src/test/java/de/ids_mannheim/korap/user/UserdataTest.java
index 970a698..c828b05 100644
--- a/full/src/test/java/de/ids_mannheim/korap/user/UserdataTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/user/UserdataTest.java
@@ -109,10 +109,10 @@
     public void testUserdataDefaultFields () throws KustvaktException {
         UserSettingProcessor settings = new UserSettingProcessor();
         Map<String, Object> m = new HashMap<>();
-        m.put(Attributes.DEFAULT_REL_FOUNDRY, "rel_1");
-        m.put(Attributes.DEFAULT_CONST_FOUNDRY, "const_1");
-        m.put(Attributes.DEFAULT_POS_FOUNDRY, "pos_1");
-        m.put(Attributes.DEFAULT_LEMMA_FOUNDRY, "lemma_1");
+        m.put(Attributes.DEFAULT_FOUNDRY_RELATION, "rel_1");
+        m.put(Attributes.DEFAULT_FOUNDRY_CONSTITUENT, "const_1");
+        m.put(Attributes.DEFAULT_FOUNDRY_POS, "pos_1");
+        m.put(Attributes.DEFAULT_FOUNDRY_LEMMA, "lemma_1");
         m.put(Attributes.PAGE_LENGTH, 10);
         m.put(Attributes.QUERY_LANGUAGE, "poliqarp");
         m.put(Attributes.METADATA_QUERY_EXPERT_MODUS, false);
@@ -121,10 +121,10 @@
 
         assertNotEquals(m.size(), settings.size());
         assertEquals(settings.defaultFields().length, settings.size());
-        assertEquals("rel_1", settings.get(Attributes.DEFAULT_REL_FOUNDRY));
-        assertEquals("pos_1", settings.get(Attributes.DEFAULT_POS_FOUNDRY));
-        assertEquals("lemma_1", settings.get(Attributes.DEFAULT_LEMMA_FOUNDRY));
-        assertEquals("const_1", settings.get(Attributes.DEFAULT_CONST_FOUNDRY));
+        assertEquals("rel_1", settings.get(Attributes.DEFAULT_FOUNDRY_RELATION));
+        assertEquals("pos_1", settings.get(Attributes.DEFAULT_FOUNDRY_POS));
+        assertEquals("lemma_1", settings.get(Attributes.DEFAULT_FOUNDRY_LEMMA));
+        assertEquals("const_1", settings.get(Attributes.DEFAULT_FOUNDRY_CONSTITUENT));
         assertEquals(10, settings.get(Attributes.PAGE_LENGTH));
 
     }
diff --git a/full/src/test/java/de/ids_mannheim/korap/web/controller/UserSettingControllerTest.java b/full/src/test/java/de/ids_mannheim/korap/web/controller/UserSettingControllerTest.java
index c3fd0b4..880cc14 100644
--- a/full/src/test/java/de/ids_mannheim/korap/web/controller/UserSettingControllerTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/web/controller/UserSettingControllerTest.java
@@ -28,12 +28,12 @@
  */
 public class UserSettingControllerTest extends SpringJerseyTest {
 
-    private String username = "~UserSettingTest";
-    private String username2 = "~UserSettingTest2";
+    private String username = "UserSettingTest";
+    private String username2 = "UserSettingTest2";
 
-    private ClientResponse sendPutRequest (String username,
+    public ClientResponse sendPutRequest (String username,
             Map<String, Object> map) throws KustvaktException {
-        ClientResponse response = resource().path(API_VERSION).path(username)
+        ClientResponse response = resource().path(API_VERSION).path("~"+username)
                 .path("setting")
                 .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
                         .createBasicAuthorizationHeaderValue(username, "pass"))
@@ -45,10 +45,10 @@
 
     @Test
     public void testCreateSettingWithJson () throws KustvaktException {
-        String json = "{\"foundry\":\"opennlp\",\"metadata\":\"author title "
+        String json = "{\"pos-foundry\":\"opennlp\",\"metadata\":\"author title "
                 + "textSigle availability\",\"resultPerPage\":25}";
 
-        ClientResponse response = resource().path(API_VERSION).path(username)
+        ClientResponse response = resource().path(API_VERSION).path("~"+username)
                 .path("setting")
                 .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
                         .createBasicAuthorizationHeaderValue(username, "pass"))
@@ -69,7 +69,7 @@
     public void testCreateSettingWithMap () throws KustvaktException {
 
         Map<String, Object> map = new HashMap<>();
-        map.put("foundry", "opennlp");
+        map.put("pos-foundry", "opennlp");
         map.put("resultPerPage", 25);
         map.put("metadata", "author title textSigle availability");
 
@@ -82,7 +82,7 @@
         testUpdateSetting(username2);
         testputRequestInvalidKey();
     }
-    
+
     @Test
     public void testputRequestInvalidKey () throws KustvaktException {
         Map<String, Object> map = new HashMap<>();
@@ -90,18 +90,19 @@
 
         ClientResponse response = sendPutRequest(username2, map);
         assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
-        
+
         JsonNode node = JsonUtils.readTree(response.getEntity(String.class));
-        assertEquals(StatusCodes.INVALID_ARGUMENT, node.at("/errors/0/0").asInt());
+        assertEquals(StatusCodes.INVALID_ARGUMENT,
+                node.at("/errors/0/0").asInt());
         assertEquals("key/", node.at("/errors/0/2").asText());
     }
-    
+
     @Test
     public void testPutDifferentUsername () throws KustvaktException {
-        String json = "{\"foundry\":\"opennlp\",\"metadata\":\"author title "
+        String json = "{\"pos-foundry\":\"opennlp\",\"metadata\":\"author title "
                 + "textSigle availability\",\"resultPerPage\":25}";
 
-        ClientResponse response = resource().path(API_VERSION).path(username)
+        ClientResponse response = resource().path(API_VERSION).path("~"+username)
                 .path("setting")
                 .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
                         .createBasicAuthorizationHeaderValue(username2, "pass"))
@@ -117,7 +118,7 @@
 
     @Test
     public void testGetDifferentUsername () throws KustvaktException {
-        ClientResponse response = resource().path(API_VERSION).path(username)
+        ClientResponse response = resource().path(API_VERSION).path("~"+username)
                 .path("setting")
                 .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
                         .createBasicAuthorizationHeaderValue(username2, "pass"))
@@ -132,8 +133,8 @@
 
     @Test
     public void testDeleteKeyDifferentUsername () throws KustvaktException {
-        ClientResponse response = resource().path(API_VERSION).path(username)
-                .path("setting").path("foundry")
+        ClientResponse response = resource().path(API_VERSION).path("~"+username)
+                .path("setting").path("pos-foundry")
                 .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
                         .createBasicAuthorizationHeaderValue(username2, "pass"))
                 .delete(ClientResponse.class);
@@ -148,8 +149,8 @@
     private void testDeleteKey (String username, int numOfResult,
             String metadata) throws KustvaktException {
 
-        ClientResponse response = resource().path(API_VERSION).path(username)
-                .path("setting").path("foundry")
+        ClientResponse response = resource().path(API_VERSION).path("~"+username)
+                .path("setting").path("pos-foundry")
                 .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
                         .createBasicAuthorizationHeaderValue(username, "pass"))
                 .delete(ClientResponse.class);
@@ -160,7 +161,7 @@
 
     private void testUpdateSetting (String username) throws KustvaktException {
         Map<String, Object> map = new HashMap<>();
-        map.put("foundry", "malt");
+        map.put("pos-foundry", "malt");
         map.put("resultPerPage", 15);
         map.put("metadata", "author title");
 
@@ -169,10 +170,10 @@
 
         testRetrieveSettings(username, "malt", 15, "author title");
     }
-    
-    private void testRetrieveSettings (String username, String foundry,
+
+    private void testRetrieveSettings (String username, String posFoundry,
             int numOfResult, String metadata) throws KustvaktException {
-        ClientResponse response = resource().path(API_VERSION).path(username)
+        ClientResponse response = resource().path(API_VERSION).path("~"+username)
                 .path("setting")
                 .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
                         .createBasicAuthorizationHeaderValue(username, "pass"))
@@ -181,11 +182,11 @@
 
         String entity = response.getEntity(String.class);
         JsonNode node = JsonUtils.readTree(entity);
-        if (foundry == null) {
-            assertTrue(node.at("/foundry").isMissingNode());
+        if (posFoundry == null) {
+            assertTrue(node.at("/pos-foundry").isMissingNode());
         }
         else {
-            assertEquals(foundry, node.at("/foundry").asText());
+            assertEquals(posFoundry, node.at("/pos-foundry").asText());
         }
         assertEquals(numOfResult, node.at("/resultPerPage").asInt());
         assertEquals(metadata, node.at("/metadata").asText());
diff --git a/full/src/test/resources/kustvakt-test.conf b/full/src/test/resources/kustvakt-test.conf
index b1d9e21..ce12cff 100644
--- a/full/src/test/resources/kustvakt-test.conf
+++ b/full/src/test/resources/kustvakt-test.conf
@@ -29,12 +29,13 @@
 ## mail.templates
 template.group.invitation = notification.vm
 
-## default layers
-default.layer.partOfSpeech = tt
-default.layer.lemma = tt
-default.layer.orthography = opennlp
-default.layer.dependency = mate
-default.layer.constituent = corenlp
+## default foundries for specific layers
+default.foundry.partOfSpeech = tt
+default.foundry.lemma = tt
+default.foundry.orthography = opennlp
+default.foundry.dependency = malt
+default.foundry.constituent = corenlp
+default.foundry.morphology = marmot
 
 ## delete configuration (default hard)
 # delete.auto.group = hard
diff --git a/full/src/test/resources/test-config.xml b/full/src/test/resources/test-config.xml
index 6a19768..16f7ee3 100644
--- a/full/src/test/resources/test-config.xml
+++ b/full/src/test/resources/test-config.xml
@@ -196,8 +196,24 @@
 		<constructor-arg value="http,https" />
 	</bean>
 
-	<bean id="rewriteHandler" class="de.ids_mannheim.korap.rewrite.FullRewriteHandler">
-		<constructor-arg ref="kustvakt_config" />
+	<!-- Rewrite -->
+	<bean id="foundryRewrite" class="de.ids_mannheim.korap.rewrite.FoundryRewrite"/>
+	<bean id="collectionRewrite" class="de.ids_mannheim.korap.rewrite.CollectionRewrite"/>
+	<bean id="collectionCleanRewrite" class="de.ids_mannheim.korap.rewrite.CollectionCleanRewrite"/>
+	<bean id="virtualCorpusRewrite" class="de.ids_mannheim.korap.rewrite.VirtualCorpusRewrite"/>
+	<bean id="collectionConstraint" class="de.ids_mannheim.korap.rewrite.CollectionConstraint"/>
+	
+	<util:list id="rewriteTasks"
+		value-type="de.ids_mannheim.korap.rewrite.RewriteTask">
+		<!-- <ref bean="collectionConstraint" />
+		<ref bean="collectionCleanRewrite" /> -->
+		<ref bean="foundryRewrite" />
+		<ref bean="collectionRewrite" />
+		<ref bean="virtualCorpusRewrite" />
+	</util:list>
+	
+	<bean id="rewriteHandler" class="de.ids_mannheim.korap.rewrite.RewriteHandler">
+		<constructor-arg ref="rewriteTasks"/>
 	</bean>
 
 	<bean id="kustvakt_auditing" class="de.ids_mannheim.korap.handlers.JDBCAuditing">
diff --git a/full/src/test/resources/test-jdbc.properties b/full/src/test/resources/test-jdbc.properties
index bbf5f6b..da5fd57 100644
--- a/full/src/test/resources/test-jdbc.properties
+++ b/full/src/test/resources/test-jdbc.properties
@@ -7,5 +7,4 @@
 #jdbc.url=jdbc:sqlite:testDB.sqlite
 jdbc.username=pc
 jdbc.password=pc
-#jdbc.schemaPath=classpath:db.sqlite
-jdbc.schemaPath=classpath:db.sqlite, db.insert, db.predefined
\ No newline at end of file
+jdbc.schemaPath=classpath:db.sqlite, db.test, db.predefined
\ No newline at end of file