Added annotation parser and implemented key-value structure.

Change-Id: I8244f81dda48f6c4a002b13d74fc79a3066eac06
diff --git a/full/src/main/java/de/ids_mannheim/korap/annotation/AnnotationParser.java b/full/src/main/java/de/ids_mannheim/korap/annotation/AnnotationParser.java
new file mode 100644
index 0000000..865f7cf
--- /dev/null
+++ b/full/src/main/java/de/ids_mannheim/korap/annotation/AnnotationParser.java
@@ -0,0 +1,232 @@
+package de.ids_mannheim.korap.annotation;
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.Set;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import org.apache.logging.log4j.LogManager;
+import org.apache.logging.log4j.Logger;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+
+import de.ids_mannheim.korap.constant.AnnotationType;
+import de.ids_mannheim.korap.dao.AnnotationDao;
+import de.ids_mannheim.korap.entity.Annotation;
+import de.ids_mannheim.korap.entity.AnnotationKey;
+import de.ids_mannheim.korap.entity.AnnotationLayer;
+
+@Component
+public class AnnotationParser {
+
+    private Logger log = LogManager.getLogger(AnnotationDao.class);
+
+    public static final Pattern quotePattern = Pattern.compile("\"([^\"]*)\"");
+
+    @Autowired
+    private AnnotationDao annotationDao;
+
+    private Annotation foundry = null;
+    private AnnotationLayer layer = null;
+    private AnnotationKey key = null;
+
+    private Set<AnnotationKey> keys = new HashSet<>();
+    private Set<Annotation> values = new HashSet<>();
+
+    public void run () throws IOException {
+        String dir = "annotation-scripts/foundries";
+        if (dir.isEmpty()) return;
+
+        File d = new File(dir);
+        if (!d.isDirectory()) {
+            throw new IOException("Directory " + dir + " is not valid");
+        }
+
+        for (File file : d.listFiles()) {
+            if (!file.exists()) {
+                throw new IOException("File " + file + " is not found.");
+            }
+            readFile(file);
+        }
+    }
+
+    private void readFile (File file) throws IOException {
+        BufferedReader br = new BufferedReader(
+                new InputStreamReader(new FileInputStream(file)));
+
+        foundry = null;
+
+        String line, annotationCode = "", annotationType = "";
+        Matcher m;
+        ArrayList<String> array;
+        while ((line = br.readLine()) != null) {
+            line = line.trim();
+            if (line.startsWith("ah")) {
+                m = quotePattern.matcher(line);
+                if (m.find()) {
+                    annotationCode = m.group(1);
+                    annotationType = computeAnnotationType(annotationCode);
+                }
+                m.reset();
+            }
+            else if (line.startsWith("];")) {
+                if (!keys.isEmpty()) {
+                    layer.setKeys(keys);
+                    annotationDao.updateAnnotationLayer(layer);
+                }
+                if (!values.isEmpty()) {
+                    key.setValues(values);
+                    annotationDao.updateAnnotationKey(key);
+                }
+                keys.clear();
+                values.clear();
+                layer = null;
+                key = null;
+            }
+            else if (line.startsWith("[")) {
+                array = computeValues(line);
+                parseArray(annotationCode, annotationType, array);
+            }
+
+        }
+        br.close();
+    }
+
+    public static ArrayList<String> computeValues (String line) {
+        ArrayList<String> values;
+        Matcher m = quotePattern.matcher(line);
+        values = new ArrayList<String>();
+        while (m.find()) {
+            values.add(m.group(1));
+        }
+        return values;
+    }
+
+    private void parseArray (String annotationCode, String annotationType,
+            ArrayList<String> array) {
+        if (annotationType.equals(AnnotationType.FOUNDRY)) {
+            String code = array.get(1).substring(0, array.get(1).length() - 1);
+            foundry = retrieveOrCreateAnnotation(code, AnnotationType.FOUNDRY,
+                    null, array.get(0));
+        }
+        else if (annotationType.equals(AnnotationType.LAYER)) {
+            String code = array.get(1);
+            if (code.endsWith("=")) {
+                code = code.substring(0, code.length() - 1);
+            }
+            Annotation layer = retrieveOrCreateAnnotation(code, annotationType,
+                    null, array.get(0));
+            try {
+                annotationDao.createAnnotationLayer(foundry, layer);
+            }
+            catch (Exception e) {
+                log.debug("Duplicate annotation layer: " + foundry.getCode()
+                        + "/" + layer.getCode());
+            }
+        }
+        else if (annotationType.equals(AnnotationType.KEY)) {
+            if (layer == null) {
+                computeLayer(annotationCode);
+            }
+            String code = array.get(1);
+            if (code.endsWith("=") || code.endsWith(":")) {
+                code = code.substring(0, code.length() - 1);
+            }
+            Annotation annotation = null;
+            if (array.size() == 2) {
+                annotation = retrieveOrCreateAnnotation(code, annotationType,
+                        null, array.get(0));
+            }
+            else if (array.size() == 3) {
+                annotation = retrieveOrCreateAnnotation(code, annotationType,
+                        array.get(1), array.get(2));
+            }
+            if (annotation != null) {
+                AnnotationKey annotationKey =
+                        annotationDao.retrieveAnnotationKey(layer, annotation);
+                if (annotationKey == null) {
+                    annotationDao.createAnnotationKey(layer, annotation);
+                }
+                this.keys.add(annotationKey);
+            }
+        }
+        else if (annotationType.equals(AnnotationType.VALUE)) {
+            if (this.key == null) {
+                computeKey(annotationCode);
+            }
+            String valueCode = array.get(0);
+            Annotation value = retrieveOrCreateAnnotation(valueCode,
+                    AnnotationType.VALUE, array.get(1), array.get(2));
+            if (value != null) {
+                values.add(value);
+            }
+        }
+    }
+
+    private void computeKey (String code) {
+        String[] codes = code.split("=");
+        if (codes.length > 1) {
+            computeLayer(codes[0]);
+            String keyCode = codes[1];
+            if (keyCode.endsWith(":") || keyCode.endsWith("-")) {
+                keyCode = keyCode.substring(0, keyCode.length() - 1);
+            }
+            Annotation key = annotationDao.retrieveAnnotation(keyCode,
+                    AnnotationType.KEY);
+            this.key = annotationDao.retrieveAnnotationKey(layer, key);
+        }
+
+    }
+
+    private void computeLayer (String code) {
+        String[] codes = code.split("/");
+        if (codes.length > 1) {
+            String layerCode = codes[1];
+            if (layerCode.endsWith("=")) {
+                layerCode = layerCode.substring(0, layerCode.length() - 1);
+            }
+            this.layer =
+                    annotationDao.retrieveAnnotationLayer(codes[0], layerCode);
+            if (layer == null) {
+                log.warn("Layer is null for " + code);
+            }
+        }
+    }
+
+    private Annotation retrieveOrCreateAnnotation (String code, String type,
+            String text, String description) {
+        Annotation annotation = annotationDao.retrieveAnnotation(code, type);
+        if (annotation == null) {
+            annotation = annotationDao.createAnnotation(code, type, text,
+                    description);
+        }
+        return annotation;
+    }
+
+    private String computeAnnotationType (String code) {
+        String[] codes = code.split("/");
+        if (codes.length == 1) {
+            if (codes[0].equals("-")) {
+                return AnnotationType.FOUNDRY;
+            }
+            return AnnotationType.LAYER;
+        }
+        else if (codes.length == 2) {
+            if (codes[1].endsWith(":") || codes[1].endsWith("-")) {
+                return AnnotationType.VALUE;
+            }
+            else {
+                return AnnotationType.KEY;
+            }
+        }
+
+        return "unknown";
+    }
+
+}
diff --git a/full/src/main/java/de/ids_mannheim/korap/annotation/ArrayVariables.java b/full/src/main/java/de/ids_mannheim/korap/annotation/ArrayVariables.java
new file mode 100644
index 0000000..55f476a
--- /dev/null
+++ b/full/src/main/java/de/ids_mannheim/korap/annotation/ArrayVariables.java
@@ -0,0 +1,94 @@
+package de.ids_mannheim.korap.annotation;
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+
+import de.ids_mannheim.korap.constant.AnnotationType;
+import de.ids_mannheim.korap.entity.Annotation;
+
+/**
+ * Helper class to parse annotation scripts variables. It prints out
+ * corenlp constituency layer for each negranodes.
+ * 
+ * @author margaretha
+ *
+ */
+public class ArrayVariables {
+
+    public static HashMap<String, List<Annotation>> annotationMap =
+            new HashMap<>();
+
+    public static void main (String[] args) throws IOException {
+        ArrayVariables variables = new ArrayVariables();
+        variables.extractVariables();
+
+        List<Annotation> negranodes = annotationMap.get("negranodes");
+        for (Annotation n : negranodes) {
+            System.out.println("ah[\"corenlp/c=" + n.getCode() + "-\"] = [");
+            int i = 1;
+            List<Annotation> negraedges = annotationMap.get("negraedges");
+            for (Annotation edge : negraedges) {
+                System.out.print(
+                        "  [\"" + edge.getCode() + "\", \"" + edge.getText()
+                                + "\", \"" + edge.getDescription() + "\"]");
+                if (i < negraedges.size()) {
+                    System.out.println(",");
+                }
+                else {
+                    System.out.println();
+                }
+                i++;
+            }
+            System.out.println("];");
+            System.out.println();
+        }
+    }
+
+    public void extractVariables () throws IOException {
+        String dir = "annotation-scripts/variables";
+        if (dir.isEmpty()) return;
+
+        File d = new File(dir);
+        if (!d.isDirectory()) {
+            throw new IOException("Directory " + dir + " is not valid");
+        }
+
+        for (File file : d.listFiles()) {
+            if (!file.exists()) {
+                throw new IOException("File " + file + " is not found.");
+            }
+            readFile(file);
+        }
+
+    }
+
+    private void readFile (File file) throws IOException {
+        BufferedReader br = new BufferedReader(
+                new InputStreamReader(new FileInputStream(file)));
+
+        String line;
+        ArrayList<String> values;
+        List<Annotation> annotations = new ArrayList<>();
+        while ((line = br.readLine()) != null) {
+            line = line.trim();
+            if (line.startsWith("[")) {
+                values = AnnotationParser.computeValues(line);
+
+                Annotation annotation = new Annotation(values.get(0),
+                        AnnotationType.VALUE, values.get(1), values.get(2));
+                annotations.add(annotation);
+            }
+        }
+        br.close();
+
+        String filename = file.getName();
+        filename = filename.substring(0, filename.length() - 3);
+        annotationMap.put(filename, annotations);
+    }
+}
diff --git a/full/src/main/java/de/ids_mannheim/korap/config/FullConfiguration.java b/full/src/main/java/de/ids_mannheim/korap/config/FullConfiguration.java
index 296be80..bbed39c 100644
--- a/full/src/main/java/de/ids_mannheim/korap/config/FullConfiguration.java
+++ b/full/src/main/java/de/ids_mannheim/korap/config/FullConfiguration.java
@@ -113,7 +113,7 @@
         setRSAKeys(properties);
         
         setNamedVCPath(properties
-                .getProperty("krill.namedVC", "vc"));
+                .getProperty("krill.namedVC", ""));
     }
 
     private void setSecurityConfiguration (Properties properties) {
diff --git a/full/src/main/java/de/ids_mannheim/korap/config/Initializator.java b/full/src/main/java/de/ids_mannheim/korap/config/Initializator.java
index 85360c7..f0cace9 100644
--- a/full/src/main/java/de/ids_mannheim/korap/config/Initializator.java
+++ b/full/src/main/java/de/ids_mannheim/korap/config/Initializator.java
@@ -5,6 +5,7 @@
 
 import org.springframework.beans.factory.annotation.Autowired;
 
+import de.ids_mannheim.korap.annotation.AnnotationParser;
 import de.ids_mannheim.korap.exceptions.KustvaktException;
 import de.ids_mannheim.korap.oauth2.constant.OAuth2Scope;
 import de.ids_mannheim.korap.oauth2.dao.AccessScopeDao;
@@ -23,6 +24,8 @@
     private AccessScopeDao accessScopeDao;
     @Autowired
     private NamedVCLoader loader;
+    @Autowired
+    private AnnotationParser annotationParser;
 
     public Initializator () {}
 
@@ -31,6 +34,13 @@
         loader.loadVCToCache();
     }
 
+    public void initAnnotation ()
+            throws IOException, QueryException, KustvaktException {
+        setInitialAccessScope();
+        loader.loadVCToCache();
+        annotationParser.run();
+    }
+
     public void initTest () {
         setInitialAccessScope();
     }
diff --git a/full/src/main/java/de/ids_mannheim/korap/config/NamedVCLoader.java b/full/src/main/java/de/ids_mannheim/korap/config/NamedVCLoader.java
index 21216a8..1e4c4c4 100644
--- a/full/src/main/java/de/ids_mannheim/korap/config/NamedVCLoader.java
+++ b/full/src/main/java/de/ids_mannheim/korap/config/NamedVCLoader.java
@@ -48,6 +48,8 @@
             throws IOException, QueryException, KustvaktException {
 
         String dir = config.getNamedVCPath();
+        if (dir.isEmpty()) return;
+        
         File d = new File(dir);
         if (!d.isDirectory()) {
             throw new IOException("Directory " + dir + " is not valid");
diff --git a/full/src/main/java/de/ids_mannheim/korap/constant/AnnotationType.java b/full/src/main/java/de/ids_mannheim/korap/constant/AnnotationType.java
new file mode 100644
index 0000000..560d401
--- /dev/null
+++ b/full/src/main/java/de/ids_mannheim/korap/constant/AnnotationType.java
@@ -0,0 +1,8 @@
+package de.ids_mannheim.korap.constant;
+
+public class AnnotationType {
+    public static String FOUNDRY = "foundry";
+    public static String LAYER = "layer";
+    public static String KEY = "key";
+    public static String VALUE = "value";
+}
diff --git a/full/src/main/java/de/ids_mannheim/korap/dao/AnnotationDao.java b/full/src/main/java/de/ids_mannheim/korap/dao/AnnotationDao.java
index 22f2f37..ef54fda 100644
--- a/full/src/main/java/de/ids_mannheim/korap/dao/AnnotationDao.java
+++ b/full/src/main/java/de/ids_mannheim/korap/dao/AnnotationDao.java
@@ -3,6 +3,7 @@
 import java.util.List;
 
 import javax.persistence.EntityManager;
+import javax.persistence.NoResultException;
 import javax.persistence.PersistenceContext;
 import javax.persistence.Query;
 import javax.persistence.criteria.CriteriaBuilder;
@@ -11,11 +12,17 @@
 import javax.persistence.criteria.Root;
 
 import org.springframework.stereotype.Repository;
+import org.springframework.transaction.annotation.Transactional;
 
-import de.ids_mannheim.korap.entity.AnnotationPair;
-import de.ids_mannheim.korap.entity.AnnotationPair_;
+import de.ids_mannheim.korap.constant.AnnotationType;
+import de.ids_mannheim.korap.entity.Annotation;
+import de.ids_mannheim.korap.entity.AnnotationKey;
+import de.ids_mannheim.korap.entity.AnnotationKey_;
+import de.ids_mannheim.korap.entity.AnnotationLayer;
+import de.ids_mannheim.korap.entity.AnnotationLayer_;
 import de.ids_mannheim.korap.entity.Annotation_;
-
+import de.ids_mannheim.korap.exceptions.KustvaktException;
+import de.ids_mannheim.korap.utils.ParameterChecker;
 
 /**
  * AnnotationDao manages SQL queries regarding annotations including
@@ -25,31 +32,30 @@
  *
  */
 @Repository
+@Transactional
 public class AnnotationDao {
 
     @PersistenceContext
     private EntityManager entityManager;
 
-
     /**
      * Retrieves all foundry-layer pairs.
      * 
      * @return a list of foundry-layer pairs.
      */
     @SuppressWarnings("unchecked")
-    public List<AnnotationPair> getAllFoundryLayerPairs () {
+    public List<AnnotationLayer> getAllFoundryLayerPairs () {
         CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
-        CriteriaQuery<AnnotationPair> query =
-                criteriaBuilder.createQuery(AnnotationPair.class);
-        Root<AnnotationPair> annotationPair = query.from(AnnotationPair.class);
-        annotationPair.fetch(AnnotationPair_.annotation1);
-        annotationPair.fetch(AnnotationPair_.annotation2);
-        query.select(annotationPair);
+        CriteriaQuery<AnnotationLayer> query =
+                criteriaBuilder.createQuery(AnnotationLayer.class);
+        Root<AnnotationLayer> layer = query.from(AnnotationLayer.class);
+        layer.fetch(AnnotationLayer_.foundry);
+        layer.fetch(AnnotationLayer_.layer);
+        query.select(layer);
         Query q = entityManager.createQuery(query);
         return q.getResultList();
     }
 
-
     /**
      * Retrieves foundry-layer pairs and their values for the given
      * foundry and layer. If layer is empty, retrieves data for all
@@ -63,33 +69,35 @@
      * @return a list of foundry-layer pairs.
      */
     @SuppressWarnings("unchecked")
-    public List<AnnotationPair> getAnnotationDescriptions (String foundry,
+    public List<AnnotationLayer> getAnnotationDescriptions (String foundry,
             String layer) {
 
         CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
         CriteriaQuery<Object> query = criteriaBuilder.createQuery();
-        Root<AnnotationPair> annotationPair = query.from(AnnotationPair.class);
-        annotationPair.fetch(AnnotationPair_.annotation1);
-        annotationPair.fetch(AnnotationPair_.annotation2);
-        annotationPair.fetch(AnnotationPair_.values);
+        Root<AnnotationLayer> annotationPair =
+                query.from(AnnotationLayer.class);
+        annotationPair.fetch(AnnotationLayer_.foundry);
+        annotationPair.fetch(AnnotationLayer_.layer);
+        annotationPair.fetch(AnnotationLayer_.keys);
 
-        // EM: Hibernate bug in join n:m (see AnnotationPair.values). 
-        // There should not be any redundant AnnotationPair. 
-        // The redundancy can be also avoided with fetch=FetchType.EAGER 
-        // because Hibernate does 2 selects.  
+        // EM: Hibernate bug in join n:m (see AnnotationPair.values).
+        // There should not be any redundant AnnotationPair.
+        // The redundancy can be also avoided with
+        // fetch=FetchType.EAGER
+        // because Hibernate does 2 selects.
         query.distinct(true);
         query = query.select(annotationPair);
 
         if (!foundry.isEmpty()) {
             Predicate foundryPredicate = criteriaBuilder.equal(annotationPair
-                    .get(AnnotationPair_.annotation1).get(Annotation_.code),
+                    .get(AnnotationLayer_.foundry).get(Annotation_.code),
                     foundry);
             if (layer.isEmpty() || layer.equals("*")) {
                 query.where(foundryPredicate);
             }
             else {
                 Predicate layerPredicate = criteriaBuilder.equal(annotationPair
-                        .get(AnnotationPair_.annotation2).get(Annotation_.code),
+                        .get(AnnotationLayer_.layer).get(Annotation_.code),
                         layer);
                 Predicate andPredicate =
                         criteriaBuilder.and(foundryPredicate, layerPredicate);
@@ -100,4 +108,108 @@
         Query q = entityManager.createQuery(query);
         return q.getResultList();
     }
+
+    public Annotation retrieveAnnotation (String code, String type) {
+        CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
+        CriteriaQuery<Annotation> query =
+                criteriaBuilder.createQuery(Annotation.class);
+
+        Root<Annotation> annotation = query.from(Annotation.class);
+        Predicate predicates = criteriaBuilder.and(
+                criteriaBuilder.equal(annotation.get(Annotation_.code), code),
+                criteriaBuilder.equal(annotation.get(Annotation_.type), type));
+        query.select(annotation).where(predicates);
+        Query q = entityManager.createQuery(query);
+        try {
+            return (Annotation) q.getSingleResult();
+        }
+        catch (NoResultException e) {
+            return null;
+        }
+    }
+
+    public AnnotationLayer retrieveAnnotationLayer (String foundry,
+            String layer) {
+        Annotation ann1 = retrieveAnnotation(foundry, AnnotationType.FOUNDRY);
+        Annotation ann2 = retrieveAnnotation(layer, AnnotationType.LAYER);
+
+        CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
+        CriteriaQuery<AnnotationLayer> query =
+                criteriaBuilder.createQuery(AnnotationLayer.class);
+
+        Root<AnnotationLayer> annotation = query.from(AnnotationLayer.class);
+        Predicate predicates = criteriaBuilder.and(
+                criteriaBuilder.equal(annotation.get(AnnotationLayer_.foundry),
+                        ann1),
+                criteriaBuilder.equal(annotation.get(AnnotationLayer_.layer),
+                        ann2));
+        query.select(annotation).where(predicates);
+        Query q = entityManager.createQuery(query);
+        try {
+            return (AnnotationLayer) q.getSingleResult();
+        }
+        catch (NoResultException e) {
+            return null;
+        }
+
+    }
+
+    public Annotation createAnnotation (String code, String type, String text,
+            String description) {
+        Annotation ann = new Annotation(code, type, text, description);
+        entityManager.persist(ann);
+        return ann;
+    }
+
+    public AnnotationLayer createAnnotationLayer (Annotation foundry,
+            Annotation layer) throws KustvaktException {
+        ParameterChecker.checkObjectValue(foundry, "foundry");
+        ParameterChecker.checkObjectValue(layer, "layer");
+
+        AnnotationLayer annotationLayer = new AnnotationLayer();
+        annotationLayer.setFoundryId(foundry.getId());
+        annotationLayer.setLayerId(layer.getId());
+        annotationLayer.setDescription(
+                foundry.getDescription() + " " + layer.getDescription());
+        entityManager.persist(annotationLayer);
+        return annotationLayer;
+    }
+
+    public void updateAnnotationLayer (AnnotationLayer layer) {
+        entityManager.merge(layer);
+    }
+
+    public void updateAnnotationKey (AnnotationKey key) {
+        entityManager.merge(key);
+    }
+
+    public AnnotationKey createAnnotationKey (AnnotationLayer layer,
+            Annotation key) {
+        AnnotationKey annotation =
+                new AnnotationKey(layer.getId(), key.getId());
+        entityManager.persist(annotation);
+        return annotation;
+    }
+
+    public AnnotationKey retrieveAnnotationKey (AnnotationLayer layer,
+            Annotation key) {
+
+        CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
+        CriteriaQuery<AnnotationKey> query =
+                criteriaBuilder.createQuery(AnnotationKey.class);
+
+        Root<AnnotationKey> annotation = query.from(AnnotationKey.class);
+        Predicate predicates = criteriaBuilder.and(
+                criteriaBuilder.equal(annotation.get(AnnotationKey_.layer),
+                        layer),
+                criteriaBuilder.equal(annotation.get(AnnotationKey_.key), key));
+        query.select(annotation).where(predicates);
+        Query q = entityManager.createQuery(query);
+        try {
+            return (AnnotationKey) q.getSingleResult();
+        }
+        catch (NoResultException e) {
+            return null;
+        }
+    }
 }
diff --git a/full/src/main/java/de/ids_mannheim/korap/dto/FoundryDto.java b/full/src/main/java/de/ids_mannheim/korap/dto/FoundryDto.java
index 4d3ea6d..aa6ef2f 100644
--- a/full/src/main/java/de/ids_mannheim/korap/dto/FoundryDto.java
+++ b/full/src/main/java/de/ids_mannheim/korap/dto/FoundryDto.java
@@ -3,6 +3,12 @@
 import java.util.List;
 import java.util.Map;
 
+import org.codehaus.jackson.map.annotate.JsonSerialize;
+import org.codehaus.jackson.map.annotate.JsonSerialize.Inclusion;
+
+import com.fasterxml.jackson.annotation.JsonInclude;
+import com.fasterxml.jackson.annotation.JsonInclude.Include;
+
 import lombok.Getter;
 import lombok.Setter;
 
@@ -15,6 +21,8 @@
  */
 @Getter
 @Setter
+@JsonInclude(Include.NON_EMPTY) // new fasterxml annotation, not used by current jersey version
+@JsonSerialize(include=Inclusion.NON_EMPTY) // old codehouse annotation, used by jersey
 public class FoundryDto {
 
     private String code;
@@ -23,10 +31,26 @@
 
     @Getter
     @Setter
+    @JsonInclude(Include.NON_EMPTY)
+    @JsonSerialize(include=Inclusion.NON_EMPTY) // old codehouse annotation used by jersey
     public class Layer {
         private String code;
         private String description;
-        // EM: pairs of annotation values and their description
-        private Map<String, String> tags;
+        private List<Key> keys;
+    }
+
+    @Getter
+    @Setter
+    @JsonInclude(Include.NON_EMPTY)
+    @JsonSerialize(include=Inclusion.NON_EMPTY) // old codehouse annotation used by jersey
+    public class Key {
+
+        private String code;
+        private String description;
+        private Map<String, String> values;
+
+        public Key (String code) {
+            this.code = code;
+        }
     }
 }
diff --git a/full/src/main/java/de/ids_mannheim/korap/dto/converter/AnnotationConverter.java b/full/src/main/java/de/ids_mannheim/korap/dto/converter/AnnotationConverter.java
index c049c2a..272d4c8 100644
--- a/full/src/main/java/de/ids_mannheim/korap/dto/converter/AnnotationConverter.java
+++ b/full/src/main/java/de/ids_mannheim/korap/dto/converter/AnnotationConverter.java
@@ -8,10 +8,12 @@
 import org.springframework.stereotype.Component;
 
 import de.ids_mannheim.korap.dto.FoundryDto;
+import de.ids_mannheim.korap.dto.FoundryDto.Key;
 import de.ids_mannheim.korap.dto.FoundryDto.Layer;
 import de.ids_mannheim.korap.dto.LayerDto;
 import de.ids_mannheim.korap.entity.Annotation;
-import de.ids_mannheim.korap.entity.AnnotationPair;
+import de.ids_mannheim.korap.entity.AnnotationKey;
+import de.ids_mannheim.korap.entity.AnnotationLayer;
 
 /**
  * AnnotationConverter prepares data transfer objects (DTOs) from
@@ -28,22 +30,22 @@
      * Returns layer descriptions in a list of {@link LayerDto}s.
      * 
      * @param pairs
-     *            a list of {@link AnnotationPair}s
+     *            a list of {@link AnnotationLayer}s
      * @return a list of {@link LayerDto}s
      */
-    public List<LayerDto> convertToLayerDto (List<AnnotationPair> pairs) {
+    public List<LayerDto> convertToLayerDto (List<AnnotationLayer> pairs) {
         List<LayerDto> layerDtos = new ArrayList<LayerDto>(pairs.size());
         LayerDto dto;
         String foundry, layer;
-        for (AnnotationPair p : pairs) {
+        for (AnnotationLayer p : pairs) {
             dto = new LayerDto();
             dto.setId(p.getId());
             dto.setDescription(p.getDescription());
 
-            foundry = p.getAnnotation1().getCode();
+            foundry = p.getFoundry().getCode();
             dto.setFoundry(foundry);
 
-            layer = p.getAnnotation2().getCode();
+            layer = p.getLayer().getCode();
             dto.setLayer(layer);
             dto.setCode(foundry + "/" + layer);
             layerDtos.add(dto);
@@ -52,60 +54,72 @@
         return layerDtos;
     }
 
-
     /**
      * Returns foundry description in {@link FoundryDto}s
      * 
      * @param pairs
-     *            a list of {@link AnnotationPair}s
+     *            a list of {@link AnnotationLayer}s
      * @param language
      * @return a list of {@link FoundryDto}s
      */
-    public List<FoundryDto> convertToFoundryDto (List<AnnotationPair> pairs,
+    public List<FoundryDto> convertToFoundryDto (List<AnnotationLayer> pairs,
             String language) {
         List<FoundryDto> foundryDtos = new ArrayList<FoundryDto>(pairs.size());
-        Map<String, List<AnnotationPair>> foundryMap = createFoundryMap(pairs);
+        Map<String, List<AnnotationLayer>> foundryMap = createFoundryMap(pairs);
 
-        for (String key : foundryMap.keySet()) {
-            List<AnnotationPair> foundries = foundryMap.get(key);
+        for (String foundryCode : foundryMap.keySet()) {
+            List<AnnotationLayer> foundries = foundryMap.get(foundryCode);
             List<Layer> layers = new ArrayList<Layer>(foundries.size());
             FoundryDto dto = null;
 
-            for (AnnotationPair f : foundries) {
+            for (AnnotationLayer f : foundries) {
                 if (dto == null) {
-                    Annotation foundry = f.getAnnotation1();
+                    Annotation foundry = f.getFoundry();
                     dto = new FoundryDto();
-                    if (language.equals("de")){
+                    if (language.equals("de")) {
                         dto.setDescription(foundry.getGermanDescription());
                     }
-                    else{
+                    else {
                         dto.setDescription(foundry.getDescription());
                     }
                     dto.setCode(foundry.getCode());
                 }
 
-                Annotation layer = f.getAnnotation2();
-                Map<String, String> tags = new HashMap<>();
-                for (Annotation value : f.getValues()) {
-                    if (language.equals("de")){
-                        tags.put(value.getCode(), value.getGermanDescription());
+                Annotation layer = f.getLayer();
+                List<Key> keys = new ArrayList<>();
+
+                for (AnnotationKey ak : f.getKeys()) {
+                    Annotation a = ak.getKey();
+                    Map<String, String> values = new HashMap<>();
+                    Key key = dto.new Key(a.getCode());
+                    if (language.equals("de")) {
+                        key.setDescription(a.getGermanDescription());
+                        for (Annotation v : ak.getValues()) {
+                            values.put(v.getCode(), v.getGermanDescription());
+                        }
+
                     }
-                    else{
-                        tags.put(value.getCode(), value.getDescription());
+                    else {
+                        key.setDescription(a.getDescription());
+                        for (Annotation v : ak.getValues()) {
+                            values.put(v.getCode(), v.getDescription());
+                        }
                     }
+                    key.setValues(values);
+                    keys.add(key);
                 }
 
                 Layer l = dto.new Layer();
                 l.setCode(layer.getCode());
-                
-                if (language.equals("de")){
+
+                if (language.equals("de")) {
                     l.setDescription(layer.getGermanDescription());
                 }
-                else{
+                else {
                     l.setDescription(layer.getDescription());
                 }
-                
-                l.setTags(tags);
+
+                l.setKeys(keys);
                 layers.add(l);
             }
 
@@ -116,19 +130,18 @@
         return foundryDtos;
     }
 
-
-    private Map<String, List<AnnotationPair>> createFoundryMap (
-            List<AnnotationPair> pairs) {
-        Map<String, List<AnnotationPair>> foundries =
-                new HashMap<String, List<AnnotationPair>>();
-        for (AnnotationPair p : pairs) {
-            String foundryCode = p.getAnnotation1().getCode();
+    private Map<String, List<AnnotationLayer>> createFoundryMap (
+            List<AnnotationLayer> pairs) {
+        Map<String, List<AnnotationLayer>> foundries =
+                new HashMap<String, List<AnnotationLayer>>();
+        for (AnnotationLayer p : pairs) {
+            String foundryCode = p.getFoundry().getCode();
             if (foundries.containsKey(foundryCode)) {
                 foundries.get(foundryCode).add(p);
             }
             else {
-                List<AnnotationPair> foundryList =
-                        new ArrayList<AnnotationPair>();
+                List<AnnotationLayer> foundryList =
+                        new ArrayList<AnnotationLayer>();
                 foundryList.add(p);
                 foundries.put(foundryCode, foundryList);
             }
diff --git a/full/src/main/java/de/ids_mannheim/korap/dto/converter/ResourceConverter.java b/full/src/main/java/de/ids_mannheim/korap/dto/converter/ResourceConverter.java
index bfd610d..5f8d0cb 100644
--- a/full/src/main/java/de/ids_mannheim/korap/dto/converter/ResourceConverter.java
+++ b/full/src/main/java/de/ids_mannheim/korap/dto/converter/ResourceConverter.java
@@ -8,12 +8,14 @@
 import org.springframework.stereotype.Component;
 
 import de.ids_mannheim.korap.dto.ResourceDto;
-import de.ids_mannheim.korap.entity.AnnotationPair;
+import de.ids_mannheim.korap.entity.AnnotationLayer;
 import de.ids_mannheim.korap.entity.Resource;
 
 /**
- * ResourceConverter prepares data transfer objects (DTOs) from {@link Resource}
- * entities. DTO structure defines controllers output, namely the structure of 
+ * ResourceConverter prepares data transfer objects (DTOs) from
+ * {@link Resource}
+ * entities. DTO structure defines controllers output, namely the
+ * structure of
  * JSON objects in HTTP responses.
  * 
  * @author margaretha
@@ -41,9 +43,9 @@
 
             layers = new HashMap<Integer, String>();
             String foundry, layer, code;
-            for (AnnotationPair annotationPair : r.getLayers()) {
-                foundry = annotationPair.getAnnotation1().getCode();
-                layer = annotationPair.getAnnotation2().getCode();
+            for (AnnotationLayer annotationPair : r.getLayers()) {
+                foundry = annotationPair.getFoundry().getCode();
+                layer = annotationPair.getLayer().getCode();
                 code = foundry + "/" + layer;
                 layers.put(annotationPair.getId(), code);
             }
diff --git a/full/src/main/java/de/ids_mannheim/korap/entity/Annotation.java b/full/src/main/java/de/ids_mannheim/korap/entity/Annotation.java
index fb6939f..f644b25 100644
--- a/full/src/main/java/de/ids_mannheim/korap/entity/Annotation.java
+++ b/full/src/main/java/de/ids_mannheim/korap/entity/Annotation.java
@@ -10,10 +10,11 @@
 import lombok.Getter;
 import lombok.Setter;
 
-/** Describes annotation tags available in the system / used in 
- *  annotating corpus data. 
+/**
+ * Describes annotation tags available in the system / used in
+ * annotating corpus data.
  * 
- *  @author margaretha
+ * @author margaretha
  *
  */
 @Setter
@@ -22,16 +23,25 @@
 @Table(name = "annotation")
 public class Annotation {
 
+    public Annotation () {}
+
+    public Annotation (String code, String type, String text, String description) {
+        this.code = code;
+        this.type = type;
+        this.text = text;
+        this.description = description;
+    }
+
     @Id
     @GeneratedValue(strategy = GenerationType.IDENTITY)
     private int id;
     private String code;
     private String type;
+    private String text;
     private String description;
     @Column(name = "de_description")
     private String germanDescription;
 
-
     @Override
     public String toString () {
         return "id=" + id + ", code= " + code + ", type= " + type
diff --git a/full/src/main/java/de/ids_mannheim/korap/entity/AnnotationKey.java b/full/src/main/java/de/ids_mannheim/korap/entity/AnnotationKey.java
new file mode 100644
index 0000000..d65ffb2
--- /dev/null
+++ b/full/src/main/java/de/ids_mannheim/korap/entity/AnnotationKey.java
@@ -0,0 +1,61 @@
+package de.ids_mannheim.korap.entity;
+
+import java.util.Set;
+
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.FetchType;
+import javax.persistence.GeneratedValue;
+import javax.persistence.GenerationType;
+import javax.persistence.Id;
+import javax.persistence.JoinColumn;
+import javax.persistence.JoinTable;
+import javax.persistence.ManyToMany;
+import javax.persistence.ManyToOne;
+import javax.persistence.Table;
+import javax.persistence.UniqueConstraint;
+
+import lombok.Getter;
+import lombok.Setter;
+
+@Setter
+@Getter
+@Entity
+@Table(name = "annotation_key", uniqueConstraints = @UniqueConstraint(
+        columnNames = { "layer_id", "key_id" }))
+public class AnnotationKey {
+
+    @Id
+    @GeneratedValue(strategy = GenerationType.IDENTITY)
+    private int id;
+    @Column(name = "key_id")
+    private int keyId;
+    @Column(name = "layer_id")
+    private int layerId;
+
+    @ManyToOne(fetch = FetchType.EAGER)
+    @JoinColumn(name = "layer_id", insertable = false, updatable = false)
+    private AnnotationLayer layer;
+
+    @ManyToOne(fetch = FetchType.EAGER)
+    @JoinColumn(name = "key_id", insertable = false, updatable = false)
+    private Annotation key;
+
+    @ManyToMany(fetch = FetchType.EAGER)
+    @JoinTable(name = "annotation_value",
+            joinColumns = @JoinColumn(name = "key_id",
+                    referencedColumnName = "id"),
+            inverseJoinColumns = @JoinColumn(name = "value_id",
+                    referencedColumnName = "id"),
+            uniqueConstraints = @UniqueConstraint(
+                    columnNames = { "key_id", "value_id" }))
+    private Set<Annotation> values;
+
+    public AnnotationKey () {}
+
+    public AnnotationKey (int layerId, int keyId) {
+        this.layerId = layerId;
+        this.keyId = keyId;
+    }
+
+}
diff --git a/full/src/main/java/de/ids_mannheim/korap/entity/AnnotationLayer.java b/full/src/main/java/de/ids_mannheim/korap/entity/AnnotationLayer.java
new file mode 100644
index 0000000..c16abec
--- /dev/null
+++ b/full/src/main/java/de/ids_mannheim/korap/entity/AnnotationLayer.java
@@ -0,0 +1,68 @@
+package de.ids_mannheim.korap.entity;
+
+import java.util.Set;
+
+import javax.persistence.CascadeType;
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.FetchType;
+import javax.persistence.GeneratedValue;
+import javax.persistence.GenerationType;
+import javax.persistence.Id;
+import javax.persistence.JoinColumn;
+import javax.persistence.ManyToOne;
+import javax.persistence.OneToMany;
+import javax.persistence.Table;
+import javax.persistence.UniqueConstraint;
+
+import org.hibernate.annotations.Fetch;
+import org.hibernate.annotations.FetchMode;
+
+import lombok.Getter;
+import lombok.Setter;
+
+/**
+ * Describes annotations as a pair, e.g. foundry and layer where
+ * foundry denotes where the annotation comes from e.g. Tree tagger
+ * parser, and layer denotes the annotation layer e.g. part of speech.
+ * 
+ * @author margaretha
+ * @see Annotation
+ */
+@Setter
+@Getter
+@Entity
+@Table(name = "annotation_layer", uniqueConstraints = @UniqueConstraint(
+        columnNames = { "foundry_id", "layer_id" }))
+public class AnnotationLayer {
+    @Id
+    @GeneratedValue(strategy = GenerationType.IDENTITY)
+    private int id;
+    @Column(name = "foundry_id")
+    private int foundryId;
+    @Column(name = "layer_id")
+    private int layerId;
+    @Column(name = "description")
+    private String description;
+
+    @Fetch(FetchMode.SELECT)
+    @ManyToOne // (fetch=FetchType.LAZY)
+    @JoinColumn(name = "foundry_id", insertable = false, updatable = false)
+    private Annotation foundry;
+
+    @Fetch(FetchMode.SELECT)
+    @ManyToOne // (fetch=FetchType.LAZY)
+    @JoinColumn(name = "layer_id", insertable = false, updatable = false)
+    private Annotation layer;
+
+    @OneToMany(mappedBy = "layer", fetch = FetchType.EAGER,
+            cascade = CascadeType.REMOVE)
+    private Set<AnnotationKey> keys;
+
+    @Override
+    public String toString () {
+        return "id=" + id + ", foundry=" + foundry + ", layer=" + layer
+                + ", description=" + description + ", keys= " + keys;
+
+    }
+}
diff --git a/full/src/main/java/de/ids_mannheim/korap/entity/AnnotationPair.java b/full/src/main/java/de/ids_mannheim/korap/entity/AnnotationPair.java
deleted file mode 100644
index fdd0ea8..0000000
--- a/full/src/main/java/de/ids_mannheim/korap/entity/AnnotationPair.java
+++ /dev/null
@@ -1,76 +0,0 @@
-package de.ids_mannheim.korap.entity;
-
-import java.util.Set;
-
-import javax.persistence.Column;
-import javax.persistence.Entity;
-import javax.persistence.FetchType;
-import javax.persistence.GeneratedValue;
-import javax.persistence.GenerationType;
-import javax.persistence.Id;
-import javax.persistence.JoinColumn;
-import javax.persistence.JoinTable;
-import javax.persistence.ManyToMany;
-import javax.persistence.ManyToOne;
-import javax.persistence.Table;
-import javax.persistence.UniqueConstraint;
-
-import org.hibernate.annotations.Fetch;
-import org.hibernate.annotations.FetchMode;
-
-import lombok.Getter;
-import lombok.Setter;
-
-/** Describes annotations as a pair, e.g. foundry and layer where 
- *  foundry denotes where the annotation comes from e.g. Tree tagger 
- *  parser, and layer denotes the annotation layer e.g. part of speech.
- * 
- *  @author margaretha
- *  @see Annotation
- */
-@Setter
-@Getter
-@Entity
-@Table(name = "annotation_pair", uniqueConstraints = @UniqueConstraint(
-        columnNames = { "annotation1", "annotation2" }))
-public class AnnotationPair {
-    @Id
-    @GeneratedValue(strategy = GenerationType.IDENTITY)
-    private int id;
-    @Column(name = "annotation1")
-    private int annotationId1;
-    @Column(name = "annotation2")
-    private int annotationId2;
-    @Column(name = "description")
-    private String description;
-
-    @Fetch(FetchMode.SELECT)
-    @ManyToOne //(fetch=FetchType.LAZY) 
-    @JoinColumn(name = "annotation1", insertable = false, updatable = false)
-    private Annotation annotation1;
-
-    @Fetch(FetchMode.SELECT)
-    @ManyToOne //(fetch=FetchType.LAZY) 
-    @JoinColumn(name = "annotation2", insertable = false, updatable = false)
-    private Annotation annotation2;
-
-    @ManyToMany(fetch = FetchType.LAZY) //(fetch=FetchType.EAGER)
-    @JoinTable(name = "annotation_pair_value",
-            joinColumns = @JoinColumn(name = "pair_id",
-                    referencedColumnName = "id"),
-            inverseJoinColumns = @JoinColumn(name = "value_id",
-                    referencedColumnName = "id"),
-            uniqueConstraints = @UniqueConstraint(
-                    columnNames = { "pair_id", "value_id" }))
-    private Set<Annotation> values;
-
-
-    @Override
-    public String toString () {
-        return "id=" + id + ", annotation1=" + annotationId1 + ", annotation2="
-                + annotationId1 + ", description=" + description
-                + ", annotation1= " + annotation1 + ", annotation2= "
-                + annotation2;
-
-    }
-}
diff --git a/full/src/main/java/de/ids_mannheim/korap/entity/Resource.java b/full/src/main/java/de/ids_mannheim/korap/entity/Resource.java
index f08b5b3..aa461c2 100644
--- a/full/src/main/java/de/ids_mannheim/korap/entity/Resource.java
+++ b/full/src/main/java/de/ids_mannheim/korap/entity/Resource.java
@@ -44,7 +44,7 @@
                     referencedColumnName = "id"),
             inverseJoinColumns = @JoinColumn(name = "layer_id",
                     referencedColumnName = "id"))
-    private Set<AnnotationPair> layers;
+    private Set<AnnotationLayer> layers;
 
 
     @Override
diff --git a/full/src/main/java/de/ids_mannheim/korap/service/AnnotationService.java b/full/src/main/java/de/ids_mannheim/korap/service/AnnotationService.java
index bbe6850..3e384ec 100644
--- a/full/src/main/java/de/ids_mannheim/korap/service/AnnotationService.java
+++ b/full/src/main/java/de/ids_mannheim/korap/service/AnnotationService.java
@@ -12,7 +12,7 @@
 import de.ids_mannheim.korap.dto.FoundryDto;
 import de.ids_mannheim.korap.dto.LayerDto;
 import de.ids_mannheim.korap.dto.converter.AnnotationConverter;
-import de.ids_mannheim.korap.entity.AnnotationPair;
+import de.ids_mannheim.korap.entity.AnnotationLayer;
 import de.ids_mannheim.korap.exceptions.KustvaktException;
 import de.ids_mannheim.korap.exceptions.StatusCodes;
 import de.ids_mannheim.korap.web.controller.AnnotationController;
@@ -35,7 +35,7 @@
     private AnnotationConverter annotationConverter;
 
     public List<LayerDto> getLayerDtos () {
-        List<AnnotationPair> layers = annotationDao.getAllFoundryLayerPairs();
+        List<AnnotationLayer> layers = annotationDao.getAllFoundryLayerPairs();
         jlog.debug("/layers " + layers.toString());
         List<LayerDto> layerDto = annotationConverter.convertToLayerDto(layers);
         return layerDto;
@@ -43,7 +43,7 @@
 
     public List<FoundryDto> getFoundryDtos (List<String> codes, String language)
             throws KustvaktException {
-        List<AnnotationPair> annotationPairs = null;
+        List<AnnotationLayer> annotationPairs = null;
         String foundry = "", layer = "";
         if (codes.contains("*")) {
             annotationPairs =
@@ -51,7 +51,7 @@
         }
         else {
             String[] annotationCode;
-            annotationPairs = new ArrayList<AnnotationPair>();
+            annotationPairs = new ArrayList<AnnotationLayer>();
             for (String code : codes) {
                 jlog.debug("code " + code);
                 annotationCode = code.split("/");
diff --git a/full/src/main/resources/db/new-sqlite/V1__initial_version.sql b/full/src/main/resources/db/new-sqlite/V1__initial_version.sql
index af81b54..af14f4f 100644
--- a/full/src/main/resources/db/new-sqlite/V1__initial_version.sql
+++ b/full/src/main/resources/db/new-sqlite/V1__initial_version.sql
@@ -1,42 +1,56 @@
 CREATE TABLE IF NOT EXISTS annotation(
 	id INTEGER PRIMARY KEY AUTOINCREMENT,
 	code VARCHAR(20) NOT NULL,
-	type VARCHAR(20) NOT NULL,	
+	type VARCHAR(20) NOT NULL,
+	text VARCHAR(20) NULL,
 	description VARCHAR(100) NOT NULL,
 	de_description VARCHAR(100)
 );
 
 CREATE UNIQUE INDEX annotation_index ON annotation (code, type);
 
-CREATE TABLE IF NOT EXISTS annotation_pair(
+CREATE TABLE IF NOT EXISTS annotation_layer(
 	id INTEGER PRIMARY KEY AUTOINCREMENT,
-	annotation1 INTEGER NOT NULL,
-	annotation2 INTEGER NOT NULL,
+	foundry_id INTEGER NOT NULL,
+	layer_id INTEGER NOT NULL,
 	description VARCHAR(255) NOT NULL,
-	FOREIGN KEY (annotation1)
+	FOREIGN KEY (foundry_id)
 		REFERENCES annotation (id)
 		ON DELETE CASCADE,
-	FOREIGN KEY (annotation2)
+	FOREIGN KEY (layer_id)
 		REFERENCES annotation (id)
 		ON DELETE CASCADE
-	
 );
 
-CREATE UNIQUE INDEX annotation_pair_index ON annotation_pair (annotation1, annotation2);
+CREATE UNIQUE INDEX annotation_layer_index ON annotation_layer (foundry_id, layer_id);
 
-CREATE TABLE IF NOT EXISTS annotation_pair_value(
+CREATE TABLE IF NOT EXISTS annotation_key(
 	id INTEGER PRIMARY KEY AUTOINCREMENT,
-	pair_id INTEGER NOT NULL,
-	value_id INTEGER NOT NULL,
-	FOREIGN KEY (pair_id)
-		REFERENCES annotation_pair (id)
+	layer_id INTEGER NOT NULL,
+	key_id INTEGER NOT NULL,
+	FOREIGN KEY (layer_id)
+		REFERENCES annotation_layer (id)
 		ON DELETE CASCADE,
-	FOREIGN KEY (value_id)
+	FOREIGN KEY (key_id)
 		REFERENCES annotation (id)
 		ON DELETE CASCADE
 );
 
-CREATE UNIQUE INDEX annotation_pair_value_index ON annotation_pair_value (pair_id, value_id);
+CREATE UNIQUE INDEX annotation_key_index ON annotation_key (layer_id, key_id);
+
+CREATE TABLE IF NOT EXISTS annotation_value(
+	id INTEGER PRIMARY KEY AUTOINCREMENT,
+	key_id INTEGER NOT NULL,
+	value_id INTEGER NOT NULL,
+	FOREIGN KEY (key_id)
+		REFERENCES annotation_key (id)
+		ON DELETE CASCADE,
+	FOREIGN KEY (key_id)
+		REFERENCES annotation (id)
+		ON DELETE CASCADE
+);
+
+CREATE UNIQUE INDEX annotation_value_index ON annotation_value (key_id, value_id);
 
 CREATE TABLE resource(
 	id VARCHAR(100) PRIMARY KEY UNIQUE NOT NULL,
@@ -53,7 +67,7 @@
 		REFERENCES resource (id)
 		ON DELETE CASCADE,
 	FOREIGN KEY (layer_id)
-		REFERENCES annotation_pair (id)
+		REFERENCES annotation_layer (id)
 		ON DELETE CASCADE	
 );
 
diff --git a/full/src/main/resources/db/insert/V2.0__insert_annotations.sql b/full/src/main/resources/db/temp/V2.0__insert_annotations.sql
similarity index 100%
rename from full/src/main/resources/db/insert/V2.0__insert_annotations.sql
rename to full/src/main/resources/db/temp/V2.0__insert_annotations.sql
diff --git a/full/src/main/resources/db/insert/V2.1__insert_annotation_pairs.sql b/full/src/main/resources/db/temp/V2.1__insert_annotation_pairs.sql
similarity index 100%
rename from full/src/main/resources/db/insert/V2.1__insert_annotation_pairs.sql
rename to full/src/main/resources/db/temp/V2.1__insert_annotation_pairs.sql
diff --git a/full/src/main/resources/db/insert/V2.2__insert_annotation_pair_values.sql b/full/src/main/resources/db/temp/V2.2__insert_annotation_pair_values.sql
similarity index 100%
rename from full/src/main/resources/db/insert/V2.2__insert_annotation_pair_values.sql
rename to full/src/main/resources/db/temp/V2.2__insert_annotation_pair_values.sql
diff --git a/full/src/main/resources/db/insert/V2.4__insert_resource_layers.sql b/full/src/main/resources/db/temp/V2.4__insert_resource_layers.sql
similarity index 100%
rename from full/src/main/resources/db/insert/V2.4__insert_resource_layers.sql
rename to full/src/main/resources/db/temp/V2.4__insert_resource_layers.sql
diff --git a/full/src/main/resources/kustvakt.conf b/full/src/main/resources/kustvakt.conf
index c5a4958..a36eef4 100644
--- a/full/src/main/resources/kustvakt.conf
+++ b/full/src/main/resources/kustvakt.conf
@@ -6,7 +6,7 @@
 krill.index.commit.auto = 500
 krill.index.relations.max = 100
 ## Directory path of virtual corpora to cache
-krill.namedVC = vc
+#krill.namedVC = vc
 
 ## LDAP
 ldap.config = file-path-to-ldap-config
diff --git a/full/src/test/java/de/ids_mannheim/korap/misc/RegexTest.java b/full/src/test/java/de/ids_mannheim/korap/misc/RegexTest.java
new file mode 100644
index 0000000..8bb0ecd
--- /dev/null
+++ b/full/src/test/java/de/ids_mannheim/korap/misc/RegexTest.java
@@ -0,0 +1,22 @@
+package de.ids_mannheim.korap.misc;
+
+import static org.junit.Assert.assertEquals;
+
+import java.util.regex.Matcher;
+
+import org.junit.Test;
+
+import de.ids_mannheim.korap.annotation.AnnotationParser;
+
+public class RegexTest {
+
+    @Test
+    public void testQuote(){
+        String s = "ah[\"-\"]";
+        Matcher m = AnnotationParser.quotePattern.matcher(s);
+        if (m.find()){
+            assertEquals("-",m.group(1));
+        }
+    }
+    
+}