Added foundry rewrite with user default setting.

Change-Id: Ibc09468b6851af359eaf18df140fc973ab9dce69
diff --git a/core/Changes b/core/Changes
index 5b04a5e..4aaa3b2 100644
--- a/core/Changes
+++ b/core/Changes
@@ -18,7 +18,8 @@
    - Added create, edit, retrieve user default setting controllers (margaretha)
 24/01/2019
    - Added default setting key validation & fixed UserdataTest (margaretha)   
-
+28/01/2019
+   - Updated Rewrite handler (margaretha)
 
 version 0.61.4
 14/11/2018
diff --git a/core/src/main/java/de/ids_mannheim/korap/config/Attributes.java b/core/src/main/java/de/ids_mannheim/korap/config/Attributes.java
index dd54f28..2ad58cc 100644
--- a/core/src/main/java/de/ids_mannheim/korap/config/Attributes.java
+++ b/core/src/main/java/de/ids_mannheim/korap/config/Attributes.java
@@ -144,10 +144,11 @@
     /**
      * default layers
      */
-    public static final String DEFAULT_POS_FOUNDRY = "POSFoundry";
-    public static final String DEFAULT_LEMMA_FOUNDRY = "lemmaFoundry";
-    public static final String DEFAULT_CONST_FOUNDRY = "constFoundry";
-    public static final String DEFAULT_REL_FOUNDRY = "relFoundry";
+    public static final String DEFAULT_FOUNDRY_POS = "pos-foundry";
+    public static final String DEFAULT_FOUNDRY_LEMMA = "lemma-foundry";
+    public static final String DEFAULT_FOUNDRY_CONSTITUENT = "constituent-foundry";
+    public static final String DEFAULT_FOUNDRY_RELATION = "relation-foundry";
+    public static final String DEFAULT_FOUNDRY_MORPHOLOGY = "morphology-foundry";
 
     /**
      * db column keys
diff --git a/core/src/main/java/de/ids_mannheim/korap/config/KustvaktConfiguration.java b/core/src/main/java/de/ids_mannheim/korap/config/KustvaktConfiguration.java
index 2d0d720..f4f107f 100644
--- a/core/src/main/java/de/ids_mannheim/korap/config/KustvaktConfiguration.java
+++ b/core/src/main/java/de/ids_mannheim/korap/config/KustvaktConfiguration.java
@@ -71,6 +71,7 @@
     private String passcodeSaltField;
 
     private String default_pos;
+    private String default_morphology;
     private String default_lemma;
     private String default_token;
     private String default_dep;
@@ -95,6 +96,7 @@
     // random code generator
     private String secureRandomAlgorithm;
     private String messageDigestAlgorithm;
+
     
     public KustvaktConfiguration (Properties properties) throws Exception {
         load(properties);
@@ -131,14 +133,15 @@
             queryLanguages.add(querylang.trim().toUpperCase());
 
         default_const =
-                properties.getProperty("default.layer.constituent", "mate");
+                properties.getProperty("default.foundry.constituent", "corenlp");
         default_dep =
-                properties.getProperty("default.layer.dependency", "mate");
-        default_lemma = properties.getProperty("default.layer.lemma", "tt");
+                properties.getProperty("default.foundry.dependency", "malt");
+        default_lemma = properties.getProperty("default.foundry.lemma", "tt");
+        default_morphology = properties.getProperty("default.foundry.morphology", "marmot");
         default_pos =
-                properties.getProperty("default.layer.partOfSpeech", "tt");
+                properties.getProperty("default.foundry.partOfSpeech", "tt");
         default_token =
-                properties.getProperty("default.layer.orthography", "opennlp");
+                properties.getProperty("default.foundry.orthography", "opennlp");
 
         // security configuration
         inactiveTime = TimeUtils.convertTimeToSeconds(
diff --git a/core/src/main/java/de/ids_mannheim/korap/rewrite/CollectionCleanRewrite.java b/core/src/main/java/de/ids_mannheim/korap/rewrite/CollectionCleanRewrite.java
index 6cacd4b..530eb86 100644
--- a/core/src/main/java/de/ids_mannheim/korap/rewrite/CollectionCleanRewrite.java
+++ b/core/src/main/java/de/ids_mannheim/korap/rewrite/CollectionCleanRewrite.java
@@ -1,17 +1,16 @@
 package de.ids_mannheim.korap.rewrite;
 
-import com.fasterxml.jackson.databind.JsonNode;
-import com.fasterxml.jackson.databind.node.ObjectNode;
-import de.ids_mannheim.korap.config.BeanInjectable;
-import de.ids_mannheim.korap.config.ContextHolder;
-import de.ids_mannheim.korap.config.KustvaktConfiguration;
-import de.ids_mannheim.korap.user.User;
-import de.ids_mannheim.korap.utils.JsonUtils;
-import edu.emory.mathcs.backport.java.util.Arrays;
-
 import java.util.Iterator;
 
-/**
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+
+import de.ids_mannheim.korap.config.KustvaktConfiguration;
+import de.ids_mannheim.korap.user.User;
+import edu.emory.mathcs.backport.java.util.Arrays;
+
+/** EM: not used anymore. This rewrite was to remove an empty koral:doc group in operands.
+ * 
  * @author hanl
  * @date 28/07/2015
  */
diff --git a/core/src/main/java/de/ids_mannheim/korap/rewrite/FoundryInject.java b/core/src/main/java/de/ids_mannheim/korap/rewrite/FoundryInject.java
index f682414..9146e5f 100644
--- a/core/src/main/java/de/ids_mannheim/korap/rewrite/FoundryInject.java
+++ b/core/src/main/java/de/ids_mannheim/korap/rewrite/FoundryInject.java
@@ -1,45 +1,28 @@
 package de.ids_mannheim.korap.rewrite;
 
-import java.util.Collection;
+import org.springframework.beans.factory.annotation.Autowired;
 
 import com.fasterxml.jackson.databind.JsonNode;
 
-import de.ids_mannheim.korap.config.BeanInjectable;
-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.rewrite.KoralNode.RewriteIdentifier;
 import de.ids_mannheim.korap.user.User;
-import edu.emory.mathcs.backport.java.util.Collections;
+import de.ids_mannheim.korap.user.UserSettingProcessor;
 
 /**
- * @author hanl
+ * @author hanl, margaretha
  * @date 30/06/2015
  */
-public class FoundryInject implements RewriteTask.IterableRewritePath,
-        BeanInjectable {
+public class FoundryInject implements RewriteTask.IterableRewritePath {
 
-    private Collection userdaos;
-
-
-    public FoundryInject () {
-        this.userdaos = Collections.emptyList();
-    }
-
-
+    @Autowired
+    protected LayerMapper mapper;
+    
     @Override
     public KoralNode rewriteQuery (KoralNode node, KustvaktConfiguration config,
             User user) throws KustvaktException {
-        LayerMapper mapper;
-        // EM: do not use DB
-//        if (user != null && !userdaos.isEmpty()) {
-//            UserDataDbIface dao = BeansFactory.getTypeFactory()
-//                    .getTypeInterfaceBean(userdaos, UserSettings.class);
-//            mapper = new LayerMapper(config, dao.get(user));
-//        }
-//        else
-            mapper = new LayerMapper(config);
-            
+        
         if (node.get("@type").equals("koral:span")) {
             if (!node.isMissingNode("/wrap")){
                 node = node.at("/wrap");
@@ -49,18 +32,23 @@
         }
         else if (node.get("@type").equals("koral:term") && !node.has("foundry")) {
             String layer;
-            if (node.has("layer"))
+            if (node.has("layer")){
                 layer = node.get("layer");
-            else
+            }
+            else{
                 layer = node.get("key");
-            String foundry = mapper.findFoundry(layer);
+            }
+            UserSettingProcessor settingProcessor = null;
+            if (user!=null){
+                settingProcessor = user.getUserSettingProcessor();
+            }
+            String foundry = mapper.findFoundry(layer, settingProcessor);
             if (foundry != null)
                 node.put("foundry", foundry);
         }
         return node;
     }
 
-
     @Override
     public String path () {
         return "query";
@@ -71,10 +59,4 @@
     public JsonNode rewriteResult (KoralNode node) {
         return null;
     }
-
-
-    @Override
-    public <T extends ContextHolder> void insertBeans (T beans) {
-        this.userdaos = beans.getUserDataProviders();
-    }
 }
diff --git a/core/src/main/java/de/ids_mannheim/korap/rewrite/LayerMapper.java b/core/src/main/java/de/ids_mannheim/korap/rewrite/LayerMapper.java
index 672f7e7..a8a81bd 100644
--- a/core/src/main/java/de/ids_mannheim/korap/rewrite/LayerMapper.java
+++ b/core/src/main/java/de/ids_mannheim/korap/rewrite/LayerMapper.java
@@ -1,30 +1,30 @@
 package de.ids_mannheim.korap.rewrite;
 
-import de.ids_mannheim.korap.config.KustvaktConfiguration;
-import de.ids_mannheim.korap.config.Attributes;
-import de.ids_mannheim.korap.user.Userdata;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
 
-/**
- * @author hanl
+import de.ids_mannheim.korap.config.Attributes;
+import de.ids_mannheim.korap.config.KustvaktConfiguration;
+import de.ids_mannheim.korap.user.UserSettingProcessor;
+
+/** EM:
+ *  <ul>
+ *  <li> Added default morphology foundry </li>
+ *  <li> Made this class as a spring component</li>
+ *  </ul>
+ * @author hanl, margaretha
  * @date 14/10/2014
  */
+@Component
 public class LayerMapper {
 
-    private Userdata settings;
+    @Autowired
     private KustvaktConfiguration config;
 
-
-    public LayerMapper (KustvaktConfiguration config, Userdata settings) {
-        this.settings = settings;
-        this.config = config;
+    public String findFoundry (String layer) {
+        return findFoundry(layer, null);
     }
 
-
-    public LayerMapper (KustvaktConfiguration config) {
-        this.config = config;
-    }
-
-
     /**
      * find foundry entry in settings specific settings. Includes a
      * call to #translateLayer to get the
@@ -35,23 +35,27 @@
      */
 
     //todo: make mapping configurable!
-    public String findFoundry (String layer) {
+    public String findFoundry (String layer, UserSettingProcessor settings) {
         if (settings != null) {
             switch (translateLayer(layer.toLowerCase().trim())) {
                 case "d":
                     return (String) settings
-                            .get(Attributes.DEFAULT_REL_FOUNDRY);
+                            .get(Attributes.DEFAULT_FOUNDRY_RELATION);
                 case "c":
                     return (String) settings
-                            .get(Attributes.DEFAULT_CONST_FOUNDRY);
+                            .get(Attributes.DEFAULT_FOUNDRY_CONSTITUENT);
                 case "pos":
                     return (String) settings
-                            .get(Attributes.DEFAULT_POS_FOUNDRY);
+                            .get(Attributes.DEFAULT_FOUNDRY_POS);
                 case "lemma":
                     return (String) settings
-                            .get(Attributes.DEFAULT_LEMMA_FOUNDRY);
+                            .get(Attributes.DEFAULT_FOUNDRY_LEMMA);
                 case "surface":
                     return "opennlp";
+                // EM: added
+                case "morphology":
+                    return (String) settings
+                            .get(Attributes.DEFAULT_FOUNDRY_MORPHOLOGY);    
                 default:
                     // if the layer is not in this specific listing, assume a default layer
                     // like orth or other tokenization layers
@@ -68,6 +72,8 @@
                     return config.getDefault_pos();
                 case "lemma":
                     return config.getDefault_lemma();
+                case "morphology":
+                    return config.getDefault_morphology();
                 case "surface":
                     return config.getDefault_token();
                     // refers to "structure" and is used for paragraphs or sentence boundaries
@@ -90,7 +96,8 @@
         //            case "lemma":
         //                return "l";
             case "m":
-                return "msd";
+                return "morphology"; // EM: changed msd to morphology
+//                return "msd";
                 //todo the orth layer does not need a foundry entry
             case "orth":
                 return "surface";
diff --git a/core/src/main/java/de/ids_mannheim/korap/rewrite/RewriteHandler.java b/core/src/main/java/de/ids_mannheim/korap/rewrite/RewriteHandler.java
index ddd7538..d674ba6 100644
--- a/core/src/main/java/de/ids_mannheim/korap/rewrite/RewriteHandler.java
+++ b/core/src/main/java/de/ids_mannheim/korap/rewrite/RewriteHandler.java
@@ -6,6 +6,7 @@
 import java.util.HashSet;
 import java.util.Iterator;
 import java.util.LinkedHashSet;
+import java.util.List;
 import java.util.Map;
 import java.util.Set;
 
@@ -15,8 +16,6 @@
 
 import com.fasterxml.jackson.databind.JsonNode;
 
-import de.ids_mannheim.korap.config.BeanInjectable;
-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.user.User;
@@ -39,21 +38,25 @@
     private Set<Class> failed_task_registration;
     @Autowired
     private KustvaktConfiguration config;
-    private ContextHolder beans;
 
-
+    public RewriteHandler (List<RewriteTask> rewriteTasks) {
+        this();
+        for (RewriteTask t : rewriteTasks){
+            addProcessor(t);
+        }
+    }
+    
+    // EM: for testing
     public RewriteHandler (KustvaktConfiguration config) {
         this();
-        this.config = config;
+        this.config=config;
     }
 
-
     public RewriteHandler () {
         this.node_processors = new HashSet<>();
         this.token_node_processors = new HashSet<>();
         this.query_processors = new LinkedHashSet<>();
         this.failed_task_registration = new HashSet<>();
-        this.beans = null;
     }
 
     public Set getFailedProcessors () {
@@ -99,6 +102,7 @@
      * @return boolean if rewriter class was successfully added to
      *         rewrite handler!
      */
+    @Deprecated
     public boolean add (Class<? extends RewriteTask> rewriter) {
         RewriteTask task;
         try {
@@ -244,10 +248,10 @@
                     jlog.debug("on processor: " + task.getClass().toString());
                 }
 
-                if (RewriteHandler.this.beans != null
-                        && task instanceof BeanInjectable)
-                    ((BeanInjectable) task)
-                            .insertBeans(RewriteHandler.this.beans);
+//                if (RewriteHandler.this.beans != null
+//                        && task instanceof BeanInjectable)
+//                    ((BeanInjectable) task)
+//                            .insertBeans(RewriteHandler.this.beans);
 
                 if (task instanceof RewriteTask.IterableRewritePath) {
                     RewriteTask.IterableRewritePath rw = (RewriteTask.IterableRewritePath) task;
@@ -302,7 +306,4 @@
 
     }
 
-    public void defaultRewriteConstraints () {
-        this.add(FoundryInject.class);
-    }
 }
diff --git a/core/src/main/java/de/ids_mannheim/korap/service/SearchService.java b/core/src/main/java/de/ids_mannheim/korap/service/SearchService.java
index 10414bf..fa6a680 100644
--- a/core/src/main/java/de/ids_mannheim/korap/service/SearchService.java
+++ b/core/src/main/java/de/ids_mannheim/korap/service/SearchService.java
@@ -52,8 +52,6 @@
 
     @PostConstruct
     private void doPostConstruct () {
-        this.rewriteHandler.defaultRewriteConstraints();
-
         UriBuilder builder = UriBuilder.fromUri("http://10.0.10.13").port(9997);
         this.graphDBhandler = new ClientsHandler(builder.build());
     }
diff --git a/core/src/main/java/de/ids_mannheim/korap/user/KorAPUser.java b/core/src/main/java/de/ids_mannheim/korap/user/KorAPUser.java
index d25097f..8f51378 100644
--- a/core/src/main/java/de/ids_mannheim/korap/user/KorAPUser.java
+++ b/core/src/main/java/de/ids_mannheim/korap/user/KorAPUser.java
@@ -20,7 +20,7 @@
     private Long URIExpiration;
 
 
-    protected KorAPUser (String username) {
+    public KorAPUser (String username) {
         super(username, 0);
         this.URIFragment = "";
         this.URIExpiration = 0L;
diff --git a/core/src/main/java/de/ids_mannheim/korap/user/User.java b/core/src/main/java/de/ids_mannheim/korap/user/User.java
index 7aa4f57..eb6cf53 100644
--- a/core/src/main/java/de/ids_mannheim/korap/user/User.java
+++ b/core/src/main/java/de/ids_mannheim/korap/user/User.java
@@ -1,7 +1,6 @@
 package de.ids_mannheim.korap.user;
 
 import java.io.Serializable;
-import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
@@ -46,7 +45,7 @@
     @Setter(AccessLevel.PRIVATE)
     private List<UserQuery> queries;
 
-    private List<Userdata> userdata;
+    private UserSettingProcessor userSettingProcessor;
 
 //    private boolean isSystemAdmin;
 
@@ -78,7 +77,6 @@
         this.isAccountLocked = false;
         this.username = "";
         this.id = -1;
-        this.userdata = new ArrayList<>();
         this.location 		= Location.EXTERN;
         this.corpusAccess 	= CorpusAccess.FREE;
     }
@@ -105,19 +103,6 @@
         return this.fields.get(cl);
     }
 
-
-    public void addUserData (Userdata data) {
-        if (data != null) {
-            for (Userdata d : this.userdata) {
-                // already has an object of that type!
-                if (d.getClass().equals(data.getClass()))
-                    return;
-            }
-            userdata.add(data);
-        }
-    }
-
-
     public void setId (Integer id) {
         this.id = id;
         //        if (this.settings != null)
diff --git a/core/src/main/java/de/ids_mannheim/korap/user/UserSettingProcessor.java b/core/src/main/java/de/ids_mannheim/korap/user/UserSettingProcessor.java
index df11e40..57b5e4b 100644
--- a/core/src/main/java/de/ids_mannheim/korap/user/UserSettingProcessor.java
+++ b/core/src/main/java/de/ids_mannheim/korap/user/UserSettingProcessor.java
@@ -30,10 +30,10 @@
 
     @Override
     public String[] defaultFields () {
-        return new String[] { Attributes.DEFAULT_REL_FOUNDRY,
-                Attributes.DEFAULT_POS_FOUNDRY,
-                Attributes.DEFAULT_CONST_FOUNDRY,
-                Attributes.DEFAULT_LEMMA_FOUNDRY, Attributes.QUERY_LANGUAGE,
+        return new String[] { Attributes.DEFAULT_FOUNDRY_RELATION,
+                Attributes.DEFAULT_FOUNDRY_POS,
+                Attributes.DEFAULT_FOUNDRY_CONSTITUENT,
+                Attributes.DEFAULT_FOUNDRY_LEMMA, Attributes.QUERY_LANGUAGE,
                 Attributes.PAGE_LENGTH };
     }
 }
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
diff --git a/lite/src/main/resources/lite-config.xml b/lite/src/main/resources/lite-config.xml
index e120e9d..a180563 100644
--- a/lite/src/main/resources/lite-config.xml
+++ b/lite/src/main/resources/lite-config.xml
@@ -13,7 +13,9 @@
 
 
 	<context:component-scan
-		base-package="de.ids_mannheim.korap.web.filter, de.ids_mannheim.korap.web.utils,
+		base-package="de.ids_mannheim.korap.rewrite, 
+	    de.ids_mannheim.korap.web.filter, 
+		de.ids_mannheim.korap.web.utils,
 		de.ids_mannheim.korap.authentication.http" />
 	<context:annotation-config />
 
@@ -168,8 +170,14 @@
 	<bean id="annotationConverter" class="de.ids_mannheim.korap.dto.converter.AnnotationConverter" />
 
 	<!-- Rewrite -->
+	<bean id="foundryInject" class="de.ids_mannheim.korap.rewrite.FoundryInject" />
+	
+	<util:list id="rewriteTasks" value-type="de.ids_mannheim.korap.rewrite.RewriteTask">
+		<ref bean="foundryInject"/>
+	</util:list>
+	
 	<bean id="rewriteHandler" class="de.ids_mannheim.korap.rewrite.RewriteHandler">
-		<constructor-arg ref="config" />
+		<constructor-arg ref="rewriteTasks" />
 	</bean>
 
 
diff --git a/lite/src/test/resources/test-config.xml b/lite/src/test/resources/test-config.xml
index 434828f..a012e26 100644
--- a/lite/src/test/resources/test-config.xml
+++ b/lite/src/test/resources/test-config.xml
@@ -13,7 +13,9 @@
 
 
 	<context:component-scan
-		base-package="de.ids_mannheim.korap.web.filter, de.ids_mannheim.korap.web.utils,
+		base-package="de.ids_mannheim.korap.rewrite,
+		de.ids_mannheim.korap.web.filter, 
+		de.ids_mannheim.korap.web.utils,
 		de.ids_mannheim.korap.authentication.http" />
 	<context:annotation-config />
 
@@ -133,9 +135,8 @@
 	</bean>
 
 	<!-- Filters -->
-<!-- 	<bean id="APIVersionFilter" class="de.ids_mannheim.korap.web.APIVersionFilter"
-		scope="singleton" />
- -->
+	<!-- <bean id="APIVersionFilter" class="de.ids_mannheim.korap.web.APIVersionFilter" 
+		scope="singleton" /> -->
 	<!-- Authentication -->
 	<bean id="authenticationManager"
 		class="de.ids_mannheim.korap.authentication.DummyAuthenticationManager" />
@@ -166,12 +167,19 @@
 	<bean id="annotationConverter" class="de.ids_mannheim.korap.dto.converter.AnnotationConverter" />
 
 	<!-- Rewrite -->
+	<bean id="foundryInject" class="de.ids_mannheim.korap.rewrite.FoundryInject" />
+
+	<util:list id="rewriteTasks" value-type="de.ids_mannheim.korap.rewrite.RewriteTask">
+		<ref bean="foundryInject" />
+	</util:list>
+
 	<bean id="rewriteHandler" class="de.ids_mannheim.korap.rewrite.RewriteHandler">
-		<constructor-arg ref="config" />
+		<constructor-arg ref="rewriteTasks" />
 	</bean>
 
 
 
+
 	<bean id="kustvakt_auditing"
 		class="de.ids_mannheim.korap.interfaces.defaults.DefaultAuditing">
 	</bean>