Index: /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/license-header.txt
===================================================================
--- /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/license-header.txt	(revision 4603)
+++ /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/license-header.txt	(revision 4603)
@@ -0,0 +1,15 @@
+Copyright (C) ${year} ${organization}
+
+This program is free software; you can redistribute it and/or
+modify it under the terms of the GNU General Public License
+as published by the Free Software Foundation; either version 2
+of the License, or (at your option) any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
Index: /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/assembly/deploymenttarball.xml
===================================================================
--- /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/assembly/deploymenttarball.xml	(revision 4603)
+++ /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/assembly/deploymenttarball.xml	(revision 4603)
@@ -0,0 +1,58 @@
+<!--
+
+    Copyright (C) 2013 DASISH
+
+    This program is free software; you can redistribute it and/or
+    modify it under the terms of the GNU General Public License
+    as published by the Free Software Foundation; either version 2
+    of the License, or (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License
+    along with this program; if not, write to the Free Software
+    Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+-->
+
+<assembly xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.2"
+    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+    xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.2 http://maven.apache.org/xsd/assembly-1.1.2.xsd">
+    
+    <id>mpi-deploy</id>
+    <formats>
+        <format>tar.gz</format>
+    </formats>
+    
+    <fileSets>
+        
+      <fileSet>
+            <directory>${project.basedir}</directory>
+            <outputDirectory>/</outputDirectory>
+            <includes>
+                <include>UPDATE*</include>
+                <include>LICENSES*</include>
+                <include>README*</include>
+                <include>CHANGES*</include>
+                <include>INSTALL*</include>
+            </includes>
+            <fileMode>0644</fileMode>
+        </fileSet>
+        
+       
+        <fileSet>            
+            <directory>target</directory>
+            <outputDirectory>war</outputDirectory>
+            <includes>
+                <include>*.war</include>
+            </includes>
+            <fileMode>0644</fileMode>
+            <directoryMode>0755</directoryMode>
+        </fileSet>
+
+            
+    </fileSets>              
+</assembly>
Index: /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/java/eu/dasish/annotation/backend/BackendConstants.java
===================================================================
--- /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/java/eu/dasish/annotation/backend/BackendConstants.java	(revision 4603)
+++ /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/java/eu/dasish/annotation/backend/BackendConstants.java	(revision 4603)
@@ -0,0 +1,30 @@
+/**
+ * Copyright (C) 2013 DASISH
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ */
+package eu.dasish.annotation.backend;
+
+/**
+ *
+ * @author olhsha
+ */
+public class BackendConstants {
+    
+    public static final String regExpIdentifier = "[a-zA-Z0-9_-]*";
+    public static final String regExpEmail = regExpIdentifier+"@"+regExpIdentifier;
+    public static final String fragmentDescriptors = "[a-zA-Z0-9_-(),#%]*";
+    public static final String regExpRemoteId = regExpIdentifier+"|"+regExpEmail;
+}
Index: /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/java/eu/dasish/annotation/backend/Helpers.java
===================================================================
--- /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/java/eu/dasish/annotation/backend/Helpers.java	(revision 4603)
+++ /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/java/eu/dasish/annotation/backend/Helpers.java	(revision 4603)
@@ -0,0 +1,81 @@
+/*
+ * Copyright (C) 2013 DASISH
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
+ */
+package eu.dasish.annotation.backend;
+
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.Map;
+import java.util.Set;
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+import javax.xml.parsers.ParserConfigurationException;
+import org.slf4j.Logger;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.w3c.dom.ls.DOMImplementationLS;
+import org.w3c.dom.ls.LSSerializer;
+import org.xml.sax.SAXException;
+
+/**
+ *
+ * @author olhsha
+ */
+public class Helpers {
+
+    //exception messages
+    final static public String INVALID_BODY_EXCEPTION = "Invalide annotation body: both, text and xml options, are null.";
+   
+    public static String replace(String text, Map<String, String> pairs) {
+        String result = (new StringBuilder(text)).toString();
+        for (String tempTarget : pairs.keySet()) {
+            result = result.replaceAll(tempTarget, pairs.get(tempTarget));
+        }
+        return result;
+    }
+
+    public static Element stringToElement(String string) {
+        try {
+            DocumentBuilder dbf = DocumentBuilderFactory.newInstance().newDocumentBuilder();
+            try {
+                try {
+                    InputStream is = new ByteArrayInputStream(string.getBytes("UTF-16"));
+                    Document doc = dbf.parse(is);
+                    return doc.getDocumentElement();
+                } catch (SAXException saxException) {
+                    System.out.println(saxException);
+                }
+            } catch (IOException ioe) {
+                System.out.println(ioe);
+            }
+        } catch (ParserConfigurationException parserException) {
+            System.out.println(parserException);
+        }
+        return null;
+    }
+
+    public static String elementToString(Element element) {
+        Document document = element.getOwnerDocument();
+        DOMImplementationLS domImplLS = (DOMImplementationLS) document.getImplementation();
+        LSSerializer serializer = domImplLS.createLSSerializer();
+        String result = serializer.writeToString(element);
+        return result;
+    }
+    
+    
+}
Index: /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/java/eu/dasish/annotation/backend/MyResource.java
===================================================================
--- /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/java/eu/dasish/annotation/backend/MyResource.java	(revision 4603)
+++ /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/java/eu/dasish/annotation/backend/MyResource.java	(revision 4603)
@@ -0,0 +1,39 @@
+/**
+ * Copyright (C) 2013 DASISH
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ */
+
+package eu.dasish.annotation.backend;
+
+import javax.ws.rs.GET;
+import javax.ws.rs.Path;
+import javax.ws.rs.Produces;
+
+/** Example reTarget class hosted at the URI path "/myreTarget"
+ */
+@Path("/myresource")
+public class MyResource {
+    
+    /** Method processing HTTP GET requests, producing "text/plain" MIME media
+     * type.
+     * @return String that will be send back as a response of type "text/plain".
+     */
+    @GET 
+    @Produces("text/plain")
+    public String getIt() {
+        return "Hi there!";
+    }
+}
Index: /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/java/eu/dasish/annotation/backend/Resource.java
===================================================================
--- /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/java/eu/dasish/annotation/backend/Resource.java	(revision 4603)
+++ /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/java/eu/dasish/annotation/backend/Resource.java	(revision 4603)
@@ -0,0 +1,26 @@
+/*
+ * Copyright (C) 2013 DASISH
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
+ */
+package eu.dasish.annotation.backend;
+
+/**
+ *
+ * @author olhsha
+ */
+public enum Resource {
+    PRINCIPAL, ANNOTATION, TARGET, CACHED_REPRESENTATION,NOTEBOOK
+}
Index: /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/java/eu/dasish/annotation/backend/dao/AnnotationDao.java
===================================================================
--- /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/java/eu/dasish/annotation/backend/dao/AnnotationDao.java	(revision 4603)
+++ /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/java/eu/dasish/annotation/backend/dao/AnnotationDao.java	(revision 4603)
@@ -0,0 +1,227 @@
+/*
+ * Copyright (C) 2013 DASISH
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
+ */
+package eu.dasish.annotation.backend.dao;
+
+import eu.dasish.annotation.schema.Annotation;
+import eu.dasish.annotation.schema.AnnotationBody;
+import eu.dasish.annotation.schema.AnnotationInfo;
+import eu.dasish.annotation.schema.Permission;
+import java.sql.SQLException;
+import java.sql.Timestamp;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Created on : Jun 27, 2013, 10:34:13 AM
+ *
+ * @author Peter Withers <peter.withers@mpi.nl>
+ */
+
+
+public interface AnnotationDao extends ResourceDao{
+    
+    
+    /**
+     * GETTERS
+     */
+    
+    /**
+     * 
+     * @param annotationID
+     * @return the pair (annotation, owner_id) with empty list of Targets.
+     * 
+     * (Constructing a complete Annotation object using  "getAnnotationWithoutTargets" and "retrieveTargetIDs" is done in "DaoDispatchter".)
+     * 
+     */
+    public Annotation getAnnotationWithoutTargetsAndPermissions(Number annotationID);
+    
+      
+    public List<Number> getFilteredAnnotationIDs(Number ownerID, String text, String namespace, String after, String before);
+     
+  
+    public List<Number> getAnnotationIDsForUserWithPermission(Number userID, String acess);
+    
+    
+    public List<Number> getAnnotationIDsForTargets(List<Number> TargetIDs);   
+    
+    /*
+     * Use inly in the debugging mode to acces all the existing annotations.
+     */
+    public List<Number> getAllAnnotationIDs();
+    
+    public List<Number> sublistOrderedAnnotationIDs(List<Number> annotationIDs, int offset, int limit, String orderedBy, String desc);
+    
+       /**
+     * unit test is missing
+     * @param annotationIDs
+     * @return annotationInfo  for the annotation with the internal annotationID.
+     * 
+     */
+    public AnnotationInfo getAnnotationInfoWithoutTargets(Number annotationID);    
+   
+    /**
+     * 
+     * @param annotationIDs
+     * @return list of reTarget references where an i-th reference is constructed from the external identifier of the annotation with the i-th internal identifier from the list.
+     */
+    public List<String> getAnnotationREFs(List<Number> annotationIDs); 
+    
+   
+    
+    
+    
+       /**
+     * 
+     * @param annotationID
+     * @return the list of the internal IDs of all the target Targets of "annotationID".
+     */
+    //public List<Number> retrieveTargetIDs(Number annotationID);   
+    
+    
+    public Number  getOwner(Number annotationID);
+    
+    /**
+     * 
+     * @param annotationID
+     * @param userID
+     * @return permission of the userID w.r.t. annotationID, or null if the permission is not given
+     */ 
+    public Permission  getPermission(Number annotationID, Number userID);
+    
+    
+    
+    public List<Number> getAnnotations(Number notebookID);
+    
+    
+    public boolean targetIsInUse(Number targetID);
+    /**
+     * 
+     * @param annotationID
+     * @return true if "annotationID" is mentioned in at least one of the joint tables:
+     * "annotations_targets", "annotations_principals_permissions", "notebook_annotations".
+     * Otherwise return "false".
+     */
+    //public boolean annotationIsInUse(Number annotationID);
+    
+    /**
+     * ADDERS 
+     */
+    
+    /**
+     * 
+     * @param annotationID
+     * @param targetID
+     * @return # updated rows in the joint table "annotations_target_Targets".
+     * @throws SQLException 
+     * Connects the annotation to its target Target by adding the pair (annotationID, TargetID) to the joint table.
+     */ 
+    public int addAnnotationTarget(Number annotationID, Number targetID);
+    
+   
+    /**
+     * 
+     * @param annotationID
+     * @param userID
+     * @param permission
+     * @return # rows added to the table "annotations_principals_permissions"
+     * Sets the "permission" for the "userID" w.r.t. the annotation with "annotationID".
+     */
+    public int addAnnotationPrincipalPermission(Number annotationID, Number userID, Permission permission);
+    
+    
+  
+     /**
+     * 
+     * @param annotation: the object to be added to the table "annotation".
+     * @return  the internal ID of the added annotation, if it is added, or null otherwise.
+     **/
+    
+    public Number addAnnotation(Annotation annotation, Number newOwnerID);
+ 
+     
+    /////// UPDATERS //////////////////
+    
+   
+    public int updateAnnotationBody(Number annotationID, String text, String mimeType, Boolean isXml);
+    
+   
+    
+    /**
+     * 
+     * @param annotation
+     * @return # of updated rows in "annotation" table after updating the annotation. Should return 1 if update  happens
+     * @throws SQLException 
+     */
+    public int updateAnnotation(Annotation annotation, Number ownerID);
+    
+    
+     /**
+     * 
+     * @param annotationID
+     * @param userID
+     * @param permission
+     * @return # rows updated to the table "annotations_principals_permissions"
+     * Sets the "permission" for the "userID" w.r.t. the annotation with "annotationID".
+     */
+    public int updateAnnotationPrincipalPermission(Number annotationID, Number userID, Permission permission);
+    
+    
+    
+    
+   /**
+    * DELETERS 
+    */
+    
+    /**
+     * 
+     * @param annotationId
+     * @return # rows in the table "annotation". It should be "1" if the annotation with "annotationID" is successfully deleted, and "0" otherwise.
+     */
+    
+    
+   
+    public int deleteAnnotation(Number annotationId);
+    
+    /**
+     * 
+     * @param annotationId
+     * @return # removed rows in the table "annotations_target_Targets". 
+     */
+    
+    public int deleteAllAnnotationTarget(Number annotationID);
+    
+   
+   /**
+    * 
+    * @param annotationID
+    * @return # removed rows in the table "annotations_principals_permissions".
+    * @throws SQLException 
+    */
+    public int deleteAnnotationPrincipalPermissions(Number annotationID);
+    
+    public int deleteAnnotationPrincipalPermission(Number annotationID, Number userID);
+    
+    public int deleteAnnotationFromAllNotebooks(Number annotationID);
+    
+    /*
+     * HELPERS 
+     */
+    
+    public String[] retrieveBodyComponents(AnnotationBody annotationBody);
+
+}
Index: /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/java/eu/dasish/annotation/backend/dao/CachedRepresentationDao.java
===================================================================
--- /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/java/eu/dasish/annotation/backend/dao/CachedRepresentationDao.java	(revision 4603)
+++ /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/java/eu/dasish/annotation/backend/dao/CachedRepresentationDao.java	(revision 4603)
@@ -0,0 +1,82 @@
+/*
+ * Copyright (C) 2013 DASISH
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
+ */
+package eu.dasish.annotation.backend.dao;
+
+import eu.dasish.annotation.schema.CachedRepresentationInfo;
+import java.io.InputStream;
+import java.util.List;
+
+/**
+ *
+ * @author olhsha
+ */
+public interface CachedRepresentationDao extends ResourceDao{
+    
+   
+    /** GETTERS
+     * 
+     */
+  
+    /**
+     * 
+     * @param internalID
+     * @return the object of the class "CachedRepresentationInfo"  with the internal id "internalID".
+     */
+    public CachedRepresentationInfo getCachedRepresentationInfo(Number internalID);
+    
+    
+    /**
+     * 
+     * @param internalID
+     * @return the Blob of the cached representation  with the internal id "internalID".
+     */
+    public InputStream getCachedRepresentationBlob(Number internalID);
+    
+    
+     /* 
+     * @param targetID
+     * @return the list of the cached representation's ID-s for the target the internal ID "targetID". 
+     */
+    public List<Number> getCachedRepresentationsForTarget(Number targetID);
+  
+    /**
+     * ADDERS
+     */
+    
+     /**
+     * 
+     * @param cachedInfo
+     * @param cachedBlob
+     * @return the internal ID of the just added "cached", or null if the cached representation is not added for some reason.
+     */
+    public Number addCachedRepresentation(CachedRepresentationInfo cachedInfo, InputStream cachedBlob);
+    
+    
+   /**
+    * DELETERS
+    */
+    /**
+     * 
+     * @param internalID
+     * @return  # deleted rows on the table "cached_representation".
+     */
+    public  int deleteCachedRepresentation(Number internalID);
+    
+   
+    
+}
Index: /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/java/eu/dasish/annotation/backend/dao/DBIntegrityService.java
===================================================================
--- /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/java/eu/dasish/annotation/backend/dao/DBIntegrityService.java	(revision 4603)
+++ /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/java/eu/dasish/annotation/backend/dao/DBIntegrityService.java	(revision 4603)
@@ -0,0 +1,382 @@
+/*
+ * Copyright (C) 2013 DASISH
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
+ */
+package eu.dasish.annotation.backend.dao;
+
+import eu.dasish.annotation.backend.Resource;
+import eu.dasish.annotation.schema.Annotation;
+import eu.dasish.annotation.schema.AnnotationBody;
+import eu.dasish.annotation.schema.AnnotationInfoList;
+import eu.dasish.annotation.schema.CachedRepresentationInfo;
+import eu.dasish.annotation.schema.Notebook;
+import eu.dasish.annotation.schema.NotebookInfo;
+import eu.dasish.annotation.schema.NotebookInfoList;
+import eu.dasish.annotation.schema.Permission;
+import eu.dasish.annotation.schema.UserWithPermissionList;
+import eu.dasish.annotation.schema.ReferenceList;
+import eu.dasish.annotation.schema.ResponseBody;
+import eu.dasish.annotation.schema.Target;
+import eu.dasish.annotation.schema.TargetInfo;
+import eu.dasish.annotation.schema.User;
+import java.io.InputStream;
+import java.sql.SQLException;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+
+/**
+ *
+ * @author olhsha
+ *
+ */
+public interface DBIntegrityService {
+
+    void setServiceURI(String serviceURI);
+
+    /**
+     * GETTERS
+     */
+    String getRemoteUser();
+    
+    void setRemoteUser(String currentUser);
+    
+    
+    Number getResourceInternalIdentifier(UUID externalID, Resource resource);
+
+    Number getResourceInternalIdentifierFromURI(String uri, Resource resource);
+
+    UUID getResourceExternalIdentifier(Number resourceID, Resource resource);
+
+    String getResourceURI(Number resourceID, Resource resource);
+
+    UserWithPermissionList getPermissions(Number resourceID, Resource resource);
+
+    /**
+     *
+     * @param word
+     * @param text
+     * @param access
+     * @param namespace
+     * @param after
+     * @param before
+     * @return the list of internal id-s of the annotations such that: --
+     * Targets' links of which contain "link" (as a substring), -- serialized
+     * bodies of which contain "text", -- current user has "access" (owner,
+     * reader, writer) to them, -- namespace ???, -- owned by "owner", --
+     * created after time-samp "after and before time-stamp "before".
+     */
+    List<Number> getFilteredAnnotationIDs(UUID ownerId, String link, String text, Number inloggedUserID, String access, String namespace, String after, String before);
+
+    AnnotationInfoList getAllAnnotationInfos();
+
+    /**
+     *
+     * @param word
+     * @param text
+     * @param access
+     * @param namespace
+     * @param owner
+     * @param after
+     * @param before
+     * @return the list of the annotationInfos of the annotations such that: --
+     * Targets' links of which contain "link" (as a substring), -- serialized
+     * bodies of which contain "text", -- current user has "access" (owner,
+     * reader, writer) to them, -- namespace ???, -- owned by "owner", --
+     * created after time-samp "after and before time-stamp "before".
+     */
+    AnnotationInfoList getFilteredAnnotationInfos(UUID ownerId, String word, String text, Number inloggedUserID, String access, String namespace, String after, String before);
+
+    /**
+     *
+     * @param internalID
+     * @return CachedRepresentationInfo (i.e. "metadata") for cached
+     * representation with the internal id "intenalID"
+     */
+    CachedRepresentationInfo getCachedRepresentationInfo(Number internalID);
+
+    /**
+     *
+     * @param annotationID
+     * @return the object Annotation generated from the tables "annotation",
+     * "annotations_target_Targets", "Target",
+     * "annotations_principals_permissions".
+     * @throws SQLException
+     */
+    Annotation getAnnotation(Number annotationID);
+
+    Number getAnnotationOwnerID(Number annotationID);
+
+    User getAnnotationOwner(Number annotationID);
+    
+    /**
+     *
+     * @param annotationID
+     * @return the object TargetList containing all target Targets of the
+     * annotationID
+     * @throws SQLException
+     */
+    ReferenceList getAnnotationTargets(Number annotationID);
+
+    /**
+     *
+     * @param annotationID
+     * @return the list of targetURI's for which there is no cached
+     * representation
+     */
+    List<String> getTargetsWithNoCachedRepresentation(Number annotationID);
+
+    List<String> getUsersWithNoInfo(Number annotationID);
+
+    /**
+     *
+     * @param targetID
+     * @return the list of the external version ID-s that refers to the same
+     * source (link) as targetID
+     */
+    ReferenceList getTargetsForTheSameLinkAs(Number targetID);
+
+    /**
+     *
+     * @param cachedID
+     * @return BLOB of the cachedID
+     */
+    InputStream getCachedRepresentationBlob(Number cachedID);
+
+    Target getTarget(Number internalID);
+
+    /**
+     *
+     * @param userID
+     * @return user with "userID"
+     */
+    User getUser(Number userID);
+
+    /**
+     *
+     * @param eMail
+     * @return user with e-mail "eMail"
+     */
+    User getUserByInfo(String eMail);
+
+    String getUserRemoteID(Number internalID);
+
+    Number getUserInternalIDFromRemoteID(String remoteID);
+
+    /**
+     *
+     * @param annotationID
+     * @param userID
+     * @return permission of the userID w.r.t. annotationID, or null if the
+     * permission is not given
+     */
+    Permission getPermission(Number annotationID, Number userID);
+
+    String getTypeOfUserAccount(Number userID);
+    
+    User getDataBaseAdmin();
+
+    boolean canRead(Number userID, Number annotationID);
+
+    boolean canWrite(Number userID, Number annotationID);
+
+    /// notebooks ///
+    NotebookInfoList getNotebooks(Number prinipalID, String permission);
+
+    boolean hasAccess(Number notebookID, Number principalID, Permission permission);
+
+    ReferenceList getNotebooksOwnedBy(Number principalID);
+
+    ReferenceList getPrincipals(Number notebookID, String permission);
+
+    Notebook getNotebook(Number notebookID);
+
+    Number getNotebookOwner(Number notebookID);
+
+    ReferenceList getAnnotationsForNotebook(Number notebookID, int startAnnotation, int maximumAnnotations, String orderedBy, boolean desc);
+
+    /**
+     * UPDATERS
+     */
+    boolean updateAccount(UUID userExternalID, String account);
+
+    /**
+     *
+     * @param annotation
+     * @return 1 of the annotation if it is updated
+     */
+    int updateAnnotation(Annotation annotation);
+
+    /**
+     *
+     * @param userID
+     * @param annotationBody
+     * @return 1 of the annotation if it is updated
+     */
+    int updateAnnotationBody(Number internalID, AnnotationBody annotationBody);
+
+    /**
+     *
+     * @param annotationID
+     * @param userID
+     * @param permission
+     * @return # rows updated to the table "annotations_principals_permissions"
+     * Sets the "permission" for the "userID" w.r.t. the annotation with
+     * "annotationID".
+     */
+    int updateAnnotationPrincipalPermission(Number annotationID, Number userID, Permission permission);
+
+    /**
+     *
+     * @param annotationID
+     * @param permissionList
+     * @return # of rows updated or added in the table
+     * annotations_principals_permissions
+     */
+    int updatePermissions(Number annotationID, UserWithPermissionList permissionList);
+
+    Number updateUser(User user);
+
+    /// notebooks ///
+    boolean updateNotebookMetadata(Number notebookID, NotebookInfo upToDateNotebookInfo);
+
+    boolean addAnnotationToNotebook(Number notebookID, Number annotationID);
+
+    /**
+     * ADDERS
+     */
+    /**
+     *
+     * @param targetID
+     * @param cachedInfo
+     * @param cachedBlob
+     * @return result[0] = # updated rows in the table
+     * "Targets_cached_representations" (must be 1 or 0). result[1] = the
+     * internal ID of the added cached (a new one if "cached" was new for the
+     * Data Base).
+     */
+    Number[] addCachedForTarget(Number targetID, String fragmentDescriptor, CachedRepresentationInfo cachedInfo, InputStream cachedBlob);
+
+    /**
+     *
+     * @param annotationID
+     * @param targets
+     * @return map temporaryTargetID |--> TargetExternalID. Its domain is the
+     * temporary IDs of all the new Targets. While adding a new Target a new
+     * external ID is generated for it and it becomes the value of the map. The
+     * TargetIDs which are already present in the DB are not in the domain. If
+     * all Targets are old, then the map is empty.
+     * @throws SQLException
+     */
+    Map<String, String> addTargetsForAnnotation(Number annotationID, List<TargetInfo> targets);
+
+    /**
+     *
+     * @param userID
+     * @param annotation
+     * @return the internalId of the just added "annotation" (or null if it is
+     * not added) by the owner "userID". calls "addTargetsForAnnotation"
+     * @throws SQLException
+     */
+    Number addUsersAnnotation(Number ownerID, Annotation annotation);
+
+    /**
+     *
+     * @param user
+     * @param remoteID is got from the server
+     * @return the internal Id of the just added "user", or null if it was not
+     * added for some reason (already exists)
+     * @throws SQLException
+     */
+    Number addUser(User user, String remoteID);
+
+    int addAnnotationPrincipalPermission(Number annotationID, Number userID, Permission permission);
+
+    /// notebooks ////
+    Number createNotebook(Notebook notebook, Number ownerID);
+
+    boolean createAnnotationInNotebook(Number notebookID, Annotation annotation, Number ownerID);
+
+    /**
+     * DELETERS
+     */
+    /**
+     *
+     * @param userID
+     * @return # of affected rows in the table "principal". It is 1 if the
+     * userId is found and deleted; it is 0 if it is not found or not deleted,
+     * e.g. because it is in use in the table
+     * "annotationsPreincipalsPermissions"
+     */
+    int deleteUser(Number userID);
+
+    /**
+     *
+     * @param userID
+     * @return # of affected rows in the table "principal". It is 1 if the
+     * userId is found and deleted; it is 0 if it is not found or not deleted,
+     * e.g. because it is in use in the table
+     * "annotationsPreincipalsPermissions"
+     */
+    int deleteUserSafe(Number userID);
+
+    int deleteCachedRepresentation(Number internalID);
+
+    /**
+     *
+     * @param TargetID
+     * @param cachedID
+     * @return result[0] = # deleted rows in the table
+     * "Targets_cached_representations" (1, or 0). result[1] = # deleted rows in
+     * the table "cached_representation" (should be 0 if the cached
+     * representation is in use by some other Target???).
+     */
+    int[] deleteCachedRepresentationOfTarget(Number TargetID, Number cachedID);
+
+    /**
+     *
+     * @param targetID
+     * @return result[0] = # deleted rows in the table
+     * "targets_cached_representations". result[1] = # deleted rows in the table
+     * "cached_representation".
+     *
+     */
+    int[] deleteAllCachedRepresentationsOfTarget(Number versionID);
+
+    int deleteTarget(Number internalID);
+
+    /**
+     *
+     * @param annotationID
+     * @return result[0] = # deleted rows in the table "annotation" (1 or 0).
+     * result[1] = # deleted rows in the table
+     * "annotations_principals_permissions". result[2] = # deleted rows in the
+     * table "annotations_target_Targets". result[3] = # deleted rows in the
+     * table "Target".
+     * @throws SQLException
+     */
+    int[] deleteAnnotation(Number annotationID);
+
+    /// notebooks ///
+    boolean deleteNotebook(Number notebookID);
+
+    //////// HELPERS for resources /////
+    ResponseBody makeAnnotationResponseEnvelope(Number annotationID);
+
+    ResponseBody makeNotebookResponseEnvelope(Number notebookID);
+
+    ResponseBody makePermissionResponseEnvelope(Number resourceID, Resource resource);
+}
Index: /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/java/eu/dasish/annotation/backend/dao/NotebookDao.java
===================================================================
--- /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/java/eu/dasish/annotation/backend/dao/NotebookDao.java	(revision 4603)
+++ /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/java/eu/dasish/annotation/backend/dao/NotebookDao.java	(revision 4603)
@@ -0,0 +1,124 @@
+/*
+ * Copyright (C) 2013 DASISH
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
+ */
+package eu.dasish.annotation.backend.dao;
+
+
+import eu.dasish.annotation.schema.Permission;
+import eu.dasish.annotation.schema.Notebook;
+import eu.dasish.annotation.schema.NotebookInfo;
+import java.util.List;
+import java.util.UUID;
+
+/**
+ * Created on : Jun 12, 2013, 1:40:09 PM
+ *
+ * @author Peter Withers <peter.withers@mpi.nl>
+ */
+
+// TODO: not yet fully updated.
+
+public interface NotebookDao extends ResourceDao {
+
+    
+    /**
+     * 
+     * GETTERS 
+     * 
+  **/
+    
+    Number getOwner(Number notebookID);
+    
+    
+    
+    List<Number> getNotebookIDs(Number principalID, Permission acessMode);
+    
+    // Returns a list of notebook Ids for the notebooks for which the given user "userID" is the owner.
+    List<Number> getNotebookIDsOwnedBy(Number principaID);
+    
+   
+    
+    /**
+     * 
+     * @param notebookID
+     * @return the notebook info for the notebook with notebookID
+     */
+    NotebookInfo getNotebookInfoWithoutOwner(Number notebookID);
+    
+   
+    /**
+     * 
+     * @param notebookID
+     * @return notebook metadata for the notebook with notebookID
+     */
+    Notebook getNotebookWithoutAnnotationsAndPermissionsAndOwner(Number notebookID);
+    
+   
+   
+    
+    /**
+     * 
+     * UPDATERS 
+     * 
+     * 
+     */
+    
+    
+    
+    /**
+     * 
+     * @param notebookID
+     * @return true if updated, false otherwise. Logs the reason if the notebook is not updated.
+     */
+    boolean updateNotebookMetadata(Number notebookID, String title, Number ownerID);
+    
+    boolean setOwner(Number notebookID, Number ownerID);
+    
+    boolean updateUserPermissionForNotebook(Number notebookID, Number principalID, Permission permission);
+    
+     /**
+     * 
+     * ADDERS
+     * 
+     * 
+     */
+    
+    public Number createNotebookWithoutPermissionsAndAnnotations(Notebook notebook, Number ownerID);
+    
+    boolean addAnnotationToNotebook(Number notebookID, Number annotationID);
+    
+    boolean addPermissionToNotebook(Number notebookID, Number userID, Permission permission);
+    
+    
+    
+    /**
+     * 
+     * DELETERS 
+     * 
+     * 
+     */
+    
+    boolean deleteAnnotationFromNotebook(Number notebookID, Number annotationID);
+    
+    boolean deleteAllAnnotationsFromNotebook(Number notebookID);
+    
+    boolean deleteNotebookPrincipalPermission(Number notebookID, Number principalID);
+    
+    boolean deleteAllPermissionsForNotebook(Number notebookID);
+    
+    boolean deleteNotebook(Number notebookID);
+}
Index: /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/java/eu/dasish/annotation/backend/dao/ResourceDao.java
===================================================================
--- /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/java/eu/dasish/annotation/backend/dao/ResourceDao.java	(revision 4603)
+++ /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/java/eu/dasish/annotation/backend/dao/ResourceDao.java	(revision 4603)
@@ -0,0 +1,61 @@
+/*
+ * Copyright (C) 2013 DASISH
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
+ */
+package eu.dasish.annotation.backend.dao;
+
+
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+
+/**
+ *
+ * @author olhsha
+ */
+public interface ResourceDao {
+    
+    
+    public void setServiceURI(String serviceURI);
+    
+   
+    public Number getInternalID(UUID externalId);
+    
+  
+    public Number getInternalIDFromURI(String uri);
+    
+  
+    public UUID getExternalID(Number internalId);
+    
+  
+    public String externalIDtoURI(String externalID);
+    
+    /**
+     * 
+     * @param stringURI
+     * @return returns the extranlID which is a suffix of stringURI
+     */
+    public String stringURItoExternalID(String stringURI);
+    
+    /**
+     * 
+     * @param internalID
+     * @return URI string of the resource )of the type set in resourceTableName) with internalID
+     */
+    public String getURIFromInternalID(Number internalID);
+    
+    public List<Map<Number, String>>  getPermissions(Number resourceID); 
+}
Index: /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/java/eu/dasish/annotation/backend/dao/TargetDao.java
===================================================================
--- /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/java/eu/dasish/annotation/backend/dao/TargetDao.java	(revision 4603)
+++ /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/java/eu/dasish/annotation/backend/dao/TargetDao.java	(revision 4603)
@@ -0,0 +1,128 @@
+/*
+ * Copyright (C) 2013 DASISH
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
+ */
+package eu.dasish.annotation.backend.dao;
+
+import eu.dasish.annotation.schema.Target;
+import eu.dasish.annotation.schema.TargetInfo;
+import java.sql.SQLException;
+import java.util.List;
+import java.util.Map;
+
+/**
+ *
+ * @author olhsha
+ */
+public interface TargetDao extends ResourceDao {
+
+    /**
+     * GETTERS 
+     *
+     */
+    /**
+     *
+     * @param inernalID
+     * @return the Target with the intrenal Id "internalID".
+     */
+    public Target getTarget(Number internalID);
+
+    /**
+     *
+     * @param targets
+     * @return the list of TargetInfo objects corresponding to the Targets with
+     * the internalIds from the list "Targets".
+     */
+    public List<TargetInfo> getTargetInfos(List<Number> targets);
+
+    /**
+     *
+     * @param targetID
+     * @return the list of pairs (cached_representation_id, fragment_descriptor)
+     * for the target with the internal ID "targetID".
+     */
+    public Map<Number, String> getCachedRepresentationFragmentPairs(Number targetID);
+
+    /**
+     *
+     * @param subword
+     * @return the list of Target ID's which link-fields contain "subword" as a
+     * substring.
+     */
+    public List<Number> getTargetsReferringTo(String subword);
+
+    /**
+     *
+     * @param targetID
+     * @return The link (uri) to the source to which the target refers
+     */
+    public String getLink(Number targetID);
+
+    /**
+     *
+     * @param link
+     * @return the list of Target ID's which link-fields is exactly "link"
+     */
+    public List<Number> getTargetsForLink(String link);
+
+    boolean cachedIsInUse(Number cachedID);
+
+    public List<Number> retrieveTargetIDs(Number annotationID);
+
+    /**
+     * ADDERS
+     *
+     */
+    /**
+     *
+     * @param target: the Target-object of the Target to be added to "Target"
+     * table.
+     * @return the internal ID of the just added Target or null if it has not
+     * been added.
+     */
+    public Number addTarget(Target target);
+
+    /**
+     *
+     * @param TargetID
+     * @param cachedID
+     * @return # added rows to the table "Targets_cached_representations".
+     * Should be "1" if the pair (TargetID, cachedID) has been added.
+     * @throws SQLException
+     */
+    public int addTargetCachedRepresentation(Number TargetID, Number cachedID, String fragmentDescription);
+
+    /**
+     * DELETERS
+     *
+     */
+    /**
+     *
+     * @param internalId
+     * @return # deleted rows in "Target" table. Should be "1" if the Target has
+     * been deleted.
+     */
+    public int deleteTarget(Number internalID);
+
+    /**
+     *
+     * @param TargetID
+     * @return # deleted rows in the table "Targets_cached_representation" when
+     * deleting the pair (TargetID, chachedID)
+     * @throws SQLException
+     */
+    public int deleteTargetCachedRepresentation(Number TargetID, Number chachedID);
+}
Index: /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/java/eu/dasish/annotation/backend/dao/UserDao.java
===================================================================
--- /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/java/eu/dasish/annotation/backend/dao/UserDao.java	(revision 4603)
+++ /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/java/eu/dasish/annotation/backend/dao/UserDao.java	(revision 4603)
@@ -0,0 +1,66 @@
+/*
+ * Copyright (C) 2013 DASISH
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
+ */
+package eu.dasish.annotation.backend.dao;
+
+import eu.dasish.annotation.schema.Permission;
+import eu.dasish.annotation.schema.User;
+import java.util.List;
+import java.util.UUID;
+
+
+/**
+ *
+ * @author olhsha
+ */
+public interface UserDao extends ResourceDao{
+    
+     public User getUser(Number internalID);
+     
+     public User getUserByInfo(String  eMail);
+     
+     public Number getDBAdminID();
+     
+     // where is it used?
+     public boolean userIsInUse(Number userID);
+     
+     // where is it used??
+     public boolean userExists(User user);
+     
+     public String getTypeOfUserAccount(Number internalID);
+     
+     public String getRemoteID(Number internalID);
+     
+     
+     public Number getUserInternalIDFromRemoteID(String remoteID);
+     
+     public List<Number> getPrincipalIDsWithPermissionForNotebook(Number notebookID, Permission permission);
+     
+     public boolean updateAccount(UUID externalID, String account);
+     
+     public Number updateUser(User user);
+    
+     public Number addUser(User user, String remoteID);
+     
+     public int deleteUser(Number intenralID);
+     
+     public int deleteUserSafe(Number internalID);
+  
+     
+}
+
+
Index: /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/java/eu/dasish/annotation/backend/dao/impl/DBIntegrityServiceImlp.java
===================================================================
--- /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/java/eu/dasish/annotation/backend/dao/impl/DBIntegrityServiceImlp.java	(revision 4603)
+++ /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/java/eu/dasish/annotation/backend/dao/impl/DBIntegrityServiceImlp.java	(revision 4603)
@@ -0,0 +1,930 @@
+/*
+ * Copyright (C) 2013 DASISH
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
+ */
+package eu.dasish.annotation.backend.dao.impl;
+
+import eu.dasish.annotation.backend.Resource;
+import eu.dasish.annotation.backend.Helpers;
+import eu.dasish.annotation.backend.dao.AnnotationDao;
+import eu.dasish.annotation.backend.dao.CachedRepresentationDao;
+import eu.dasish.annotation.backend.dao.DBIntegrityService;
+import eu.dasish.annotation.backend.dao.NotebookDao;
+import eu.dasish.annotation.backend.dao.ResourceDao;
+import eu.dasish.annotation.backend.dao.TargetDao;
+import eu.dasish.annotation.backend.dao.UserDao;
+import eu.dasish.annotation.backend.rest.AnnotationResource;
+import eu.dasish.annotation.schema.Action;
+import eu.dasish.annotation.schema.ActionList;
+import eu.dasish.annotation.schema.Annotation;
+import eu.dasish.annotation.schema.AnnotationActionName;
+import eu.dasish.annotation.schema.AnnotationBody;
+import eu.dasish.annotation.schema.AnnotationInfo;
+import eu.dasish.annotation.schema.AnnotationInfoList;
+import eu.dasish.annotation.schema.CachedRepresentationFragment;
+import eu.dasish.annotation.schema.CachedRepresentationFragmentList;
+import eu.dasish.annotation.schema.CachedRepresentationInfo;
+import eu.dasish.annotation.schema.Notebook;
+import eu.dasish.annotation.schema.NotebookInfo;
+import eu.dasish.annotation.schema.NotebookInfoList;
+import eu.dasish.annotation.schema.TargetInfoList;
+import eu.dasish.annotation.schema.Permission;
+import eu.dasish.annotation.schema.PermissionActionName;
+import eu.dasish.annotation.schema.UserWithPermissionList;
+import eu.dasish.annotation.schema.ReferenceList;
+import eu.dasish.annotation.schema.ResponseBody;
+import eu.dasish.annotation.schema.Target;
+import eu.dasish.annotation.schema.TargetInfo;
+import eu.dasish.annotation.schema.User;
+import eu.dasish.annotation.schema.UserWithPermission;
+import java.io.InputStream;
+import java.lang.Number;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import java.lang.reflect.Field;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ *
+ * @author olhsha
+ */
+public class DBIntegrityServiceImlp implements DBIntegrityService {
+
+    @Autowired
+    UserDao userDao;
+    @Autowired
+    CachedRepresentationDao cachedRepresentationDao;
+    @Autowired
+    TargetDao targetDao;
+    @Autowired
+    AnnotationDao annotationDao;
+    @Autowired
+    NotebookDao notebookDao;
+    private String remoteUser=null;
+    
+    
+    final static protected String admin = "admin";
+    private static final Logger logger = LoggerFactory.getLogger(DBIntegrityServiceImlp.class);
+
+    //////////////////////////////////
+    private ResourceDao getDao(Resource resource) {
+        switch (resource) {
+            case PRINCIPAL:
+                return userDao;
+            case ANNOTATION:
+                return annotationDao;
+            case TARGET:
+                return targetDao;
+            case CACHED_REPRESENTATION:
+                return cachedRepresentationDao;
+            case NOTEBOOK:
+                return notebookDao;
+            default:
+                return null;
+        }
+    }
+    
+    public String getRemoteUser(){
+        return remoteUser;
+    }
+    
+    public void setRemoteUser(String currentUser){
+        remoteUser = currentUser;
+    }
+    
+
+    @Override
+    public void setServiceURI(String serviceURI) {
+        userDao.setServiceURI(serviceURI + "users/");
+        cachedRepresentationDao.setServiceURI(serviceURI + "cached/");
+        targetDao.setServiceURI(serviceURI + "targets/");
+        annotationDao.setServiceURI(serviceURI + "annotations/");
+        notebookDao.setServiceURI(serviceURI + "notebooks/");
+    }
+
+    ///////////// GETTERS //////////////////////////
+    @Override
+    public Number getResourceInternalIdentifier(UUID externalID, Resource resource) {
+        return this.getDao(resource).getInternalID(externalID);
+    }
+
+    @Override
+    public Number getResourceInternalIdentifierFromURI(String uri, Resource resource) {
+        return this.getDao(resource).getInternalIDFromURI(uri);
+    }
+
+    @Override
+    public UUID getResourceExternalIdentifier(Number resourceID, Resource resource) {
+        return this.getDao(resource).getExternalID(resourceID);
+    }
+
+    @Override
+    public String getResourceURI(Number resourceID, Resource resource) {
+        return this.getDao(resource).getURIFromInternalID(resourceID);
+    }
+
+    @Override
+    public Annotation getAnnotation(Number annotationID) {
+        if (annotationID != null) {
+            Annotation result = annotationDao.getAnnotationWithoutTargetsAndPermissions(annotationID);
+            result.setOwnerRef(userDao.getURIFromInternalID(annotationDao.getOwner(annotationID)));
+            List<Number> targetIDs = targetDao.retrieveTargetIDs(annotationID);
+            TargetInfoList sis = new TargetInfoList();
+            for (Number targetID : targetIDs) {
+                TargetInfo targetInfo = getTargetInfoFromTarget(targetDao.getTarget(targetID));
+                sis.getTargetInfo().add(targetInfo);
+            }
+            result.setTargets(sis);
+
+            result.setPermissions(this.getPermissions(annotationID, Resource.ANNOTATION));
+            return result;
+        } else {
+            return null;
+        }
+    }
+
+    @Override
+    public Number getAnnotationOwnerID(Number annotationID) {
+        return annotationDao.getOwner(annotationID);
+    }
+    
+    @Override
+    public User getAnnotationOwner(Number annotationID) {
+       return userDao.getUser(annotationDao.getOwner(annotationID)); 
+    }
+
+    ///////////////////////////////////////////////////
+    // TODO UNIT tests
+    @Override
+    public UserWithPermissionList getPermissions(Number resourceID, Resource resource) {
+        if (resourceID != null) {
+            List<Map<Number, String>> principalsPermissions = this.getDao(resource).getPermissions(resourceID);
+            UserWithPermissionList result = new UserWithPermissionList();
+            List<UserWithPermission> list = result.getUserWithPermission();
+            for (Map<Number, String> principalPermission : principalsPermissions) {
+                Number[] principal = new Number[1];
+                principalPermission.keySet().toArray(principal);
+                UserWithPermission userWithPermission = new UserWithPermission();
+                userWithPermission.setRef(userDao.getURIFromInternalID(principal[0]));
+                userWithPermission.setPermission(Permission.fromValue(principalPermission.get(principal[0])));
+                list.add(userWithPermission);
+            }
+            return result;
+
+        }
+        return null;
+    }
+
+////////////////////////////////////////////////////////////////////////
+    @Override
+    public List<Number> getFilteredAnnotationIDs(UUID ownerId, String link, String text, Number inloggedUserID, String access, String namespace, String after, String before) {
+
+        Number ownerID = (ownerId != null) ? userDao.getInternalID(ownerId) : null;
+        if (ownerID != null) {
+            if ("owner".equals(access) && !inloggedUserID.equals(ownerID)) {
+                logger.info("The inlogged user cannot be the owner of the annotations owned by " + ownerId.toString());
+                return null;
+            }
+        }
+
+        //filtering on tables "target" and "annotations_targets"
+        List<Number> annotationIDsForTargets = null;
+        if (link != null) {
+            List<Number> targetIDs = targetDao.getTargetsReferringTo(link);
+            annotationIDsForTargets = annotationDao.getAnnotationIDsForTargets(targetIDs);
+            if (annotationIDsForTargets == null) {
+                logger.info("There are no annotations for the targets referring to " + link + ".");
+                return null;
+            }
+        }
+
+        // filtering in the table "annotation"
+        if (ownerID == null && "owner".equals(access)) {
+            ownerID = inloggedUserID;
+        }
+        List<Number> annotationIDs = annotationDao.getFilteredAnnotationIDs(ownerID, text, namespace, after, before);
+        if (annotationIDs != null) {
+            if (annotationIDsForTargets != null) {
+                annotationIDs.retainAll(annotationIDsForTargets);
+            } else {
+                // nothing to filter on link == null
+            }
+        } else {
+            logger.info("There are no annotations for the given filters on the annotation table.");
+            return null;
+        }
+
+        // filtering on table "annotations_principals_permissions"
+        if ("reader".equals(access) || "writer".equals(access)) {
+            // owner != inloggedUser
+            List<Number> annotationIDsPermission = annotationDao.getAnnotationIDsForUserWithPermission(inloggedUserID, access);
+            if (annotationIDsPermission != null) {
+                annotationIDs.retainAll(annotationIDsPermission);
+            } else {
+                logger.info("There are no annotations for which the inlogged user has access " + access);
+                return null;
+            }
+        } else {
+            // inloggedUser == owner
+        }
+        return annotationIDs;
+    }
+
+    @Override
+    public ReferenceList getAnnotationTargets(Number annotationID) {
+        ReferenceList result = new ReferenceList();
+        List<Number> targetIDs = targetDao.retrieveTargetIDs(annotationID);
+        for (Number targetID : targetIDs) {
+            result.getRef().add(targetDao.getURIFromInternalID(targetID));
+        }
+        return result;
+    }
+
+    @Override
+    public List<String> getTargetsWithNoCachedRepresentation(Number annotationID) {
+        if (annotationID == null) {
+            return null;
+        }
+        List<String> result = new ArrayList<String>();
+        List<Number> targetIDs = targetDao.retrieveTargetIDs(annotationID);
+        for (Number targetID : targetIDs) {
+            List<Number> versions = cachedRepresentationDao.getCachedRepresentationsForTarget(targetID);
+            if (versions == null) {
+                result.add(targetDao.getURIFromInternalID(targetID));
+            } else {
+                if (versions.isEmpty()) {
+                    result.add(targetDao.getURIFromInternalID(targetID));
+                }
+
+            }
+        }
+        return result;
+    }
+
+    @Override
+    public List<String> getUsersWithNoInfo(Number annotationID) {
+        if (annotationID == null) {
+            return null;
+        }
+        List<String> result = new ArrayList<String>();
+        List<Map<Number, String>> usersWithPermissions = annotationDao.getPermissions(annotationID);
+        for (Map<Number, String> userWithPermission : usersWithPermissions) {
+            Number[] userID = new Number[1];
+            userWithPermission.keySet().toArray(userID);
+            User user = userDao.getUser(userID[0]);
+
+            if (user.getDisplayName() == null || user.getDisplayName().trim().isEmpty() || user.getEMail() == null || user.getEMail().trim().isEmpty()) {
+                result.add(userDao.getURIFromInternalID(userID[0]));
+
+            }
+        }
+        return result;
+    }
+
+    @Override
+    public AnnotationInfoList getFilteredAnnotationInfos(UUID ownerId, String word, String text, Number inloggedUserID, String access, String namespace, String after, String before) {
+        List<Number> annotationIDs = this.getFilteredAnnotationIDs(ownerId, word, text, inloggedUserID, access, namespace, after, before);
+        if (annotationIDs != null) {
+            AnnotationInfoList result = new AnnotationInfoList();
+            for (Number annotationID : annotationIDs) {
+                AnnotationInfo annotationInfo = annotationDao.getAnnotationInfoWithoutTargets(annotationID);
+                annotationInfo.setTargets(this.getAnnotationTargets(annotationID));
+                annotationInfo.setOwnerRef(userDao.getURIFromInternalID(annotationDao.getOwner(annotationID)));
+                result.getAnnotationInfo().add(annotationInfo);
+            }
+
+            return result;
+        } else {
+            return null;
+        }
+    }
+
+    @Override
+    public AnnotationInfoList getAllAnnotationInfos() {
+        List<Number> annotationIDs = annotationDao.getAllAnnotationIDs();
+        if (annotationIDs != null) {
+            AnnotationInfoList result = new AnnotationInfoList();
+            for (Number annotationID : annotationIDs) {
+                Number ownerID = annotationDao.getOwner(annotationID);
+                ReferenceList targets = getAnnotationTargets(annotationID);
+                AnnotationInfo annotationInfo = annotationDao.getAnnotationInfoWithoutTargets(annotationID);
+                annotationInfo.setTargets(targets);
+                if (ownerID != null) {
+                    annotationInfo.setOwnerRef(userDao.getURIFromInternalID(ownerID));
+                } else {
+                    annotationInfo.setOwnerRef("ACHTUNG: This annotation does not have an owner in the DB!!!!");
+                }
+                result.getAnnotationInfo().add(annotationInfo);
+            }
+
+            return result;
+        } else {
+            return null;
+        }
+    }
+
+    // TODO unit test
+    @Override
+    public Target getTarget(Number internalID) {
+        Target result = targetDao.getTarget(internalID);
+        result.setSiblingTargets(getTargetsForTheSameLinkAs(internalID));
+        Map<Number, String> cachedIDsFragments = targetDao.getCachedRepresentationFragmentPairs(internalID);
+        CachedRepresentationFragmentList cachedRepresentationFragmentList = new CachedRepresentationFragmentList();
+        for (Number key : cachedIDsFragments.keySet()) {
+            CachedRepresentationFragment cachedRepresentationFragment = new CachedRepresentationFragment();
+            cachedRepresentationFragment.setRef(cachedRepresentationDao.getURIFromInternalID(key));
+            cachedRepresentationFragment.setFragmentString(cachedIDsFragments.get(key));
+            cachedRepresentationFragmentList.getCached().add(cachedRepresentationFragment);
+        }
+        result.setCachedRepresentatinons(cachedRepresentationFragmentList);
+        return result;
+    }
+
+    // TODO unit test
+    @Override
+    public CachedRepresentationInfo getCachedRepresentationInfo(Number internalID) {
+        return cachedRepresentationDao.getCachedRepresentationInfo(internalID);
+    }
+
+    //TODO unit test
+    @Override
+    public InputStream getCachedRepresentationBlob(Number cachedID) {
+        return cachedRepresentationDao.getCachedRepresentationBlob(cachedID);
+    }
+
+    @Override
+    public ReferenceList getTargetsForTheSameLinkAs(Number targetID) {
+        List<Number> targetIDs = targetDao.getTargetsForLink(targetDao.getLink(targetID));
+        ReferenceList referenceList = new ReferenceList();
+        for (Number siblingID : targetIDs) {
+            referenceList.getRef().add(targetDao.externalIDtoURI(targetDao.getExternalID(siblingID).toString()));
+        }
+        return referenceList;
+    }
+
+    @Override
+    public User getUser(Number userID) {
+        return userDao.getUser(userID);
+    }
+
+    @Override
+    public User getUserByInfo(String eMail) {
+        return userDao.getUserByInfo(eMail);
+    }
+
+    @Override
+    public String getUserRemoteID(Number internalID) {
+        return userDao.getRemoteID(internalID);
+    }
+
+    @Override
+    public Permission getPermission(Number annotationID, Number userID) {
+        return annotationDao.getPermission(annotationID, userID);
+    }
+
+    @Override
+    public Number getUserInternalIDFromRemoteID(String remoteID) {
+        return userDao.getUserInternalIDFromRemoteID(remoteID);
+    }
+
+    @Override
+    public String getTypeOfUserAccount(Number userID) {
+        return userDao.getTypeOfUserAccount(userID);
+    }
+    
+    @Override
+    public User getDataBaseAdmin(){
+        return userDao.getUser(userDao.getDBAdminID());
+    }
+    
+
+    @Override
+    public boolean canRead(Number userID, Number annotationID) {
+        if (userID.equals(annotationDao.getOwner(annotationID)) || userDao.getTypeOfUserAccount(userID).equals(admin)) {
+            return true;
+        }
+
+        final Permission permission = annotationDao.getPermission(annotationID, userID);
+        if (permission != null) {
+            return (permission.value().equals(Permission.WRITER.value()) || permission.value().equals(Permission.READER.value()));
+        } else {
+            return false;
+        }
+    }
+
+    @Override
+    public boolean canWrite(Number userID, Number annotationID) {
+        if (userID.equals(annotationDao.getOwner(annotationID)) || userDao.getTypeOfUserAccount(userID).equals(admin)) {
+            return true;
+        }
+        final Permission permission = annotationDao.getPermission(annotationID, userID);
+        if (permission != null) {
+            return (permission.value().equals(Permission.WRITER.value()));
+        } else {
+            return false;
+        }
+    }
+    
+    ////// noetbooks ///////
+
+    @Override
+    public NotebookInfoList getNotebooks(Number principalID, String permission) {
+        NotebookInfoList result = new NotebookInfoList();
+        if (permission.equalsIgnoreCase("reader") || permission.equalsIgnoreCase("writer")) {
+            List<Number> notebookIDs = notebookDao.getNotebookIDs(principalID, Permission.fromValue(permission));
+            for (Number notebookID : notebookIDs) {
+                NotebookInfo notebookInfo = notebookDao.getNotebookInfoWithoutOwner(notebookID);
+                Number ownerID = notebookDao.getOwner(notebookID);
+                notebookInfo.setOwnerRef(userDao.getURIFromInternalID(ownerID));
+                result.getNotebookInfo().add(notebookInfo);
+            }
+        } else {
+            if (permission.equalsIgnoreCase("owner")) {
+                List<Number> notebookIDs = notebookDao.getNotebookIDsOwnedBy(principalID);
+                String ownerRef = userDao.getURIFromInternalID(principalID);
+                for (Number notebookID : notebookIDs) {
+                    NotebookInfo notebookInfo = notebookDao.getNotebookInfoWithoutOwner(notebookID);
+                    notebookInfo.setOwnerRef(ownerRef);
+                    result.getNotebookInfo().add(notebookInfo);
+                }
+            } else {
+                return null;
+            }
+        }
+        return result;
+    }
+
+    @Override
+    public boolean hasAccess(Number notebookID, Number principalID, Permission permission) {
+        List<Number> notebookIDs = notebookDao.getNotebookIDs(principalID, permission);
+        if (notebookIDs == null) {
+            return false;
+        }
+        return notebookIDs.contains(notebookID);
+    }
+
+    @Override
+    public ReferenceList getNotebooksOwnedBy(Number principalID) {
+        ReferenceList result = new ReferenceList();
+        List<Number> notebookIDs = notebookDao.getNotebookIDsOwnedBy(principalID);
+        for (Number notebookID : notebookIDs) {
+            String reference = notebookDao.getURIFromInternalID(notebookID);
+            result.getRef().add(reference);
+        }
+        return result;
+    }
+
+    @Override
+    public ReferenceList getPrincipals(Number notebookID, String permission) {
+        ReferenceList result = new ReferenceList();
+        List<Number> principalIDs = userDao.getPrincipalIDsWithPermissionForNotebook(notebookID, Permission.fromValue(permission));
+        for (Number principalID : principalIDs) {
+            String reference = userDao.getURIFromInternalID(principalID);
+            result.getRef().add(reference);
+        }
+        return result;
+    }
+
+    @Override
+    public Notebook getNotebook(Number notebookID) {
+        Notebook result = notebookDao.getNotebookWithoutAnnotationsAndPermissionsAndOwner(notebookID);
+
+        result.setOwnerRef(userDao.getURIFromInternalID(notebookDao.getOwner(notebookID)));
+
+        ReferenceList annotations = new ReferenceList();
+        List<Number> annotationIDs = annotationDao.getAnnotations(notebookID);
+        for (Number annotationID : annotationIDs) {
+            annotations.getRef().add(annotationDao.getURIFromInternalID(annotationID));
+        }
+        result.setAnnotations(annotations);
+
+        UserWithPermissionList ups = new UserWithPermissionList();
+        List<Permission> permissions = new ArrayList<Permission>();
+        permissions.add(Permission.READER);
+        permissions.add(Permission.WRITER);
+        for (Permission permission : permissions) {
+            List<Number> users = userDao.getPrincipalIDsWithPermissionForNotebook(notebookID, permission);
+            if (users != null) {
+                for (Number user : users) {
+                    UserWithPermission up = new UserWithPermission();
+                    up.setRef(userDao.getURIFromInternalID(user));
+                    up.setPermission(permission);
+                    ups.getUserWithPermission().add(up);
+                }
+            }
+        }
+        result.setPermissions(ups);
+        return result;
+    }
+
+    @Override
+    public Number getNotebookOwner(Number notebookID) {
+        return notebookDao.getOwner(notebookID);
+    }
+
+    /////////////////////////////////////////////////////////////
+    @Override
+    public ReferenceList getAnnotationsForNotebook(Number notebookID, int startAnnotation, int maximumAnnotations, String orderedBy, boolean desc) {
+        List<Number> annotationIDs = annotationDao.getAnnotations(notebookID);
+
+        if (startAnnotation < -1) {
+            logger.info("Variable's startAnnotation value " + startAnnotation + " is invalid. I will return null.");
+            return null;
+        }
+
+        if (maximumAnnotations < -1) {
+            logger.info("Variable's maximumAnnotations value " + maximumAnnotations + " is invalid. I will return null.");
+            return null;
+        }
+
+        int offset = (startAnnotation > 0) ? startAnnotation - 1 : 0;
+        String direction = desc ? "DESC" : "ASC";
+        List<Number> selectedAnnotIDs = annotationDao.sublistOrderedAnnotationIDs(annotationIDs, offset, maximumAnnotations, orderedBy, direction);
+        ReferenceList references = new ReferenceList();
+        for (Number annotationID : selectedAnnotIDs) {
+            references.getRef().add(annotationDao.getURIFromInternalID(annotationID));
+        }
+        return references;
+    }
+
+    ///// UPDATERS /////////////////
+    @Override
+    public boolean updateAccount(UUID userExternalID, String account) {
+        return userDao.updateAccount(userExternalID, account);
+    }
+
+    @Override
+    public int updateAnnotationPrincipalPermission(Number annotationID, Number userID, Permission permission) {
+        if (permission != null) {
+            return annotationDao.updateAnnotationPrincipalPermission(annotationID, userID, permission);
+        } else {
+            return annotationDao.deleteAnnotationPrincipalPermission(annotationID, userID);
+        }
+    }
+
+    @Override
+    public int updatePermissions(Number annotationID, UserWithPermissionList permissionList) {
+
+        List<UserWithPermission> usersWithPermissions = permissionList.getUserWithPermission();
+        int result = 0;
+        for (UserWithPermission userWithPermission : usersWithPermissions) {
+            Number userID = userDao.getInternalID(UUID.fromString(userDao.stringURItoExternalID(userWithPermission.getRef())));
+            if (userID != null) {
+                Permission permission = userWithPermission.getPermission();
+                Permission currentPermission = annotationDao.getPermission(annotationID, userID);
+                if (currentPermission != null) {
+                    if (!permission.value().equals(currentPermission.value())) {
+                        result = result + annotationDao.updateAnnotationPrincipalPermission(annotationID, userID, permission);
+                    }
+                } else {
+                    result = result + annotationDao.addAnnotationPrincipalPermission(annotationID, userID, permission);
+                }
+            }
+        }
+
+        return result;
+    }
+
+    // TODO: optimize (not chnaged targets should not be deleted)
+    // TODO: unit test
+    @Override
+    public int updateAnnotation(Annotation annotation) {
+        int updatedAnnotations = annotationDao.updateAnnotation(annotation, userDao.getInternalIDFromURI(annotation.getOwnerRef()));
+        Number annotationID = annotationDao.getInternalIDFromURI(annotation.getURI());
+        int deletedTargets = annotationDao.deleteAllAnnotationTarget(annotationID);
+        int deletedPrinsipalsPermissions = annotationDao.deleteAnnotationPrincipalPermissions(annotationID);
+        int addedTargets = addTargets(annotation, annotationID);
+        int addedPrincipalsPermissions = addPrincipalsPermissions(annotation.getPermissions().getUserWithPermission(), annotationID);
+        return updatedAnnotations;
+    }
+
+    // TODO: unit test
+    @Override
+    public int updateAnnotationBody(Number internalID, AnnotationBody annotationBody) {
+        String[] body = annotationDao.retrieveBodyComponents(annotationBody);
+        return annotationDao.updateAnnotationBody(internalID, body[0], body[1], annotationBody.getXmlBody() != null);
+    }
+
+    @Override
+    public Number updateUser(User user) {
+        return userDao.updateUser(user);
+    }
+    /// notebooks ///
+
+    @Override
+    public boolean updateNotebookMetadata(Number notebookID, NotebookInfo upToDateNotebookInfo) {
+        Number ownerID = userDao.getInternalIDFromURI(upToDateNotebookInfo.getOwnerRef());
+        return notebookDao.updateNotebookMetadata(notebookID, upToDateNotebookInfo.getTitle(), ownerID);
+    }
+
+    @Override
+    public boolean addAnnotationToNotebook(Number notebookID, Number annotationID) {
+        return notebookDao.addAnnotationToNotebook(notebookID, annotationID);
+    }
+
+    /////////////// ADDERS  /////////////////////////////////
+    @Override
+    public Number[] addCachedForTarget(Number targetID, String fragmentDescriptor, CachedRepresentationInfo cachedInfo, InputStream cachedBlob) {
+        Number[] result = new Number[2];
+        result[1] = cachedRepresentationDao.getInternalIDFromURI(cachedInfo.getURI());
+        if (result[1] == null) {
+            result[1] = cachedRepresentationDao.addCachedRepresentation(cachedInfo, cachedBlob);
+        }
+        result[0] = targetDao.addTargetCachedRepresentation(targetID, result[1], fragmentDescriptor);
+        return result;
+
+    }
+
+    // TODo: mapping uri to external ID
+    @Override
+    public Map<String, String> addTargetsForAnnotation(Number annotationID, List<TargetInfo> targets) {
+        Map<String, String> result = new HashMap<String, String>();
+        Number targetIDRunner;
+        for (TargetInfo targetInfo : targets) {
+            targetIDRunner = targetDao.getInternalIDFromURI(targetInfo.getRef());
+            if (targetIDRunner != null) {
+                int affectedRows = annotationDao.addAnnotationTarget(annotationID, targetIDRunner);
+            } else {
+                Target newTarget = createFreshTarget(targetInfo);
+                Number targetID = targetDao.addTarget(newTarget);
+                String targetTemporaryID = targetDao.stringURItoExternalID(targetInfo.getRef());
+                result.put(targetTemporaryID, targetDao.getExternalID(targetID).toString());
+                int affectedRows = annotationDao.addAnnotationTarget(annotationID, targetID);
+            }
+        }
+        return result;
+    }
+
+    @Override
+    public Number addUsersAnnotation(Number ownerID, Annotation annotation) {
+        Number annotationID = annotationDao.addAnnotation(annotation, ownerID);
+        int affectedAnnotRows = addTargets(annotation, annotationID);
+        if (annotation.getPermissions() != null) {
+            if (annotation.getPermissions().getUserWithPermission() != null) {
+                int addedPrincipalsPermissions = this.addPrincipalsPermissions(annotation.getPermissions().getUserWithPermission(), annotationID);
+            }
+        }
+        return annotationID;
+    }
+
+    @Override
+    public Number addUser(User user, String remoteID) {
+        if (userDao.userExists(user)) {
+            return null;
+        } else {
+            return userDao.addUser(user, remoteID);
+        }
+    }
+
+    @Override
+    public int addAnnotationPrincipalPermission(Number annotationID, Number userID, Permission permission) {
+        return annotationDao.addAnnotationPrincipalPermission(annotationID, userID, permission);
+    }
+
+    //////////// notebooks //////
+    @Override
+    public Number createNotebook(Notebook notebook, Number ownerID) {
+        Number notebookID = notebookDao.createNotebookWithoutPermissionsAndAnnotations(notebook, ownerID);
+        boolean updateOwner = notebookDao.setOwner(notebookID, ownerID);
+        List<UserWithPermission> permissions = notebook.getPermissions().getUserWithPermission();
+        for (UserWithPermission principalPermission : permissions) {
+            Number principalID = userDao.getInternalIDFromURI(principalPermission.getRef());
+            Permission permission = principalPermission.getPermission();
+            boolean updatePermissions = notebookDao.addPermissionToNotebook(notebookID, principalID, permission);
+        }
+        return notebookID;
+    }
+
+    @Override
+    public boolean createAnnotationInNotebook(Number notebookID, Annotation annotation, Number ownerID) {
+        Number newAnnotationID = this.addUsersAnnotation(ownerID, annotation);
+        return notebookDao.addAnnotationToNotebook(notebookID, newAnnotationID);
+    }
+
+    ////////////// DELETERS //////////////////
+    
+   
+    
+    
+    @Override
+    public int deleteUser(Number userID) {
+        return userDao.deleteUser(userID);
+    }
+
+    
+    @Override
+    public int deleteUserSafe(Number userID) {
+        return userDao.deleteUserSafe(userID);
+    }
+
+    @Override
+    public int deleteCachedRepresentation(Number internalID) {
+        
+        if (internalID == null) {
+            logger.debug("Cached's internalID is null");
+            return 0;
+        }
+        
+        if (targetDao.cachedIsInUse(internalID)) {
+            logger.debug("Cached Repr. is in use, and cannot be deleted.");
+            return 0;
+        }
+
+        return cachedRepresentationDao.deleteCachedRepresentation(internalID);
+    };
+    
+    
+    @Override
+    public int[] deleteCachedRepresentationOfTarget(Number versionID, Number cachedID) {
+        int[] result = new int[2];
+        result[0] = targetDao.deleteTargetCachedRepresentation(versionID, cachedID);
+        if (result[0] > 0) {
+            result[1] = cachedRepresentationDao.deleteCachedRepresentation(cachedID);
+        } else {
+            result[1] = 0;
+
+        }
+        return result;
+    }
+
+    @Override
+    public int[] deleteAllCachedRepresentationsOfTarget(Number targetID) {
+        int[] result = new int[2];
+        result[0] = 0;
+        result[1] = 0;
+        List<Number> cachedIDs = cachedRepresentationDao.getCachedRepresentationsForTarget(targetID);
+        for (Number cachedID : cachedIDs) {
+            int[] currentResult = this.deleteCachedRepresentationOfTarget(targetID, cachedID);
+            result[0] = result[0] + currentResult[0];
+            result[1] = result[1] + currentResult[1];
+        }
+        return result;
+    }
+
+    @Override
+    public int[] deleteAnnotation(Number annotationID) {
+        int[] result = new int[5];
+        result[1] = annotationDao.deleteAnnotationPrincipalPermissions(annotationID);
+        List<Number> targetIDs = targetDao.retrieveTargetIDs(annotationID);
+        result[2] = annotationDao.deleteAllAnnotationTarget(annotationID);
+        result[3] = 0;
+        if (targetIDs != null) {
+            for (Number targetID : targetIDs) {
+                this.deleteAllCachedRepresentationsOfTarget(targetID);
+                result[3] = result[3] + this.deleteTarget(targetID);
+
+            }
+        }
+        
+        result[4] = annotationDao.deleteAnnotationFromAllNotebooks(annotationID);
+        
+        result[0] = annotationDao.deleteAnnotation(annotationID);
+        return result;
+    }
+    
+    ////////////////////// DELETERS ////////////////////////
+    @Override
+    public int deleteTarget(Number internalID) {
+        if (internalID == null) {
+            logger.debug("internalID of the target is null.");
+            return 0;
+        }
+        
+        if (annotationDao.targetIsInUse(internalID)) {
+            logger.debug("The target is in use, and cannot be deleted.");
+            return 0;
+        }
+        
+        return targetDao.deleteTarget(internalID);
+
+    }
+
+    @Override
+    public boolean deleteNotebook(Number notebookID) {
+        if (notebookDao.deleteAllPermissionsForNotebook(notebookID) || notebookDao.deleteAllAnnotationsFromNotebook(notebookID)) {
+            return notebookDao.deleteNotebook(notebookID);
+        } else {
+            return false;
+        }
+    }
+
+////////////// HELPERS ////////////////////
+    ////////////////////////////////////////
+    @Override
+    public ResponseBody makeAnnotationResponseEnvelope(Number annotationID) {
+        ResponseBody result = new ResponseBody();
+        Annotation annotation = this.getAnnotation(annotationID);
+        result.setAnnotation(annotation);
+        List<String> targetsNoCached = this.getTargetsWithNoCachedRepresentation(annotationID);
+        ActionList actionList = new ActionList();
+        result.setActionList(actionList);
+        actionList.getAction().addAll(makeActionList(targetsNoCached, AnnotationActionName.CREATE_CACHED_REPRESENTATION.value()));
+        return result;
+    }
+
+    @Override
+    public ResponseBody makeNotebookResponseEnvelope(Number notebookID) {
+        ResponseBody result = new ResponseBody();
+        result.setPermissions(null);
+        Notebook notebook = this.getNotebook(notebookID);
+        result.setNotebook(notebook);
+        return result;
+    }
+
+    @Override
+    public ResponseBody makePermissionResponseEnvelope(Number resourceID, Resource resource) {
+        ResponseBody result = new ResponseBody();
+        UserWithPermissionList permissions = this.getPermissions(resourceID, resource);
+        result.setPermissions(permissions);
+        List<String> usersWithNoInfo = this.getUsersWithNoInfo(resourceID);
+        ActionList actionList = new ActionList();
+        result.setActionList(actionList);
+        actionList.getAction().addAll(makeActionList(usersWithNoInfo, PermissionActionName.PROVIDE_USER_INFO.value()));
+        return result;
+    }
+
+    private List<Action> makeActionList(List<String> resourceURIs, String message) {
+        if (resourceURIs != null) {
+            if (resourceURIs.isEmpty()) {
+                return (new ArrayList<Action>());
+            } else {
+                List<Action> result = new ArrayList<Action>();
+                for (String resourceURI : resourceURIs) {
+                    Action action = new Action();
+                    result.add(action);
+                    action.setMessage(message);
+                    action.setObject(resourceURI);
+                }
+                return result;
+            }
+        } else {
+            return null;
+        }
+    }
+
+    //// priveee ///
+    private Target createFreshTarget(TargetInfo targetInfo) {
+        Target target = new Target();
+        target.setLink(targetInfo.getLink());
+        target.setVersion(targetInfo.getVersion());
+        return target;
+    }
+
+    private int addTargets(Annotation annotation, Number annotationID) {
+        List<TargetInfo> targets = annotation.getTargets().getTargetInfo();
+        Map<String, String> targetIdPairs = addTargetsForAnnotation(annotationID, targets);
+        AnnotationBody annotationBody = annotation.getBody();
+        String bodyText;
+        String newBodyText;
+        String mimeType;
+        if (annotationBody.getXmlBody() != null) {
+            bodyText = Helpers.elementToString(annotation.getBody().getXmlBody().getAny());
+            mimeType = annotationBody.getXmlBody().getMimeType();
+        } else {
+            if (annotation.getBody().getTextBody() != null) {
+                bodyText = annotation.getBody().getTextBody().getBody();
+                mimeType = annotationBody.getTextBody().getMimeType();
+            } else {
+                logger.error("The client has sent ill-formed annotation body.");
+                return -1;
+            }
+        }
+        newBodyText = Helpers.replace(bodyText, targetIdPairs);
+        return annotationDao.updateAnnotationBody(annotationID, newBodyText, mimeType, annotationBody.getXmlBody() != null);
+    }
+
+    private int addPrincipalsPermissions(List<UserWithPermission> permissions, Number annotationID) {
+        int addedPermissions = 0;
+        for (UserWithPermission permission : permissions) {
+            addedPermissions = addedPermissions + annotationDao.addAnnotationPrincipalPermission(annotationID, userDao.getInternalIDFromURI(permission.getRef()), permission.getPermission());
+
+        }
+        return addedPermissions;
+    }
+
+    private TargetInfo getTargetInfoFromTarget(Target target) {
+        TargetInfo targetInfo = new TargetInfo();
+        targetInfo.setRef(target.getURI());
+        targetInfo.setLink(target.getLink());
+        targetInfo.setVersion(target.getVersion());
+        return targetInfo;
+    }
+}
Index: /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/java/eu/dasish/annotation/backend/dao/impl/JdbcAnnotationDao.java
===================================================================
--- /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/java/eu/dasish/annotation/backend/dao/impl/JdbcAnnotationDao.java	(revision 4603)
+++ /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/java/eu/dasish/annotation/backend/dao/impl/JdbcAnnotationDao.java	(revision 4603)
@@ -0,0 +1,665 @@
+/*
+ * Copyright (C) 2013 DASISH
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
+ */
+package eu.dasish.annotation.backend.dao.impl;
+
+import eu.dasish.annotation.backend.Helpers;
+import eu.dasish.annotation.backend.dao.AnnotationDao;
+import eu.dasish.annotation.schema.Annotation;
+import eu.dasish.annotation.schema.AnnotationBody;
+import eu.dasish.annotation.schema.AnnotationBody.TextBody;
+import eu.dasish.annotation.schema.AnnotationBody.XmlBody;
+import eu.dasish.annotation.schema.AnnotationInfo;
+import eu.dasish.annotation.schema.Permission;
+import java.lang.String;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Timestamp;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import javax.sql.DataSource;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.jdbc.core.RowMapper;
+
+/**
+ * Created on : Jun 27, 2013, 10:30:52 AM
+ *
+ * @author Peter Withers <peter.withers@mpi.nl>
+ */
+public class JdbcAnnotationDao extends JdbcResourceDao implements AnnotationDao {
+
+    private final Logger loggerAnnotationDao = LoggerFactory.getLogger(JdbcAnnotationDao.class);
+
+    public JdbcAnnotationDao(DataSource dataSource) {
+        setDataSource(dataSource);
+        internalIdName = annotation_id;
+        resourceTableName = annotationTableName;
+
+    }
+
+    @Override
+    public void setServiceURI(String serviceURI) {
+        _serviceURI = serviceURI;
+    }
+
+    ///////////// GETTERS /////////////
+   
+
+    ///////////////////////////////////////////////////////////////////
+    @Override
+    public List<Map<Number, String>>  getPermissions(Number annotationID) {
+        if (annotationID == null) {
+            loggerAnnotationDao.debug(nullArgument);
+            return null;
+        }
+        StringBuilder sql = new StringBuilder("SELECT ");
+        sql.append(principal_id).append(",").append(permission).append(" FROM ").append(permissionsTableName).append(" WHERE ").append(annotation_id).append("  = ?");
+        logger.debug("Parameter "+annotation_id+" := "+annotationID.intValue());
+        return this.loggedQuery(sql.toString(), principalsPermissionsRowMapper, annotationID);
+    }
+    
+    
+    @Override
+    public Permission getPermission(Number annotationID, Number userID) {
+        if (annotationID == null) {
+            loggerAnnotationDao.debug("annotationID: " + nullArgument);
+            return null;
+        }
+
+        if (userID == null) {
+            loggerAnnotationDao.debug("userID: " + nullArgument);
+            return null;
+        }
+        
+        Map<String, Number> params = new HashMap<String,Number>();
+        params.put("annotationId", annotationID);
+        params.put("principalId", userID);
+        
+        StringBuilder sql = new StringBuilder("SELECT ");
+        sql.append(permission).append(" FROM ").append(permissionsTableName).append(" WHERE ").
+                append(annotation_id).append("  =  :annotationId ").append(" AND ").
+                append(principal_id).append("  = :principalId").append(" LIMIT 1");
+        List<Permission> result = this.loggedQuery(sql.toString(), permissionRowMapper, params);
+       
+        if (result == null) {
+            return null;
+        }
+        if (result.isEmpty()) {
+            return null;
+        }
+        return result.get(0);
+    }
+    private final RowMapper<Permission> permissionRowMapper = new RowMapper<Permission>() {
+        @Override
+        public Permission mapRow(ResultSet rs, int rowNumber) throws SQLException {
+            return Permission.fromValue(rs.getString(permission));
+        }
+    };
+
+    ////////////////////////////////////////////////////////////////////////
+    @Override
+    public List<Number> getFilteredAnnotationIDs(Number ownerID, String text, String namespace, String after, String before) {
+
+        StringBuilder sql = new StringBuilder("SELECT DISTINCT ");
+        sql.append(annotation_id).append(" FROM ").append(annotationTableName).append(" WHERE TRUE ");
+        Map<String, Object> params = new HashMap<String, Object>();
+
+        if (ownerID != null) {
+            sql.append(" AND ").append(owner_id).append("  = :ownerId");
+            params.put("ownerId", ownerID);
+        }
+
+        if (after != null) {
+            sql.append(" AND ").append(last_modified).append("  > :afterTimestamp");
+            params.put("afterTimestamp", Timestamp.valueOf(after));
+        }
+
+        if (before != null) {
+            sql.append(" AND ").append(last_modified).append("  < :beforeTimestamp");
+            params.put("beforeTimestamp", Timestamp.valueOf(before));
+        }
+
+        if (text != null) {
+            sql.append(" AND ").append(body_text).append("  LIKE '%").append(text).append("%'");
+        }
+
+        return this.loggedQuery(sql.toString(), internalIDRowMapper, params);
+    }
+
+    ///////////////////////////////////////////////////////////////////////////////////
+    @Override
+    public List<Number> getAnnotationIDsForUserWithPermission(Number userID, String access) {
+
+        if (userID == null) {
+            loggerAnnotationDao.debug("userID: " + nullArgument);
+            return null;
+        }
+
+        if (access == null) {
+            logger.info("The access argument is null. I assign it a default value 'reader'.");
+            access = "reader";
+        }
+
+
+        StringBuilder sql = new StringBuilder("SELECT ");
+        sql.append(annotation_id).append(" FROM ").append(permissionsTableName).append(" WHERE ").
+                append(principal_id).append("  = ?").append(" AND ").
+                append(permission).append("  = ").append(access);
+        return this.loggedQuery(sql.toString(), internalIDRowMapper, userID);
+    }
+
+    //////////////////////////////
+    @Override
+    public List<Number> getAnnotationIDsForTargets(List<Number> targetIDs) {
+        if (targetIDs == null) {
+            loggerAnnotationDao.debug("targetIDs: " + nullArgument);
+            return null;
+        }
+        if (targetIDs.isEmpty()) {
+            return new ArrayList<Number>();
+        }
+        String values = makeListOfValues(targetIDs);
+        StringBuilder query = new StringBuilder("SELECT DISTINCT ");
+        query.append(annotation_id).append(" FROM ").append(annotationsTargetsTableName).append(" WHERE ").append(target_id).append(" IN ");
+        query.append(values);
+        return this.loggedQuery(query.toString(), internalIDRowMapper);
+    }
+
+    /////////////////////////////////////////
+    @Override
+    public List<Number> getAllAnnotationIDs() {
+        StringBuilder sql = new StringBuilder("SELECT ");
+        sql.append(annotation_id).append(" , ").append(last_modified).append(" FROM ").append(annotationTableName).append(" ORDER BY ").append(last_modified).append(" DESC");
+        return this.loggedQuery(sql.toString(), internalIDRowMapper);
+    }
+
+    @Override
+    public List<Number> sublistOrderedAnnotationIDs(List<Number> annotationIDs, int offset, int limit, String orderedBy, String direction) {
+        if (annotationIDs == null) {
+            return null;
+        }
+
+        if (annotationIDs.isEmpty()) {
+            return annotationIDs;
+        }
+
+        
+        String values = makeListOfValues(annotationIDs);
+        Map<String, Object> params = new HashMap<String, Object>();
+        params.put("offset", offset);
+        params.put("limit", limit);
+
+        StringBuilder query = new StringBuilder("SELECT DISTINCT ");
+        query.append(annotation_id).append(" FROM ").append(annotationsTargetsTableName).append(" WHERE ").append(annotation_id).append(" IN ");
+        query.append(values).append(" ORDER BY ").append(orderedBy).append(" ").append(direction).append(" ");
+
+        if (limit > -1) {
+            query.append(direction).append(" LIMIT :limit ");
+        }
+
+        query.append(" OFFSET :offset ");
+        return this.loggedQuery(query.toString(), internalIDRowMapper, params);
+    }
+
+    //////////////////////////////////////////////////////////////////////
+    @Override
+    public AnnotationInfo getAnnotationInfoWithoutTargets(Number annotationID) {
+        if (annotationID == null) {
+            loggerAnnotationDao.debug("annotationID: " + nullArgument);
+            return null;
+        }
+        StringBuilder sql = new StringBuilder("SELECT  ");
+        sql.append(annotationStar).append(" FROM ").append(annotationTableName).append(" WHERE ").append(annotation_id).append("  = ? ");
+        List<AnnotationInfo> result = this.loggedQuery(sql.toString(), annotationInfoRowMapper, annotationID);
+        if (result == null) {
+            return null;
+        }
+        if (result.isEmpty()) {
+            return null;
+        }
+
+        return result.get(0);
+    }
+    private final RowMapper<AnnotationInfo> annotationInfoRowMapper = new RowMapper<AnnotationInfo>() {
+        @Override
+        public AnnotationInfo mapRow(ResultSet rs, int rowNumber) throws SQLException {
+            AnnotationInfo annotationInfo = new AnnotationInfo();
+            annotationInfo.setRef(externalIDtoURI(rs.getString(external_id)));
+            annotationInfo.setHeadline(rs.getString(headline));
+            annotationInfo.setLastModified(timeStampToXMLGregorianCalendar(rs.getString(last_modified)));
+            return annotationInfo;
+        }
+    };
+
+    /////////////////////////////////////////////////
+    /**
+     *
+     * @param annotationIDs
+     * @return list of annotation references corresponding to the annotation-ids
+     * from the input list if the input list is null or empty (zero elements)
+     * returns an empty list there may be annotationIDs which are not in the DB
+     * (so that's why we need this method).
+     */
+    @Override
+    public List<String> getAnnotationREFs(List<Number> annotationIDs) {
+        if (annotationIDs == null) {
+            loggerAnnotationDao.debug("annotationIDs: " + nullArgument);
+            return null;
+        }
+        if (annotationIDs.isEmpty()) {
+            return (new ArrayList<String>());
+        }
+
+        String values = makeListOfValues(annotationIDs);
+        StringBuilder sql = new StringBuilder("SELECT DISTINCT ");
+        sql.append(external_id).append(" FROM ").append(annotationTableName).append(" WHERE ").append(annotation_id).append("  IN ").append(values);
+        return this.loggedQuery(sql.toString(), annotationREFRowMapper);
+    }
+    private final RowMapper<String> annotationREFRowMapper = new RowMapper<String>() {
+        @Override
+        public String mapRow(ResultSet rs, int rowNumber) throws SQLException {
+            return externalIDtoURI(rs.getString(external_id));
+        }
+    };
+
+    //////////////////////////////////////////////////////////////////////////
+    @Override
+    public Annotation getAnnotationWithoutTargetsAndPermissions(Number annotationID) {
+        if (annotationID == null) {
+            loggerAnnotationDao.debug("annotationID: " + nullArgument);
+            return null;
+        }
+        StringBuilder sql = new StringBuilder("SELECT ");
+        sql.append(annotationStar).append(" FROM ").append(annotationTableName).append(" WHERE ").append(annotation_id).append("= ? LIMIT  1");
+        List<Annotation> respond = this.loggedQuery(sql.toString(), annotationRowMapper, annotationID);
+        return (respond.isEmpty() ? null : respond.get(0));
+    }
+    private final RowMapper<Annotation> annotationRowMapper = new RowMapper<Annotation>() {
+        @Override
+        public Annotation mapRow(ResultSet rs, int rowNumber) throws SQLException {
+            Annotation annotation = new Annotation();
+            annotation.setHeadline(rs.getString(headline));
+            AnnotationBody body = new AnnotationBody();
+            if (rs.getBoolean(is_xml)) {
+                body.setTextBody(null);
+                XmlBody xmlBody = new XmlBody();
+                xmlBody.setMimeType(rs.getString(body_mimetype));
+                xmlBody.setAny(Helpers.stringToElement(rs.getString(body_text)));
+                body.setXmlBody(xmlBody);
+            } else {
+                body.setXmlBody(null);
+                TextBody textBody = new TextBody();
+                textBody.setMimeType(rs.getString(body_mimetype));
+                textBody.setBody(rs.getString(body_text));
+                body.setTextBody(textBody);
+            }
+            annotation.setBody(body);
+
+            annotation.setTargets(null);
+            annotation.setURI(externalIDtoURI(rs.getString(external_id)));
+            annotation.setLastModified(timeStampToXMLGregorianCalendar(rs.getString(last_modified)));
+            return annotation;
+        }
+    };
+
+    @Override
+    public Number getOwner(Number annotationID) {
+        if (annotationID == null) {
+            loggerAnnotationDao.debug("annotationID: " + nullArgument);
+            return null;
+        }
+        StringBuilder sql = new StringBuilder("SELECT ");
+        sql.append(owner_id).append(" FROM ").append(annotationTableName).append(" WHERE ").
+                append(annotation_id).append("= ? LIMIT  1");
+        List<Number> respond = this.loggedQuery(sql.toString(), ownerIDRowMapper, annotationID);
+        return (respond.isEmpty() ? null : respond.get(0));
+    }
+
+    /////////////////////////////
+//    @Override
+//    public boolean annotationIsInUse(Number annotationID) {
+//        StringBuilder sqlNotebooks = new StringBuilder("SELECT ");
+//        sqlNotebooks.append(notebook_id).append(" FROM ").append(notebooksAnnotationsTableName).append(" WHERE ").append(annotation_id).append("= ? LIMIT 1");
+//        List<Number> resultNotebooks = this.loggedQuery(sqlNotebooks.toString(), notebookIDRowMapper, annotationID);
+//        if (resultNotebooks.size() > 0) {
+//            return true;
+//        }
+//
+//        StringBuilder sqlTargets = new StringBuilder("SELECT ");
+//        sqlTargets.append(target_id).append(" FROM ").append(annotationsTargetsTableName).append(" WHERE ").append(annotation_id).append("= ? LIMIT 1");
+//        List<Number> resultTargets = this.loggedQuery(sqlTargets.toString(), targetIDRowMapper, annotationID);
+//        if (resultTargets.size() > 0) {
+//            return true;
+//        }
+//
+//        StringBuilder sqlPermissions = new StringBuilder("SELECT ");
+//        sqlPermissions.append(principal_id).append(" FROM ").append(permissionsTableName).append(" WHERE ").append(annotation_id).append("= ? LIMIT 1");
+//        List<Number> resultPermissions = this.loggedQuery(sqlPermissions.toString(), principalIDRowMapper, annotationID);
+//        return (resultPermissions.size() > 0);
+//    }
+    
+     @Override
+    public List<Number> getAnnotations(Number notebookID) {
+
+        if (notebookID == null) {
+            loggerAnnotationDao.debug("notebookID: " + nullArgument);
+            return null;
+        }
+
+        StringBuilder sql = new StringBuilder("SELECT ");
+        sql.append(annotation_id).
+                append(" FROM ").append(notebooksAnnotationsTableName).append(" WHERE ").
+                append(notebook_id).append(" = :notebookID");
+        return this.loggedQuery(sql.toString(), internalIDRowMapper, notebookID);
+
+    }
+     
+       /////////////////////////////////////////////////
+    @Override
+    public boolean targetIsInUse(Number targetID) {
+        if (targetID == null) {
+            loggerAnnotationDao.debug("targetID: " + nullArgument);
+            return false;
+        }
+
+
+        StringBuilder sqlAnnotations = new StringBuilder("SELECT ");
+        sqlAnnotations.append(annotation_id).append(" FROM ").append(annotationsTargetsTableName).append(" WHERE ").append(target_id).append(" = ? LIMIT 1");
+        List<Number> resultAnnotations = this.loggedQuery(sqlAnnotations.toString(), internalIDRowMapper, targetID);
+        if (resultAnnotations == null) {
+            return false;
+        }
+        return (resultAnnotations.size() > 0);
+    }
+    
+
+
+    //////////// UPDATERS /////////////
+    @Override
+    public int updateAnnotationBody(Number annotationID, String text, String mimeType, Boolean isXml) {
+        Map<String, Object> params = new HashMap<String, Object>();
+        params.put("annotationID", annotationID);
+        params.put("bodyText", text);
+        params.put("bodyMimeType", mimeType);
+        params.put("isXml", isXml);
+
+        StringBuilder sql = new StringBuilder("UPDATE ");
+        sql.append(annotationTableName).append(" SET ").
+                append(last_modified).append("=  default,").
+                append(body_text).append("= :bodyText, ").
+                append(body_mimetype).append("= :bodyMimeType, ").
+                append(is_xml).append("= :isXml").
+                append(" WHERE ").append(annotation_id).append("= :annotationID");
+        int affectedRows = this.loggedUpdate(sql.toString(), params);
+        return affectedRows;
+    }
+
+    // TODO Unit test
+    @Override
+    public int updateAnnotation(Annotation annotation, Number newOwnerID) {
+
+        String[] body = retrieveBodyComponents(annotation.getBody());
+        String externalID = stringURItoExternalID(annotation.getURI());
+        Map<String, Object> params = new HashMap<String, Object>();
+        params.put("owner", newOwnerID);
+        params.put("bodyText", body[0]);
+        params.put("bodyMimeType", body[1]);
+        params.put("headline", annotation.getHeadline());
+        params.put("isXml", annotation.getBody().getXmlBody() != null);
+        params.put("externalID", externalID);
+
+
+        StringBuilder sql = new StringBuilder("UPDATE ");
+        sql.append(annotationTableName).append(" SET ").
+                append(owner_id).append("=  :owner ,").
+                append(body_text).append("=  :bodyText ,").
+                append(body_mimetype).append("= :bodyMimeType ,").
+                append(headline).append("=  :headline ,").
+                append(last_modified).append("=  default,").
+                append(is_xml).append("= :isXml").
+                append(" WHERE ").append(external_id).append("= :externalID");
+        int affectedRows = this.loggedUpdate(sql.toString(), params);
+        return affectedRows;
+    }
+
+    @Override
+    public int updateAnnotationPrincipalPermission(Number annotationID, Number userID, Permission permission) {
+
+        if (annotationID == null) {
+            loggerAnnotationDao.debug("annotationID: " + nullArgument);
+            return 0;
+        }
+
+        if (userID == null) {
+            loggerAnnotationDao.debug("userID: " + nullArgument);
+            return 0;
+        }
+
+        if (permission == null) {
+            loggerAnnotationDao.debug("permission: " + nullArgument);
+            return 0;
+        }
+
+        Map<String, Object> params = new HashMap<String, Object>();
+
+        params.put("annotationID", annotationID);
+        params.put("principalID", userID);
+
+        if (permission != null) {
+            params.put("permission", permission.value());
+            StringBuilder sql = new StringBuilder("UPDATE ");
+            sql.append(permissionsTableName).append(" SET ").
+                    append(this.permission).append("= :permission").
+                    append(" WHERE ").append(annotation_id).append("= :annotationID").
+                    append(" AND ").append(principal_id).append("= :principalID");
+            return this.loggedUpdate(sql.toString(), params);
+        } else {
+            StringBuilder sql = new StringBuilder("DELETE FROM ");
+            sql.append(permissionsTableName).append(" WHERE ").append(annotation_id).append("= :annotationID").
+                    append(" AND ").append(principal_id).append("= :principalID");
+            return (this.loggedUpdate(sql.toString(), params));
+        }
+
+    }
+
+    //////////// ADDERS ////////////////////////
+    @Override
+    public Number addAnnotation(Annotation annotation, Number ownerID) {
+
+        String[] body = retrieveBodyComponents(annotation.getBody());
+
+        if (annotation == null) {
+            loggerAnnotationDao.debug("annotation: " + nullArgument);
+            return null;
+        }
+        
+        if (ownerID == null) {
+            loggerAnnotationDao.debug("ownerID: " + nullArgument);
+            return null;
+        }
+
+        // generate a new annotation ID 
+        UUID externalID = UUID.randomUUID();
+        Map<String, Object> params = new HashMap<String, Object>();
+        params.put("externalId", externalID.toString());
+        params.put("owner", ownerID);
+        params.put("headline", annotation.getHeadline());
+        params.put("bodyText", body[0]);
+        params.put("bodyMimeType", body[1]);
+        params.put("isXml", annotation.getBody().getXmlBody() != null);
+
+        StringBuilder sql = new StringBuilder("INSERT INTO ");
+        sql.append(annotationTableName).append("(").append(external_id).append(",").append(owner_id);
+        sql.append(",").append(headline).append(",").append(body_text).append(",").append(body_mimetype).append(",").append(is_xml).
+                append(" ) VALUES (:externalId, :owner, :headline, :bodyText, :bodyMimeType, :isXml)");
+        int affectedRows = this.loggedUpdate(sql.toString(), params);
+        return ((affectedRows > 0) ? getInternalID(externalID) : null);
+    }
+
+    //////////////////////////////////////////////////////////////////////////////////
+    @Override
+    public int addAnnotationTarget(Number annotationID, Number targetID) {
+
+        if (annotationID == null) {
+            loggerAnnotationDao.debug("annotationID: " + nullArgument);
+            return 0;
+        }
+
+        if (targetID == null) {
+            loggerAnnotationDao.debug("targetID: " + nullArgument);
+            return 0;
+        }
+
+        Map<String, Object> paramsAnnotationsTargets = new HashMap<String, Object>();
+        paramsAnnotationsTargets.put("annotationId", annotationID);
+        paramsAnnotationsTargets.put("targetId", targetID);
+        StringBuilder sqlAnnotationsTargets = new StringBuilder("INSERT INTO ");
+        sqlAnnotationsTargets.append(annotationsTargetsTableName).append("(").append(annotation_id).append(",").append(target_id).append(" ) VALUES (:annotationId, :targetId)");
+        return this.loggedUpdate(sqlAnnotationsTargets.toString(), paramsAnnotationsTargets);
+    }
+
+    /////////////////////////////////////////////////////////////////////////////////////////
+    @Override
+    public int addAnnotationPrincipalPermission(Number annotationID, Number userID, Permission permission) {
+
+        if (annotationID == null) {
+            loggerAnnotationDao.debug("annotationID: " + nullArgument);
+            return 0;
+        }
+
+        if (userID == null) {
+            loggerAnnotationDao.debug("userID: " + nullArgument);
+            return 0;
+        }
+
+        if (permission == null) {
+            loggerAnnotationDao.debug("permission: " + nullArgument);
+            return 0;
+        }
+
+
+        Map<String, Object> paramsPermissions = new HashMap<String, Object>();
+        paramsPermissions.put("annotationId", annotationID);
+        paramsPermissions.put("principalId", userID);
+        paramsPermissions.put("status", permission.value());
+        StringBuilder sqlUpdatePermissionTable = new StringBuilder("INSERT INTO ");
+        sqlUpdatePermissionTable.append(permissionsTableName).append(" (").append(annotation_id).append(",").append(principal_id).append(",").append(this.permission).append(") VALUES (:annotationId, :principalId, :status)");
+        final int affectedPermissions = this.loggedUpdate(sqlUpdatePermissionTable.toString(), paramsPermissions);
+        return affectedPermissions;
+    }
+
+    //////////////////////////////////////////////////////////////////////////////////
+    /////////////////// DELETERS //////////////////////////
+    @Override
+    public int deleteAnnotation(Number annotationID) {
+        if (annotationID != null) {
+            StringBuilder sqlAnnotation = new StringBuilder("DELETE FROM ");
+            sqlAnnotation.append(annotationTableName).append(" where ").append(annotation_id).append(" = ?");
+            return (this.loggedUpdate(sqlAnnotation.toString(), annotationID));
+        } else {
+            loggerAnnotationDao.debug("annotationID: " + nullArgument);
+            return 0;
+        }
+    }
+
+    @Override
+    public int deleteAllAnnotationTarget(Number annotationID) {
+        if (annotationID != null) {
+            StringBuilder sqlTargetTargets = new StringBuilder("DELETE FROM ");
+            sqlTargetTargets.append(annotationsTargetsTableName).append(" WHERE ").append(annotation_id).append(" = ?");
+            return this.loggedUpdate(sqlTargetTargets.toString(), annotationID); // # removed "annotations_target_Targets" rows
+        } else {
+            loggerAnnotationDao.debug("annotationID: " + nullArgument);
+            return 0;
+        }
+    }
+
+    //////////////////////////////////////////////////////
+    @Override
+    public int deleteAnnotationPrincipalPermissions(Number annotationID) {
+        if (annotationID != null) {
+            StringBuilder sqlPermissions = new StringBuilder("DELETE FROM ");
+            sqlPermissions.append(permissionsTableName).append(" WHERE ").append(annotation_id).append(" = ?");
+            return this.loggedUpdate(sqlPermissions.toString(), annotationID); // removed "permission" rows 
+        } else {
+            loggerAnnotationDao.debug("annotationID: " + nullArgument);
+            return 0;
+        }
+
+    }
+    
+    ////////////////////////////////////////
+    @Override
+    public int deleteAnnotationFromAllNotebooks(Number annotationID){
+        if (annotationID != null) {
+            StringBuilder sql = new StringBuilder("DELETE FROM ");
+            sql.append(notebooksAnnotationsTableName).append(" WHERE ").append(annotation_id).append(" = ?");
+            return this.loggedUpdate(sql.toString(), annotationID); // removed "notebook-annotation" rows 
+        } else {
+            loggerAnnotationDao.debug("annotationID: " + nullArgument);
+            return 0;
+        }
+    }
+
+    //////////////////////////////////////////////////////
+    @Override
+    public int deleteAnnotationPrincipalPermission(Number annotationID, Number userID) {
+        if (annotationID != null) {
+            if (userID != null) {
+                Map<String, Number> params = new HashMap();
+                params.put("annotationId", annotationID);
+                params.put("userId", userID);
+                StringBuilder sqlPermissions = new StringBuilder("DELETE FROM ");
+                sqlPermissions.append(permissionsTableName).append(" WHERE ").append(annotation_id).append(" = :annotationId AND ").
+                        append(principal_id).append(" = :userId");
+                return this.loggedUpdate(sqlPermissions.toString(), params);
+            } else {
+                loggerAnnotationDao.debug("userID: " + nullArgument);
+                return 0;
+            }
+        } else {
+            loggerAnnotationDao.debug("annotationID: " + nullArgument);
+            return 0;
+        }
+
+    }
+
+    /////////////// helpers //////////////////
+    @Override
+    public String[] retrieveBodyComponents(AnnotationBody annotationBody) {
+        boolean body_is_xml = annotationBody.getXmlBody() != null;
+        String[] result = new String[2];
+        if (body_is_xml) {
+            result[0] = Helpers.elementToString(annotationBody.getXmlBody().getAny());
+            result[1] = annotationBody.getXmlBody().getMimeType();
+        } else {
+            TextBody textBody = annotationBody.getTextBody();
+            if (textBody != null) {
+                result[0] = textBody.getBody();
+                result[1] = textBody.getMimeType();
+            } else {
+                loggerAnnotationDao.error("Ill-formed body: both options, xml-body and text-body, are set to null. ");
+                return null;
+            }
+        }
+        return result;
+    }
+}
Index: /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/java/eu/dasish/annotation/backend/dao/impl/JdbcCachedRepresentationDao.java
===================================================================
--- /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/java/eu/dasish/annotation/backend/dao/impl/JdbcCachedRepresentationDao.java	(revision 4603)
+++ /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/java/eu/dasish/annotation/backend/dao/impl/JdbcCachedRepresentationDao.java	(revision 4603)
@@ -0,0 +1,163 @@
+/*
+ * Copyright (C) 2013 DASISH
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
+ */
+package eu.dasish.annotation.backend.dao.impl;
+
+import eu.dasish.annotation.backend.dao.CachedRepresentationDao;
+import eu.dasish.annotation.schema.CachedRepresentationInfo;
+import java.io.IOException;
+import java.io.InputStream;
+import java.lang.String;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import javax.sql.DataSource;
+import org.springframework.jdbc.core.RowMapper;
+import org.apache.commons.io.IOUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ *
+ * @author olhsha
+ */
+public class JdbcCachedRepresentationDao extends JdbcResourceDao implements CachedRepresentationDao {
+
+    private  final Logger loggerCachedDao = LoggerFactory.getLogger(JdbcCachedRepresentationDao.class);
+    
+    
+    
+    public JdbcCachedRepresentationDao(DataSource dataSource) {
+        setDataSource(dataSource);
+        internalIdName = cached_representation_id;
+        resourceTableName = cachedRepresentationTableName;
+    }
+
+    @Override
+    public void setServiceURI(String serviceURI) {
+        _serviceURI = serviceURI;
+    }
+
+    /////////////////////////// GETTERS  ////////////////////////////////////////
+    @Override
+    public CachedRepresentationInfo getCachedRepresentationInfo(Number internalID) {
+        if (internalID == null) {
+            loggerCachedDao.debug("internalID: " + nullArgument);
+            return null;
+        }
+        StringBuilder sql = new StringBuilder("SELECT ");
+        sql.append(cachedRepresentationStar).append(" FROM ").append(cachedRepresentationTableName).append(" WHERE ").append(cached_representation_id).append("= ? LIMIT 1");
+        List<CachedRepresentationInfo> result = this.loggedQuery(sql.toString(), cachedRepresentationRowMapper, internalID);
+
+        if (result.isEmpty()) {
+            return null;
+        }
+        return result.get(0);
+    }
+    private final RowMapper<CachedRepresentationInfo> cachedRepresentationRowMapper = new RowMapper<CachedRepresentationInfo>() {
+        @Override
+        public CachedRepresentationInfo mapRow(ResultSet rs, int rowNumber) throws SQLException {
+            CachedRepresentationInfo result = new CachedRepresentationInfo();
+            result.setMimeType(rs.getString(mime_type));
+            result.setURI(externalIDtoURI(rs.getString(external_id)));
+            result.setTool(rs.getString(tool));
+            result.setType(rs.getString(type_));
+            return result;
+        }
+    };
+
+    /////////////////////////// GETTERS  ////////////////////////////////////////
+    @Override
+    public InputStream getCachedRepresentationBlob(Number internalID) {
+        
+        if (internalID == null) {
+            loggerCachedDao.debug("internalID: " + nullArgument);
+            return null;
+        }
+        StringBuilder sql = new StringBuilder("SELECT ");
+        sql.append(file_).append(" FROM ").append(cachedRepresentationTableName).append(" WHERE ").append(cached_representation_id).append("= ? LIMIT 1");
+        List<InputStream> result = this.loggedQuery(sql.toString(), cachedRepresentationBlobRowMapper, internalID);
+
+        if (result.isEmpty()) {
+            return null;
+        }
+
+        return result.get(0);
+    }
+    private final RowMapper<InputStream> cachedRepresentationBlobRowMapper = new RowMapper<InputStream>() {
+        @Override
+        public InputStream mapRow(ResultSet rs, int rowNumber) throws SQLException {
+            return rs.getBinaryStream(file_);
+        }
+    };
+
+   
+    
+       /////////////////////////////////////////
+    @Override
+    public List<Number> getCachedRepresentationsForTarget(Number targetID) {
+
+        if (targetID == null) {
+            loggerCachedDao.debug("targetID: " + nullArgument);
+            return null;
+        }
+
+        String sql = "SELECT " + cached_representation_id + " FROM " + targetsCachedRepresentationsTableName + " WHERE " + target_id + " = ?";
+        return this.loggedQuery(sql, internalIDRowMapper, targetID);
+    }
+
+
+    //////////////////////// ADDERS ///////////////////////////////
+    @Override
+    public Number addCachedRepresentation(CachedRepresentationInfo cachedInfo, InputStream streamCached) {
+        try {
+            UUID externalIdentifier = UUID.randomUUID();
+            Map<String, Object> params = new HashMap<String, Object>();
+            params.put("externalId", externalIdentifier.toString());
+            params.put("mime_type", cachedInfo.getMimeType());
+            params.put("tool", cachedInfo.getTool());
+            params.put("type", cachedInfo.getType());
+            params.put("blob", IOUtils.toByteArray(streamCached));
+            StringBuilder sql = new StringBuilder("INSERT INTO ");
+            sql.append(cachedRepresentationTableName).append("(").append(external_id).append(",").append(mime_type).append(",").append(tool).append(",").append(type_).append(",").append(file_).append(" ) VALUES (:externalId, :mime_type,  :tool, :type, :blob)");
+            final int affectedRows = this.loggedUpdate(sql.toString(), params);
+            return (affectedRows > 0 ? getInternalID(externalIdentifier) : null);
+
+        } catch (IOException ioe) {
+            loggerCachedDao.debug(ioe + "while adding cached representation");
+            return null;
+        }
+
+    }
+
+    /////////////////////// DELETERS  //////////////////////////////////////////////
+    @Override
+    public int deleteCachedRepresentation(Number internalID) {
+        
+        if (internalID == null) {
+            loggerCachedDao.debug("internalID: " + nullArgument);
+            return 0;
+        }
+               
+        StringBuilder sql = new StringBuilder("DELETE FROM ");
+        sql.append(cachedRepresentationTableName).append(" WHERE ").append(cached_representation_id).append(" = ?");
+        return this.loggedUpdate(sql.toString(), internalID);
+    }
+}
Index: /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/java/eu/dasish/annotation/backend/dao/impl/JdbcNotebookDao.java
===================================================================
--- /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/java/eu/dasish/annotation/backend/dao/impl/JdbcNotebookDao.java	(revision 4603)
+++ /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/java/eu/dasish/annotation/backend/dao/impl/JdbcNotebookDao.java	(revision 4603)
@@ -0,0 +1,481 @@
+/*
+ * Copyright (C) 2013 DASISH
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
+ */
+package eu.dasish.annotation.backend.dao.impl;
+
+import eu.dasish.annotation.backend.dao.NotebookDao;
+import eu.dasish.annotation.schema.Notebook;
+import eu.dasish.annotation.schema.NotebookInfo;
+import eu.dasish.annotation.schema.Permission;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import javax.sql.DataSource;
+import org.springframework.jdbc.core.RowMapper;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Created on : Jun 14, 2013, 3:27:04 PM
+ *
+ * @author Peter Withers <peter.withers@mpi.nl>
+ */
+// TODO: not updated fully yet. 
+public class JdbcNotebookDao extends JdbcResourceDao implements NotebookDao {
+
+    private final Logger loggerNotebookDao = LoggerFactory.getLogger(JdbcNotebookDao.class);
+
+    public JdbcNotebookDao(DataSource dataSource) {
+        setDataSource(dataSource);
+        internalIdName = notebook_id;
+        resourceTableName = notebookTableName;
+    }
+
+    /// GETTERS /////////
+    ////////////////////////////////////////////////
+    ////////////////////////////////////////////////
+    @Override
+    public Number getOwner(Number notebookID) {
+        if (notebookID == null) {
+            loggerNotebookDao.debug("notebookID: " + nullArgument);
+            return null;
+        }
+        StringBuilder sql = new StringBuilder("SELECT ");
+        sql.append(owner_id).append(" FROM ").append(notebookTableName).append(" WHERE ").
+                append(notebook_id).append(" = ?");
+        List<Number> result = this.loggedQuery(sql.toString(), ownerIDRowMapper, notebookID);
+        if (result.isEmpty()) {
+            return null;
+        } else {
+            return result.get(0);
+        }
+    }
+    
+    //////////////////////////////////////////////////
+    @Override
+    public List<Map<Number, String>>  getPermissions(Number notebookID) {
+        if (notebookID == null) {
+            loggerNotebookDao.debug(nullArgument);
+            return null;
+        }
+        StringBuilder sql = new StringBuilder("SELECT ");
+        sql.append(principal_id).append(",").append(permission).append(" FROM ").append(notebookPermissionsTableName).append(" WHERE ").append(notebook_id).append("  = ?");
+        return this.loggedQuery(sql.toString(), principalsPermissionsRowMapper, notebookID);
+    }
+    
+  /////////////
+
+    @Override
+    public List<Number> getNotebookIDs(Number principalID, Permission permission) {
+
+        if (principalID == null) {
+            loggerNotebookDao.debug("princiaplID: " + nullArgument);
+            return null;
+        }
+
+        if (permission == null) {
+            loggerNotebookDao.debug("permission: " + nullArgument);
+            return null;
+        }
+
+        Map<String, Object> params = new HashMap<String, Object>();
+        params.put("principalID", principalID);
+        params.put("accessMode", permission.value());
+        StringBuilder sql = new StringBuilder("SELECT ");
+        sql.append(notebook_id).append(" FROM ").append(notebookPermissionsTableName).append(" WHERE ").
+                append(principal_id).append(" = :principalID AND ").append(this.permission).append(" = :accessMode");
+        return this.loggedQuery(sql.toString(), internalIDRowMapper, params);
+    }
+
+    ////////////////////////////////////////////////
+    @Override
+    public List<Number> getNotebookIDsOwnedBy(Number principalID) {
+
+        if (principalID == null) {
+            loggerNotebookDao.debug("principalID: " + nullArgument);
+            return null;
+        }
+
+        StringBuilder sql = new StringBuilder("SELECT ");
+        sql.append(notebook_id).append(" FROM ").append(notebookTableName).append(" WHERE ").
+                append(owner_id).append(" = ?");
+        return this.loggedQuery(sql.toString(), internalIDRowMapper, principalID);
+    }
+
+   
+
+    @Override
+    public NotebookInfo getNotebookInfoWithoutOwner(Number notebookID) {
+        if (notebookID == null) {
+            loggerNotebookDao.debug("notebookID: " + nullArgument);
+            return null;
+        }
+
+        StringBuilder sql = new StringBuilder("SELECT ");
+        sql.append(external_id).append(" , ").append(title).
+                append(" FROM ").append(notebookTableName).append(" WHERE ").
+                append(notebook_id).append(" = :notebookID");
+        List<NotebookInfo> result = this.loggedQuery(sql.toString(), notebookInfoRowMapper, notebookID);
+        return (!result.isEmpty() ? result.get(0) : null);
+    }
+    private final RowMapper<NotebookInfo> notebookInfoRowMapper = new RowMapper<NotebookInfo>() {
+        @Override
+        public NotebookInfo mapRow(ResultSet rs, int rowNumber) throws SQLException {
+            NotebookInfo notebookInfo = new NotebookInfo();
+            notebookInfo.setRef(externalIDtoURI(rs.getString(external_id)));
+            notebookInfo.setTitle(rs.getString(title));
+            return notebookInfo;
+        }
+    };
+
+    @Override
+    public Notebook getNotebookWithoutAnnotationsAndPermissionsAndOwner(Number notebookID) {
+        if (notebookID == null) {
+            loggerNotebookDao.debug("notebookID: " + nullArgument);
+            return null;
+        }
+        StringBuilder sql = new StringBuilder("SELECT ");
+        sql.append(external_id).append(" , ").append(title).append(" , ").append(last_modified).
+                append(" FROM ").append(notebookTableName).append(" WHERE ").
+                append(notebook_id).append(" = :notebookID");
+        List<Notebook> result = this.loggedQuery(sql.toString(), notebookRowMapper, notebookID);
+        return (!result.isEmpty() ? result.get(0) : null);
+    }
+    private final RowMapper<Notebook> notebookRowMapper = new RowMapper<Notebook>() {
+        @Override
+        public Notebook mapRow(ResultSet rs, int rowNumber) throws SQLException {
+            Notebook notebook = new Notebook();
+            notebook.setTitle(rs.getString(title));
+            notebook.setLastModified(timeStampToXMLGregorianCalendar(rs.getString(last_modified)));
+            notebook.setURI(externalIDtoURI(rs.getString(external_id)));
+            return notebook;
+        }
+    };
+
+   
+    /**
+     *
+     * UPDATERS
+     *
+     *
+     */
+    /**
+     *
+     * @param notebookID
+     * @return true if updated, false otherwise. Logs the reason if the notebook
+     * is not updated.
+     */
+    @Override
+    public boolean updateNotebookMetadata(Number notebookID, String title, Number ownerID) {
+
+        if (notebookID == null) {
+            loggerNotebookDao.debug("notebookID: " + nullArgument);
+            return false;
+        }
+
+        if (title == null) {
+            loggerNotebookDao.debug("title: " + nullArgument);
+            return false;
+        }
+
+        if (ownerID == null) {
+            loggerNotebookDao.debug("ownerID: " + nullArgument);
+            return false;
+        }
+
+        Map<String, Object> params = new HashMap<String, Object>();
+        params.put("notebookID", notebookID);
+        params.put("title", title);
+        params.put("owner", ownerID);
+
+        StringBuilder sql = new StringBuilder("UPDATE ");
+        sql.append(notebookTableName).append(" SET ").
+                append(last_modified).append("=  default,").
+                append(this.title).append("= :title, ").
+                append(owner_id).append("= :owner").
+                append(" WHERE ").append(notebook_id).append("= :notebookID");
+        int affectedRows = this.loggedUpdate(sql.toString(), params);
+        if (affectedRows <= 0) {
+            logger.info("For some reason no rows in the table notebooks were updated. ");
+            return false;
+        } else {
+            if (affectedRows > 1) {
+                logger.info("For some reason more than 1 row in the table notebooks were updated. that's strange.");
+                return true;
+            } else {
+                return true;
+            }
+        }
+    }
+    
+    @Override
+    public boolean setOwner(Number notebookID, Number ownerID) {
+
+        if (notebookID == null) {
+            loggerNotebookDao.debug("notebookID: " + nullArgument);
+            return false;
+        }
+
+        if (ownerID == null) {
+            loggerNotebookDao.debug("ownerID: " + nullArgument);
+            return false;
+        }
+
+        Map<String, Object> params = new HashMap<String, Object>();
+        params.put("notebookID", notebookID);
+        params.put("ownerID", ownerID);
+
+        StringBuilder sql = new StringBuilder("UPDATE ");
+        sql.append(notebookTableName).append(" SET ").
+                append(last_modified).append("=  default,").
+                append(owner_id).append("= :ownerID").
+                append(" WHERE ").append(notebook_id).append("= :notebookID");
+        int affectedRows = this.loggedUpdate(sql.toString(), params);
+        if (affectedRows <= 0) {
+            logger.info("For some reason no rows in the table notebooks were updated. ");
+            return false;
+        } else {
+            if (affectedRows > 1) {
+                logger.info("For some reason more than 1 row in the table notebooks were updated. that's strange.");
+                return true;
+            } else {
+                return true;
+            }
+        }
+    }
+
+    @Override
+    public boolean updateUserPermissionForNotebook(Number notebookID, Number principalID, Permission permission) {
+
+        if (notebookID == null) {
+            loggerNotebookDao.debug("notebookID: " + nullArgument);
+            return false;
+        }
+
+        if (principalID == null) {
+            loggerNotebookDao.debug("principalID: " + nullArgument);
+            return false;
+        }
+
+        if (permission == null) {
+            loggerNotebookDao.debug("permission: " + nullArgument);
+            return false;
+        }
+
+
+        Map<String, Object> params = new HashMap<String, Object>();
+        params.put("notebookID", notebookID);
+        params.put("principalID", principalID);
+        params.put("permission", permission.value());
+
+        StringBuilder sql = new StringBuilder("UPDATE ");
+        sql.append(notebookPermissionsTableName).append(" SET ").
+                append(this.permission).append("= :permission ").
+                append(" WHERE ").append(notebook_id).append("= :notebookID AND ").
+                append(principal_id).append("= :principalID");
+        int affectedRows = this.loggedUpdate(sql.toString(), params);
+        if (affectedRows <= 0) {
+            logger.info("For some reason no rows in the table notebooks-permissions were updated. ");
+            return false;
+        } else {
+            if (affectedRows > 1) {
+                logger.info("For some reason more than 1 row in the table notebooks-permissions were updated. that's strange.");
+                return true;
+            } else {
+                return true;
+            }
+        }
+    }
+
+    /**
+     *
+     * ADDERS
+     *
+     *
+     */
+    @Override
+    public Number createNotebookWithoutPermissionsAndAnnotations(Notebook notebook, Number ownerID) {
+        if (notebook == null) {
+            loggerNotebookDao.debug("notebook: " + nullArgument);
+            return null;
+        }
+
+        if (ownerID == null) {
+            loggerNotebookDao.debug("ownerID: " + nullArgument);
+            return null;
+        }
+
+        UUID externalID = UUID.randomUUID();
+        Map<String, Object> params = new HashMap<String, Object>();
+        params.put("externalId", externalID.toString());
+        params.put("owner", ownerID);
+        params.put("title", notebook.getTitle());
+
+        StringBuilder sql = new StringBuilder("INSERT INTO ");
+        sql.append(notebookTableName).append("(").append(external_id).append(",").append(owner_id);
+        sql.append(",").append(title).
+                append(" ) VALUES (:externalId, :owner, :title)");
+        int affectedRows = this.loggedUpdate(sql.toString(), params);
+        return ((affectedRows > 0) ? getInternalID(externalID) : null);
+    }
+
+    @Override
+    public boolean addAnnotationToNotebook(Number notebookID, Number annotationID) {
+
+        if (notebookID == null) {
+            loggerNotebookDao.debug("notebookID: " + nullArgument);
+            return false;
+        }
+
+        if (annotationID == null) {
+            loggerNotebookDao.debug("annotationID: " + nullArgument);
+            return false;
+        }
+
+        Map<String, Object> params = new HashMap<String, Object>();
+        params.put("notebookID", notebookID);
+        params.put("annotationID", annotationID);
+
+        StringBuilder sql = new StringBuilder("INSERT INTO ");
+        sql.append(notebooksAnnotationsTableName).append("(").append(notebook_id).append(",").append(annotation_id);
+        sql.append(" ) VALUES (:notebookID, :annotationID)");
+        int affectedRows = this.loggedUpdate(sql.toString(), params);
+        return (affectedRows > 0);
+    }
+
+    @Override
+    public boolean addPermissionToNotebook(Number notebookID, Number principalID, Permission permission) {
+        if (notebookID == null) {
+            loggerNotebookDao.debug("notebookID: " + nullArgument);
+            return false;
+        }
+
+        if (principalID == null) {
+            loggerNotebookDao.debug("principalID: " + nullArgument);
+            return false;
+        }
+
+        if (permission == null) {
+            loggerNotebookDao.debug("premission: " + nullArgument);
+            return false;
+        }
+
+        Map<String, Object> params = new HashMap<String, Object>();
+        params.put("notebookID", notebookID);
+        params.put("principalID", principalID);
+        params.put("permission", permission.value());
+
+        StringBuilder sql = new StringBuilder("INSERT INTO ");
+        sql.append(notebookPermissionsTableName).append("(").append(notebook_id).append(",").append(principal_id);
+        sql.append(",").append(this.permission).
+                append(" ) VALUES (:notebookID, :principalID, :permission)");
+        int affectedRows = this.loggedUpdate(sql.toString(), params);
+        return (affectedRows > 0);
+    }
+
+    /**
+     *
+     * DELETERS
+     *
+     *
+     */
+    @Override
+    public boolean deleteAnnotationFromNotebook(Number notebookID, Number annotationID) {
+        if (notebookID != null) {
+            if (annotationID != null) {
+                Map<String, Number> params = new HashMap();
+                params.put("notebookID", notebookID);
+                params.put("annotationID", annotationID);
+                StringBuilder sql = new StringBuilder("DELETE FROM ");
+                sql.append(notebooksAnnotationsTableName).append(" WHERE ").append(notebook_id).append(" = :notebookID AND ").
+                        append(annotation_id).append(" = :annotationID");
+                int affectedRows = this.loggedUpdate(sql.toString(), params);
+                return (affectedRows > 0);
+            } else {
+                loggerNotebookDao.debug("annotationID: " + nullArgument);
+                return false;
+            }
+        } else {
+            loggerNotebookDao.debug("notebookID: " + nullArgument);
+            return false;
+        }
+    }
+
+    @Override
+    public boolean deleteNotebookPrincipalPermission(Number notebookID, Number principalID) {
+        if (notebookID != null) {
+            if (principalID != null) {
+                Map<String, Number> params = new HashMap();
+                params.put("notebookID", notebookID);
+                params.put("principalID", principalID);
+                StringBuilder sqlPermissions = new StringBuilder("DELETE FROM ");
+                sqlPermissions.append(notebookPermissionsTableName).append(" WHERE ").append(notebook_id).append(" = :notebookID AND ").
+                        append(principal_id).append(" = :principalID");
+                int affectedRows = this.loggedUpdate(sqlPermissions.toString(), params);
+                return (affectedRows > 0);
+            } else {
+                loggerNotebookDao.debug("principalID: " + nullArgument);
+                return false;
+            }
+        } else {
+            loggerNotebookDao.debug("notebookID: " + nullArgument);
+            return false;
+        }
+    }
+
+    @Override
+    public boolean deleteAllAnnotationsFromNotebook(Number notebookID) {
+        if (notebookID != null) {
+            StringBuilder sql = new StringBuilder("DELETE FROM ");
+            sql.append(notebooksAnnotationsTableName).append(" WHERE ").append(notebook_id).append(" = ? ");
+            int affectedRows = this.loggedUpdate(sql.toString(), notebookID);
+            return (affectedRows > 0);
+        } else {
+            loggerNotebookDao.debug("notebookID: " + nullArgument);
+            return false;
+        }
+    }
+
+    @Override
+    public boolean deleteAllPermissionsForNotebook(Number notebookID) {
+        if (notebookID != null) {
+            StringBuilder sqlPermissions = new StringBuilder("DELETE FROM ");
+            sqlPermissions.append(notebookPermissionsTableName).append(" WHERE ").append(notebook_id).append(" = ? ");
+            int affectedRows = this.loggedUpdate(sqlPermissions.toString(), notebookID);
+            return (affectedRows > 0);
+        } else {
+            loggerNotebookDao.debug("notebookID: " + nullArgument);
+            return false;
+        }
+    }
+
+    @Override
+    public boolean deleteNotebook(Number notebookID) {
+        if (notebookID != null) {
+            StringBuilder sql = new StringBuilder("DELETE FROM ");
+            sql.append(notebookTableName).append(" WHERE ").append(notebook_id).append(" = ? ");
+            int affectedRows = this.loggedUpdate(sql.toString(), notebookID);
+            return (affectedRows > 0);
+        } else {
+            loggerNotebookDao.debug("notebookID: " + nullArgument);
+            return false;
+        }
+    }
+}
Index: /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/java/eu/dasish/annotation/backend/dao/impl/JdbcResourceDao.java
===================================================================
--- /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/java/eu/dasish/annotation/backend/dao/impl/JdbcResourceDao.java	(revision 4603)
+++ /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/java/eu/dasish/annotation/backend/dao/impl/JdbcResourceDao.java	(revision 4603)
@@ -0,0 +1,317 @@
+/*
+ * Copyright (C) 2013 DASISH
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
+ */
+package eu.dasish.annotation.backend.dao.impl;
+
+import eu.dasish.annotation.backend.dao.ResourceDao;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.UUID;
+import javax.xml.datatype.DatatypeConfigurationException;
+import javax.xml.datatype.DatatypeFactory;
+import javax.xml.datatype.XMLGregorianCalendar;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.jdbc.core.RowMapper;
+import org.springframework.jdbc.core.simple.SimpleJdbcDaoSupport;
+
+/**
+ *
+ * @author olhsha
+ */
+public class JdbcResourceDao extends SimpleJdbcDaoSupport implements ResourceDao {
+
+    // base string constants: table Names
+    final static protected String notebookTableName = "notebook";
+    final static protected String annotationTableName = "annotation";
+    final static protected String targetTableName = "target";
+    final static protected String cachedRepresentationTableName = "cached_representation";
+    final static protected String versionTableName = "version";
+    final static protected String principalTableName = "principal";
+    // joint tablenames
+    final static protected String notebooksAnnotationsTableName = "notebooks_annotations";
+    final static protected String permissionsTableName = "annotations_principals_permissions";
+    final static protected String notebookPermissionsTableName = "notebooks_principals_permissions";
+    final static protected String annotationsTargetsTableName = "annotations_targets";
+    final static protected String targetsCachedRepresentationsTableName = "targets_cached_representations";
+    // base string constants: field Names
+    final static protected String account = "account";
+    final static protected String admin = "admin";
+    final static protected String developer = "developer";
+    final static protected String user = "user";
+    final static protected String annotation_id = "annotation_id";
+    final static protected String notebook_id = "notebook_id";
+    final static protected String target_id = "target_id";
+    final static protected String external_id = "external_id";
+    final static protected String owner_id = "owner_id";
+    final static protected String headline = "headline";
+    final static protected String body_text = "body_text";
+    final static protected String body_mimetype = "body_mimetype";
+    final static protected String title = "title";
+    final static protected String principal_id = "principal_id";
+    final static protected String notebookOwner_id = "owner_id";
+    final static protected String last_modified = "last_modified";
+    final static protected String version = "version";
+    final static protected String permission = "permission_";
+    final static protected String link_uri = "link_uri";
+    final static protected String cached_representation_id = "cached_representation_id";
+    final static protected String sibling_Target_class = "sibling_Target_class";
+    final static protected String mime_type = "mime_type";
+    final static protected String tool = "tool";
+    final static protected String type_ = "type_";
+    final static protected String file_ = "file_";
+    final static protected String principal_name = "principal_name";
+    final static protected String e_mail = "e_mail";
+    final static protected String remote_id = "remote_id";
+    final static protected String is_xml = "is_xml";
+    final static protected String fragment_descriptor = "fragment_descriptor";
+    final static protected String fragment_descriptor_in_cached = "fragment_descriptor_in_cached";
+    final static protected String annotationStar = annotationTableName + ".*";
+    final static protected String cachedRepresentationStar = cachedRepresentationTableName + ".*";
+    final static protected String targetStar = targetTableName + ".*";
+    final static protected String principalStar = principalTableName + ".*";
+    ////////////////////////////////
+    ///////////////////////////////////////////////////
+    protected String internalIdName = null;
+    protected String resourceTableName = null;
+    protected String _serviceURI;
+    private final Logger _logger = LoggerFactory.getLogger(JdbcResourceDao.class);
+    protected String nullArgument = "Null argument is given to the method.";
+
+    protected <T> List<T> loggedQuery(String sql, RowMapper<T> rm, Map<String, ?> args) {
+        List<T> result = getSimpleJdbcTemplate().query(sql, rm, args);
+        String sqlStatement = replaceInString(sql, args);
+        logger.debug("\n SQL query: " + sqlStatement+"\n");
+        return result;
+    }
+
+    protected <T, E> List<T> loggedQuery(String sql, RowMapper<T> rm, E arg) {
+        List<T> result = getSimpleJdbcTemplate().query(sql, rm, arg);        
+        logger.debug("\n SQL query: " + this.replaceQuestionmarkInString(sql, arg)+"\n");
+        return result;
+    }
+
+    protected <T> List<T> loggedQuery(String sql, RowMapper<T> rm) {
+        logger.debug("\n SQL query: " + sql+"\n");
+        return getSimpleJdbcTemplate().query(sql, rm);
+    }
+
+    protected int loggedUpdate(String sql, Map<String, ?> args) {
+        int result = getSimpleJdbcTemplate().update(sql, args);
+        String sqlStatement = replaceInString(sql, args);
+        logger.debug("\n SQL query: " + sqlStatement+"\n");
+        return result;
+    }
+
+    protected <T> int loggedUpdate(String sql, T arg) {
+        int result = getSimpleJdbcTemplate().update(sql, arg);
+        logger.debug("\n SQL query: " + this.replaceQuestionmarkInString(sql, arg)+"\n");
+        return result;
+    }
+
+    private String replaceInString(String string, Map<String, ?> map) {
+        String result = (new StringBuilder(string)).toString();
+        Set<String> keys = map.keySet();
+        for (String key : keys) {
+            if (map.get(key) != null) {
+                result = result.replaceAll(":" + key, map.get(key).toString());
+            } else {
+                result = result.replaceAll(":" + key, "null!!");
+            }
+        }
+        return result;
+    }
+
+    private <T> String replaceQuestionmarkInString(String string, T arg) {
+        String result = (new StringBuilder(string)).toString();
+        CharSequence questionMark = "?";
+        CharSequence replacement = arg.toString();
+        result = result.replace(questionMark, replacement);
+        return result;
+    }
+
+
+    /////////////////// Class field SETTERS /////////////
+    @Override
+    public void setServiceURI(String serviceURI) {
+        _serviceURI = serviceURI;
+    }
+
+    //////////////////////////////////////////////////////////////////////////////////
+    @Override
+    public Number getInternalID(UUID externalId) {
+        StringBuilder sql = new StringBuilder("SELECT ");
+        sql.append(internalIdName).append(" FROM ").append(resourceTableName).append(" WHERE ").append(external_id).append("= ? LIMIT 1");
+        List<Number> sqlResult = this.loggedQuery(sql.toString(), internalIDRowMapper, externalId.toString());
+
+
+        if (sqlResult.isEmpty()) {
+            _logger.debug("The object with external ID " + externalId.toString() + " is not found in the database.");
+            return null;
+        } else {
+            return sqlResult.get(0);
+        }
+
+    }
+
+    /////////////////////////////////////////////
+    @Override
+    public UUID getExternalID(Number internalId) {
+        if (internalId == null) {
+            _logger.debug("internalId: " + nullArgument);
+            return null;
+        }
+        StringBuilder sql = new StringBuilder("SELECT ");
+        sql.append(external_id).append(" FROM ").append(resourceTableName).append(" WHERE ").append(internalIdName).append("= ? LIMIT 1");
+        List<UUID> sqlResult = this.loggedQuery(sql.toString(), externalIDRowMapper, internalId);
+        return (sqlResult.isEmpty() ? null : sqlResult.get(0));
+    }
+
+    //////////////////////////////////////////////
+    @Override
+    public Number getInternalIDFromURI(String uri) {
+        String externalID = stringURItoExternalID(uri);
+        try {
+            UUID externalUUID = UUID.fromString(externalID);
+            return getInternalID(externalUUID);
+        } catch (IllegalArgumentException e) {
+            _logger.debug(externalID + " is not a valid <uuid>.  Therefore, I expect that it is a temporary idendifier of a new resource that is not yet in the database and return null.");
+            return null;
+        }
+    }
+
+    //////////////////////////////////////////////
+    @Override
+    public String getURIFromInternalID(Number internalID) {
+        if (internalID == null) {
+            _logger.debug("internalID: " + nullArgument);
+            return null;
+        }
+        return externalIDtoURI(getExternalID(internalID).toString());
+    }
+
+    // override for notebooks and annotations
+    @Override
+    public List<Map<Number, String>> getPermissions(Number resourceID) {
+        return (new ArrayList<Map<Number, String>>());
+    }
+
+    /////////////////////////////////////////////////////
+    protected XMLGregorianCalendar retrieveTimeStamp(Number internalID) {
+        StringBuilder sqlTime = new StringBuilder("SELECT ");
+        sqlTime.append(last_modified).append(" FROM ").append(resourceTableName).append(" WHERE ").append(internalIdName).append("= ? LIMIT 1");
+        List<XMLGregorianCalendar> timeStamp = this.loggedQuery(sqlTime.toString(), timeStampRowMapper, internalID);
+
+        if (timeStamp.isEmpty()) {
+            return null;
+        }
+        return timeStamp.get(0);
+    }
+    protected final RowMapper<XMLGregorianCalendar> timeStampRowMapper = new RowMapper<XMLGregorianCalendar>() {
+        @Override
+        public XMLGregorianCalendar mapRow(ResultSet rs, int rowNumber) throws SQLException {
+            return timeStampToXMLGregorianCalendar(rs.getString(last_modified));
+        }
+    };
+////////////////// ROW MAPPERS ///////////////////
+    protected final RowMapper<Number> internalIDRowMapper = new RowMapper<Number>() {
+        @Override
+        public Number mapRow(ResultSet rs, int rowNumber) throws SQLException {
+            int result = rs.getInt(internalIdName);
+            Number resultNumber = result;
+            return resultNumber;
+        }
+    };
+    protected final RowMapper<UUID> externalIDRowMapper = new RowMapper<UUID>() {
+        @Override
+        public UUID mapRow(ResultSet rs, int rowNumber) throws SQLException {
+            return (UUID.fromString(rs.getString(external_id)));
+        }
+    };
+
+    protected final RowMapper<Number> ownerIDRowMapper = new RowMapper<Number>() {
+        @Override
+        public Number mapRow(ResultSet rs, int rowNumber) throws SQLException {
+            return rs.getInt(owner_id);
+        }
+    };
+    protected final RowMapper<Map<Number, String>> principalsPermissionsRowMapper = new RowMapper<Map<Number, String>>() {
+        @Override
+        public Map<Number, String> mapRow(ResultSet rs, int rowNumber) throws SQLException {
+            Map<Number, String> result = new HashMap<Number, String>();
+            result.put(rs.getInt(principal_id), rs.getString(permission));
+            return result;
+        }
+    };
+
+    ////// END ROW MAPPERS /////
+    @Override
+    public String externalIDtoURI(String externalID) {
+        if (_serviceURI != null) {
+            return _serviceURI + externalID;
+        } else {
+            return externalID;
+        }
+    }
+
+    @Override
+    public String stringURItoExternalID(String stringURI) {
+        if (stringURI.length() > _serviceURI.length()) {
+            return stringURI.substring(_serviceURI.length());
+        } else {
+            logger.debug(stringURI + " does not have the form <service url>/<isentifier>, therefore I return the input value.");
+            return stringURI;
+        }
+    }
+
+    ////////////////////////////
+    protected <T> String makeListOfValues(List<T> vals) {
+
+        if (vals == null) {
+            return null;
+        }
+
+        if (vals.isEmpty()) {
+            return null;
+        }
+
+        String result = "(";
+        int length = vals.size();
+        for (int i = 0; i < length - 1; i++) {
+            result = result + vals.get(i).toString() + ", ";
+        }
+        result = result + vals.get(length - 1).toString() + ")";
+        return result;
+    }
+
+    /////////////////////////
+    protected XMLGregorianCalendar timeStampToXMLGregorianCalendar(String ts) {
+        String tsAdjusted = ts.replace(' ', 'T') + "Z";
+        try {
+            return DatatypeFactory.newInstance().newXMLGregorianCalendar(tsAdjusted);
+        } catch (DatatypeConfigurationException dtce) {
+            _logger.error(" ", dtce);
+            return null;
+        }
+
+    }
+}
Index: /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/java/eu/dasish/annotation/backend/dao/impl/JdbcTargetDao.java
===================================================================
--- /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/java/eu/dasish/annotation/backend/dao/impl/JdbcTargetDao.java	(revision 4603)
+++ /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/java/eu/dasish/annotation/backend/dao/impl/JdbcTargetDao.java	(revision 4603)
@@ -0,0 +1,338 @@
+/*
+ * Copyright (C) 2013 DASISH
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
+ */
+package eu.dasish.annotation.backend.dao.impl;
+
+import eu.dasish.annotation.backend.dao.TargetDao;
+import eu.dasish.annotation.schema.Target;
+import eu.dasish.annotation.schema.TargetInfo;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import javax.sql.DataSource;
+import javax.xml.datatype.DatatypeConfigurationException;
+import javax.xml.datatype.XMLGregorianCalendar;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.jdbc.core.RowMapper;
+
+/**
+ *
+ * @author olhsha
+ */
+public class JdbcTargetDao extends JdbcResourceDao implements TargetDao {
+
+    private final Logger loggerTargetDao = LoggerFactory.getLogger(JdbcTargetDao.class);
+
+    public JdbcTargetDao(DataSource dataTarget) {
+        setDataSource(dataTarget);
+        internalIdName = target_id;
+        resourceTableName = targetTableName;
+    }
+
+    @Override
+    public void setServiceURI(String serviceURI) {
+        _serviceURI = serviceURI;
+    }
+
+    //////////////////////// GETTERS ///////////////////////////////////
+    @Override
+    public Target getTarget(Number internalID) {
+
+        if (internalID == null) {
+            loggerTargetDao.debug("internalID: " + nullArgument);
+            return null;
+        }
+
+        StringBuilder sql = new StringBuilder("SELECT ");
+        sql.append(targetStar).append(" FROM ").append(targetTableName).append(" WHERE ").append(target_id).append("= ? LIMIT 1");
+        List<Target> result = this.loggedQuery(sql.toString(), targetRowMapper, internalID);
+        return (!result.isEmpty() ? result.get(0) : null);
+    }
+    private final RowMapper<Target> targetRowMapper = new RowMapper<Target>() {
+        @Override
+        public Target mapRow(ResultSet rs, int rowNumber) throws SQLException {
+            XMLGregorianCalendar xmlDate = timeStampToXMLGregorianCalendar(rs.getString(last_modified));
+            Target result =
+                    constructTarget(rs.getString(external_id), rs.getString(link_uri), rs.getString(version), xmlDate, rs.getString(fragment_descriptor));
+            return result;
+        }
+    };
+
+    @Override
+    public String getLink(Number internalID) {
+
+        if (internalID == null) {
+            loggerTargetDao.debug("internalID: " + nullArgument);
+            return null;
+        }
+
+        StringBuilder sql = new StringBuilder("SELECT ");
+        sql.append(targetStar).append(" FROM ").append(targetTableName).append(" WHERE ").append(target_id).append("= ? LIMIT 1");
+        List<String> result = this.loggedQuery(sql.toString(), linkRowMapper, internalID);
+        return (!result.isEmpty() ? result.get(0) : null);
+    }
+    private final RowMapper<String> linkRowMapper = new RowMapper<String>() {
+        @Override
+        public String mapRow(ResultSet rs, int rowNumber) throws SQLException {
+            return rs.getString(link_uri);
+        }
+    };
+
+ 
+    @Override
+    public Map<Number, String> getCachedRepresentationFragmentPairs(Number targetID) {
+
+        if (targetID == null) {
+            loggerTargetDao.debug("targetID: " + nullArgument);
+            return null;
+        }
+
+        Map<Number, String> result = new HashMap<Number, String>();
+        String sql = "SELECT " + cached_representation_id + "," + fragment_descriptor_in_cached + " FROM " + targetsCachedRepresentationsTableName + " WHERE " + target_id + " = ?";
+        List<Map<Number, String>> respond = this.loggedQuery(sql, cachedFragmentRowMapper, targetID);
+        for (Map<Number, String> pair : respond) {
+            result.putAll(pair);
+        }
+        return result;
+    }
+    private final RowMapper<Map<Number, String>> cachedFragmentRowMapper = new RowMapper<Map<Number, String>>() {
+        @Override
+        public Map<Number, String> mapRow(ResultSet rs, int rowNumber) throws SQLException {
+            Map<Number, String> result = new HashMap<Number, String>();
+            result.put(rs.getInt(cached_representation_id), rs.getString(fragment_descriptor_in_cached));
+            return result;
+        }
+    };
+
+    ///////////////////////////////////////////////////////////////////
+    @Override
+    public List<TargetInfo> getTargetInfos(List<Number> targets) {
+        if (targets == null) {
+            loggerTargetDao.debug("targets: " + nullArgument);
+            return null;
+        }
+        if (targets.isEmpty()) {
+            return new ArrayList<TargetInfo>();
+        }
+
+        String targetIDs = makeListOfValues(targets);
+
+        StringBuilder sql = new StringBuilder("SELECT ");
+        sql.append(external_id).append(",").append(link_uri).append(",").append(version).append(",").append(fragment_descriptor).
+                append(" FROM ").append(targetTableName).append(" WHERE ").append(target_id).append(" IN ").append(targetIDs);
+        return this.loggedQuery(sql.toString(), targetInfoRowMapper);
+    }
+    private final RowMapper<TargetInfo> targetInfoRowMapper = new RowMapper<TargetInfo>() {
+        @Override
+        public TargetInfo mapRow(ResultSet rs, int rowNumber) throws SQLException {
+            return constructTargetInfo(rs.getString(external_id), rs.getString(link_uri), rs.getString(version), rs.getString(fragment_descriptor));
+        }
+    };
+
+    /////////////////////////////////////////////////////
+    @Override
+    public List<Number> getTargetsReferringTo(String word) {
+        if (word == null) {
+            loggerTargetDao.debug("word: " + nullArgument);
+            return null;
+        }
+        String searchTerm = "%" + word + "%";
+        StringBuilder sql = new StringBuilder("SELECT ");
+        sql.append(target_id).append(" FROM ").append(targetTableName).append(" WHERE ").append(link_uri).append(" LIKE ? ");
+        return this.loggedQuery(sql.toString(), internalIDRowMapper, searchTerm);
+    }
+
+    /////////////////////////////////////////////////////
+    @Override
+    public List<Number> getTargetsForLink(String link) {
+        if (link == null) {
+            loggerTargetDao.debug("link: " + nullArgument);
+            return null;
+        }
+
+        StringBuilder sql = new StringBuilder("SELECT ");
+        sql.append(target_id).append(" FROM ").append(targetTableName).append(" WHERE ").append(link_uri).append(" =  ? ");
+        return this.loggedQuery(sql.toString(), internalIDRowMapper, link);
+    }
+
+  
+    
+    
+     //////////////////////////////////////
+    @Override
+    public boolean cachedIsInUse(Number cachedID) {
+        
+        if (cachedID == null) {
+            logger.debug("Cached's Id is null");
+            return false;
+        }
+        
+        StringBuilder sql = new StringBuilder("SELECT ");
+        sql.append(target_id).append(" FROM ").append(targetsCachedRepresentationsTableName).append(" WHERE ").append(cached_representation_id).append("= ? LIMIT 1");
+        List<Number> result = this.loggedQuery(sql.toString(), internalIDRowMapper, cachedID);
+        if (result != null) {
+            return (!result.isEmpty());
+        } else {
+            return false;
+        }
+    }
+    
+    
+    @Override
+    public List<Number> retrieveTargetIDs(Number annotationID) {
+        if (annotationID != null) {
+            StringBuilder sql = new StringBuilder("SELECT DISTINCT ");
+            sql.append(target_id).append(" FROM ").append(annotationsTargetsTableName).append(" WHERE ").append(annotation_id).append("= ?");
+            return this.loggedQuery(sql.toString(), internalIDRowMapper, annotationID);
+        } else {
+            loggerTargetDao.debug(nullArgument);
+            return null;
+        }
+    }
+
+    ///////////////////////// ADDERS /////////////////////////////////
+    @Override
+    public Number addTarget(Target target) {
+        
+        if (target == null) {
+            loggerTargetDao.debug("target: " + nullArgument);
+            return null;
+        }
+
+        
+        UUID externalID = UUID.randomUUID();
+        String[] linkParts = splitLink(target.getLink());
+        Map<String, Object> params = new HashMap<String, Object>();
+        params.put("externalId", externalID.toString());
+        params.put("linkUri", linkParts[0]);
+        params.put("version", target.getVersion());
+        params.put("fragmentDescriptor", linkParts[1]);
+        StringBuilder sql = new StringBuilder("INSERT INTO ");
+        sql.append(targetTableName).append("(").append(external_id).append(",").append(link_uri).append(",").append(version).append(",").append(fragment_descriptor).append(" ) VALUES (:externalId, :linkUri,  :version, :fragmentDescriptor)");
+        final int affectedRows = this.loggedUpdate(sql.toString(), params);
+        return (affectedRows > 0 ? getInternalID(UUID.fromString(externalID.toString())) : null);
+    }
+
+    ///////////////////////////////////////////////////////////////////
+    @Override
+    public int addTargetCachedRepresentation(Number targetID, Number cachedID, String fragmentDescriptor) {
+         if (targetID == null) {
+            loggerTargetDao.debug("targetID: " + nullArgument);
+            return 0;
+        }
+
+         if (cachedID == null) {
+            loggerTargetDao.debug("cachedID: " + nullArgument);
+            return 0;
+        }
+         
+        Map<String, Object> paramsJoint = new HashMap<String, Object>();
+        paramsJoint.put("targetId", targetID);
+        paramsJoint.put("cachedId", cachedID);
+        paramsJoint.put("fragmentDescriptor", fragmentDescriptor);
+        StringBuilder sqlJoint = new StringBuilder("INSERT INTO ").append(targetsCachedRepresentationsTableName).append("(").append(target_id).append(",").append(cached_representation_id).append(",").append(fragment_descriptor_in_cached).append(" ) VALUES (:targetId, :cachedId, :fragmentDescriptor)");
+        return this.loggedUpdate(sqlJoint.toString(), paramsJoint);
+    }
+
+  ///////////////////////////////////
+   @Override
+    public int deleteTarget(Number internalID) {
+        if (internalID == null) {
+            logger.debug("internalID of the target is null.");
+            return 0;
+        }
+        
+      
+        StringBuilder sqlTargetsVersions = new StringBuilder("DELETE FROM ");
+        sqlTargetsVersions.append(targetTableName).append(" WHERE ").append(target_id).append(" = ? ");
+        return this.loggedUpdate(sqlTargetsVersions.toString(), internalID);
+
+    }
+
+
+    ///////////////////////////////////////////////////////////////////
+    @Override
+    public int deleteTargetCachedRepresentation(Number targetID, Number cachedID) {
+        
+         if (targetID == null) {
+            loggerTargetDao.debug("targetID: " + nullArgument);
+            return 0;
+        }
+
+         if (cachedID == null) {
+            loggerTargetDao.debug("cachedID: " + nullArgument);
+            return 0;
+        }
+        
+       
+        Map<String, Object> paramsJoint = new HashMap<String, Object>();
+        paramsJoint.put("targetId", targetID);
+        paramsJoint.put("cachedId", cachedID);
+        StringBuilder sqlTargetsVersions = new StringBuilder("DELETE FROM ");
+        sqlTargetsVersions.append(targetsCachedRepresentationsTableName).append(" WHERE ").append(target_id).append(" = :targetId").
+                append(" AND ").append(cached_representation_id).append(" = :cachedId");
+        return this.loggedUpdate(sqlTargetsVersions.toString(), paramsJoint);
+
+    }
+
+    /////////// HELPERS  ////////////////
+    private TargetInfo constructTargetInfo(String externalID, String link, String version, String fragment) {
+        TargetInfo targetInfo = new TargetInfo();
+        targetInfo.setRef(externalIDtoURI(externalID));
+        targetInfo.setLink(((new StringBuilder(link)).append("#").append(fragment)).toString());
+        targetInfo.setVersion(version);
+        return targetInfo;
+    }
+
+    private Target constructTarget(String externalID, String link, String version, XMLGregorianCalendar xmlTimeStamp, String fragment) {
+        Target target = new Target();
+        target.setURI(externalIDtoURI(externalID));
+        target.setLastModified(xmlTimeStamp);
+        if (fragment != null) {
+            target.setLink(((new StringBuilder(link)).append("#").append(fragment)).toString());
+        } else {
+            target.setLink(link);
+        }
+        target.setVersion(version);
+        return target;
+    }
+
+    private String[] splitLink(String link) {
+        if (link != null) {
+            String[] result = new String[2];
+            String[] parts = link.split("#");
+            result[0] = parts[0];
+            if (parts.length > 1) {
+                StringBuilder buffer = new StringBuilder();
+                for (int i = 1; i < parts.length; i++) {
+                    if (parts[i] != null) {
+                        buffer.append(parts[i]);
+                    }
+                }
+                result[1] = buffer.toString();
+            }
+            return result;
+        } else {
+            return null;
+        }
+    }
+}
Index: /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/java/eu/dasish/annotation/backend/dao/impl/JdbcUserDao.java
===================================================================
--- /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/java/eu/dasish/annotation/backend/dao/impl/JdbcUserDao.java	(revision 4603)
+++ /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/java/eu/dasish/annotation/backend/dao/impl/JdbcUserDao.java	(revision 4603)
@@ -0,0 +1,335 @@
+/*
+ * Copyright (C) 2013 DASISH
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
+ */
+package eu.dasish.annotation.backend.dao.impl;
+
+import eu.dasish.annotation.backend.dao.UserDao;
+import eu.dasish.annotation.schema.Permission;
+import eu.dasish.annotation.schema.User;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import javax.sql.DataSource;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.jdbc.core.RowMapper;
+
+/**
+ *
+ * @author olhsha
+ */
+public class JdbcUserDao extends JdbcResourceDao implements UserDao {
+
+    private final Logger loggerUserDao = LoggerFactory.getLogger(JdbcUserDao.class);
+
+    public JdbcUserDao(DataSource dataSource) {
+        setDataSource(dataSource);
+        internalIdName = principal_id;
+        resourceTableName = principalTableName;
+    }
+
+    @Override
+    public void setServiceURI(String serviceURI) {
+        _serviceURI = serviceURI;
+    }
+
+    /////////// GETTERS //////////////////////
+    @Override
+    public User getUser(Number internalID) {
+
+        if (internalID == null) {
+            loggerUserDao.debug("internalID: " + nullArgument);
+            return null;
+        }
+
+        StringBuilder sql = new StringBuilder("SELECT ");
+        sql.append(principalStar).append(" FROM ").append(principalTableName).append(" WHERE ").append(principal_id).append("= ? LIMIT 1");
+        List<User> result = this.loggedQuery(sql.toString(), userRowMapper, internalID);
+        return (!result.isEmpty() ? result.get(0) : null);
+    }
+    private final RowMapper<User> userRowMapper = new RowMapper<User>() {
+        @Override
+        public User mapRow(ResultSet rs, int rowNumber) throws SQLException {
+            User result = new User();
+            result.setURI(externalIDtoURI(rs.getString(external_id)));
+            result.setDisplayName(rs.getString(principal_name));
+            result.setEMail(rs.getString(e_mail));
+            return result;
+        }
+    };
+
+    @Override
+    public User getUserByInfo(String eMail) {
+        StringBuilder sql = new StringBuilder("SELECT ");
+        sql.append(principalStar).append(" FROM ").append(principalTableName).append(" WHERE ").append("LOWER(").append(e_mail).append(")").append("= ? LIMIT 1");
+        List<User> result = this.loggedQuery(sql.toString(), userRowMapper, eMail.toLowerCase());
+        return (!result.isEmpty() ? result.get(0) : null);
+    }
+
+    @Override
+    public boolean userIsInUse(Number userID) {
+
+        if (userID == null) {
+            loggerUserDao.debug("userID: " + nullArgument);
+            return false;
+        }
+
+        StringBuilder sqlPermissions = new StringBuilder("SELECT ");
+        sqlPermissions.append(principal_id).append(" FROM ").append(permissionsTableName).append(" WHERE ").append(principal_id).append("= ? LIMIT 1");
+        List<Number> resultTargets = this.loggedQuery(sqlPermissions.toString(), internalIDRowMapper, userID);
+        if (resultTargets.size() > 0) {
+            return true;
+        };
+
+        StringBuilder sqlNotebooks = new StringBuilder("SELECT ");
+        sqlNotebooks.append(owner_id).append(" FROM ").append(notebookTableName).append(" WHERE ").append(owner_id).append("= ? LIMIT 1");
+        List<Number> resultNotebooks = this.loggedQuery(sqlNotebooks.toString(), ownerIDRowMapper, userID);
+        if (resultNotebooks.size() > 0) {
+            return true;
+        };
+        return false;
+    }
+
+    @Override
+    public boolean userExists(User user) {
+        if (user == null) {
+            loggerUserDao.debug("user: " + nullArgument);
+            return false;
+        }
+
+        String emailCriterion = user.getEMail().toLowerCase();
+        StringBuilder sqlTargets = new StringBuilder("SELECT ");
+        sqlTargets.append(principal_id).append(" FROM ").append(principalTableName).append(" WHERE ").append("LOWER(").append(e_mail).append(")= ? LIMIT 1");
+        List<Number> resultTargets = this.loggedQuery(sqlTargets.toString(), internalIDRowMapper, emailCriterion);
+        if (resultTargets.size() > 0) {
+            return true;
+        } else {
+            return false;
+        }
+    }
+
+    @Override
+    public String getRemoteID(Number internalID) {
+
+        if (internalID == null) {
+            loggerUserDao.debug("internalID: " + nullArgument);
+            return null;
+        }
+
+        StringBuilder requestDB = new StringBuilder("SELECT ");
+        requestDB.append(remote_id).append(" FROM ").append(principalTableName).append(" WHERE ").append(principal_id).append("= ? LIMIT 1");
+        List<String> result = this.loggedQuery(requestDB.toString(), remoteIDRowMapper, internalID);
+        return (result.size() > 0) ? result.get(0) : null;
+    }
+    private final RowMapper<String> remoteIDRowMapper = new RowMapper<String>() {
+        @Override
+        public String mapRow(ResultSet rs, int rowNumber) throws SQLException {
+            return rs.getString(remote_id);
+        }
+    };
+
+    @Override
+    public Number getUserInternalIDFromRemoteID(String remoteID) {
+
+        if (remoteID == null) {
+            loggerUserDao.debug("remoteID: " + nullArgument);
+            return null;
+        }
+
+        StringBuilder requestDB = new StringBuilder("SELECT ");
+        requestDB.append(principal_id).append(" FROM ").append(principalTableName).append(" WHERE ").append(remote_id).append("= ? LIMIT 1");
+        List<Number> result = this.loggedQuery(requestDB.toString(), internalIDRowMapper, remoteID);
+        return (result.size() > 0) ? result.get(0) : null;
+    }
+
+    @Override
+    public String getTypeOfUserAccount(Number internalID) {
+
+        if (internalID == null) {
+            loggerUserDao.debug("internalID: " + nullArgument);
+            return null;
+        }
+
+        StringBuilder requestDB = new StringBuilder("SELECT ");
+        requestDB.append(account).append(" FROM ").append(principalTableName).append(" WHERE ").append(principal_id).append("= ? LIMIT 1");
+        List<String> result = this.loggedQuery(requestDB.toString(), adminRightsRowMapper, internalID);
+        return (result.size() > 0) ? result.get(0) : null;
+    }
+    private final RowMapper<String> adminRightsRowMapper = new RowMapper<String>() {
+        @Override
+        public String mapRow(ResultSet rs, int rowNumber) throws SQLException {
+            return rs.getString(account);
+        }
+    };
+
+    @Override
+    public Number getDBAdminID() {
+        StringBuilder requestDB = new StringBuilder("SELECT ");
+        requestDB.append(principal_id).append(" FROM ").append(principalTableName).append(" WHERE account = 'admin'  LIMIT 1");
+        List<Number> result = this.loggedQuery(requestDB.toString(), internalIDRowMapper);
+        return (result.size() > 0) ? result.get(0) : null;
+    }
+
+    @Override
+    public List<Number> getPrincipalIDsWithPermissionForNotebook(Number notebookID, Permission permission) {
+        if (notebookID == null) {
+            loggerUserDao.debug("notebookID: " + nullArgument);
+            return null;
+        }
+
+        if (permission == null) {
+            loggerUserDao.debug("permission: " + nullArgument);
+            return null;
+        }
+        Map<String, Object> params = new HashMap<String, Object>();
+        params.put("notebookID", notebookID);
+        params.put("accessMode", permission.value());
+
+        StringBuilder sql = new StringBuilder("SELECT ");
+        sql.append(principal_id).append(" FROM ").append(notebookPermissionsTableName).append(" WHERE ").
+                append(notebook_id).append(" = :notebookID AND ").append(this.permission).append(" = :accessMode");
+
+        return this.loggedQuery(sql.toString(), internalIDRowMapper, params);
+
+    }
+
+    ///////////////////// ADDERS ////////////////////////////
+    @Override
+    public Number addUser(User user, String remoteID) {
+
+        if (remoteID == null) {
+            loggerUserDao.debug("remoteID: " + nullArgument);
+            return null;
+        }
+
+        if (user == null) {
+            loggerUserDao.debug("user: " + nullArgument);
+            return null;
+        }
+
+        UUID externalIdentifier = UUID.randomUUID();
+        String newExternalIdentifier = externalIdentifier.toString();
+        Map<String, Object> params = new HashMap<String, Object>();
+        params.put("externalId", newExternalIdentifier);
+        params.put("principalName", user.getDisplayName());
+        params.put("email", user.getEMail());
+        params.put("remoteID", remoteID);
+        params.put("accountType", this.user);
+        StringBuilder sql = new StringBuilder("INSERT INTO ");
+        sql.append(principalTableName).append("(").append(external_id).append(",").
+                append(principal_name).append(",").append(e_mail).append(",").
+                append(remote_id).append(",").append(account).append(" ) VALUES (:externalId, :principalName, :email, :remoteID, :accountType)");
+        final int affectedRows = this.loggedUpdate(sql.toString(), params);
+        return (affectedRows > 0 ? getInternalID(externalIdentifier) : null);
+    }
+
+    ////////// UPDATERS ///////////////////////
+    @Override
+    public boolean updateAccount(UUID externalID, String account) {
+
+        if (externalID == null) {
+            loggerUserDao.debug("eternalId: " + nullArgument);
+            return false;
+        }
+
+        if (account == null) {
+            loggerUserDao.debug("account: " + nullArgument);
+            return false;
+        }
+
+        if (!account.equals(admin) && !account.equals(developer) && !account.equals(user)) {
+            logger.error("the given type of account '" + account + "' does not exist.");
+            return false;
+        }
+        Number principalID = this.getInternalID(externalID);
+        if (principalID != null) {
+            Map<String, Object> params = new HashMap<String, Object>();
+            params.put("externalId", externalID.toString());
+            params.put("accountType", account);
+            StringBuilder sql = new StringBuilder("UPDATE ");
+            sql.append(principalTableName).append(" SET ").
+                    append(this.account).append("= :accountType").
+                    append(" WHERE ").append(external_id).append("= :externalId");
+            int affectedRows = this.loggedUpdate(sql.toString(), params);
+            if (affectedRows > 0) {
+                return true;
+            } else {
+                logger.error("For some reason the database refuses update the account of " + externalID.toString() + " . Consult the servers' respond.");
+                return false;
+            }
+        } else {
+            logger.error("The user with external ID " + externalID.toString() + " is not found in the data base");
+            return false;
+        }
+
+    }
+
+    @Override
+    public Number updateUser(User user) {
+
+        if (user == null) {
+            loggerUserDao.debug("user: " + nullArgument);
+            return null;
+        }
+
+        Number principalID = this.getInternalIDFromURI(user.getURI());
+        StringBuilder sql = new StringBuilder("UPDATE ");
+        sql.append(principalTableName).append(" SET ").
+                append(e_mail).append("= '").append(user.getEMail()).append("',").
+                append(principal_name).append("= '").append(user.getDisplayName()).append("' ").
+                append(" WHERE ").append(principal_id).append("= ?");
+        int affectedRows = this.loggedUpdate(sql.toString(), principalID);
+        return principalID;
+    }
+
+    ////// DELETERS ////////////
+    @Override
+    public int deleteUser(Number internalID) {
+        if (internalID == null) {
+            loggerUserDao.debug("internalID: " + nullArgument);
+            return 0;
+        }
+
+
+        StringBuilder sql = new StringBuilder("DELETE FROM ");
+        sql.append(principalTableName).append(" where ").append(principal_id).append(" = ?");
+        return this.loggedUpdate(sql.toString(), internalID);
+
+    }
+
+    @Override
+    public int deleteUserSafe(Number internalID) {
+
+        if (internalID == null) {
+            loggerUserDao.debug("internalID: " + nullArgument);
+            return 0;
+        }
+
+
+        if (userIsInUse(internalID)) {
+            loggerUserDao.debug("User is in use, and cannot be deleted.");
+            return 0;
+        }
+        StringBuilder sql = new StringBuilder("DELETE FROM ");
+        sql.append(principalTableName).append(" where ").append(principal_id).append(" = ?");
+        return this.loggedUpdate(sql.toString(), internalID);
+
+    }
+}
Index: /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/java/eu/dasish/annotation/backend/rest/AnnotationResource.java
===================================================================
--- /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/java/eu/dasish/annotation/backend/rest/AnnotationResource.java	(revision 4603)
+++ /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/java/eu/dasish/annotation/backend/rest/AnnotationResource.java	(revision 4603)
@@ -0,0 +1,409 @@
+/*
+ * Copyright (C) 2013 DASISH
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
+ */
+package eu.dasish.annotation.backend.rest;
+
+import eu.dasish.annotation.backend.BackendConstants;
+import eu.dasish.annotation.backend.Resource;
+import eu.dasish.annotation.backend.dao.DBIntegrityService;
+import eu.dasish.annotation.schema.Annotation;
+import eu.dasish.annotation.schema.AnnotationBody;
+import eu.dasish.annotation.schema.AnnotationInfoList;
+import eu.dasish.annotation.schema.ObjectFactory;
+import eu.dasish.annotation.schema.Permission;
+import eu.dasish.annotation.schema.UserWithPermissionList;
+import eu.dasish.annotation.schema.ReferenceList;
+import eu.dasish.annotation.schema.ResponseBody;
+import java.io.IOException;
+import java.util.UUID;
+import javax.servlet.ServletContext;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import javax.ws.rs.Consumes;
+import javax.ws.rs.DELETE;
+import javax.ws.rs.GET;
+import javax.ws.rs.POST;
+import javax.ws.rs.PUT;
+import javax.ws.rs.Path;
+import javax.ws.rs.PathParam;
+import javax.ws.rs.Produces;
+import javax.ws.rs.QueryParam;
+import javax.ws.rs.core.Context;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.UriInfo;
+import javax.ws.rs.ext.Providers;
+import javax.xml.bind.JAXBElement;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.transaction.annotation.Transactional;
+
+/**
+ *
+ * @author olhsha
+ */
+@Component
+@Path("/annotations")
+@Transactional(rollbackFor = {Exception.class})
+public class AnnotationResource extends ResourceResource {
+
+    public void setUriInfo(UriInfo uriInfo) {
+        this.uriInfo = uriInfo;
+    }
+
+    public void setHttpServletResponse(HttpServletResponse httpServletResponse) {
+        this.httpServletResponse = httpServletResponse;
+    }
+
+    public void setHttpServletRequest(HttpServletRequest httpServletRequest) {
+        this.httpServletRequest = httpServletRequest;
+    }
+
+    public void setProviders(Providers providers) {
+        this.providers = providers;
+    }
+
+    public AnnotationResource() {
+    }
+
+    @GET
+    @Produces(MediaType.TEXT_XML)
+    @Path("{annotationid: " + BackendConstants.regExpIdentifier + "}")
+    @Transactional(readOnly = true)
+    public JAXBElement<Annotation> getAnnotation(@PathParam("annotationid") String externalIdentifier) throws IOException {
+        Number userID = this.getUserID();
+        if (userID != null) {
+            try {
+                final Number annotationID = dbIntegrityService.getResourceInternalIdentifier(UUID.fromString(externalIdentifier), Resource.ANNOTATION);
+                if (annotationID != null) {
+
+                    if (dbIntegrityService.canRead(userID, annotationID)) {
+                        final Annotation annotation = dbIntegrityService.getAnnotation(annotationID);
+                        return new ObjectFactory().createAnnotation(annotation);
+                    } else {
+                        verboseOutput.FORBIDDEN_ANNOTATION_READING(externalIdentifier, dbIntegrityService.getAnnotationOwner(annotationID).getDisplayName(), dbIntegrityService.getAnnotationOwner(annotationID).getEMail());
+                    }
+
+                } else {
+                    verboseOutput.ANNOTATION_NOT_FOUND(externalIdentifier);
+                }
+            } catch (IllegalArgumentException e) {
+                verboseOutput.ILLEGAL_UUID(externalIdentifier);
+            }
+        }
+
+        return new ObjectFactory().createAnnotation(new Annotation());
+    }
+
+    //TODO: unit test
+    @GET
+    @Produces(MediaType.TEXT_XML)
+    @Path("{annotationid: " + BackendConstants.regExpIdentifier + "}/targets")
+    @Transactional(readOnly = true)
+    public JAXBElement<ReferenceList> getAnnotationTargets(@PathParam("annotationid") String externalIdentifier) throws IOException {
+        Number userID = this.getUserID();
+        if (userID != null) {
+            try {
+                final Number annotationID = dbIntegrityService.getResourceInternalIdentifier(UUID.fromString(externalIdentifier), Resource.ANNOTATION);
+                if (annotationID != null) {
+
+                    if (dbIntegrityService.canRead(userID, annotationID)) {
+                        final ReferenceList TargetList = dbIntegrityService.getAnnotationTargets(annotationID);
+                        return new ObjectFactory().createTargetList(TargetList);
+                    } else {
+                        verboseOutput.FORBIDDEN_ANNOTATION_READING(externalIdentifier, dbIntegrityService.getAnnotationOwner(annotationID).getDisplayName(), dbIntegrityService.getAnnotationOwner(annotationID).getEMail());
+                    }
+
+                } else {
+                    verboseOutput.ANNOTATION_NOT_FOUND(externalIdentifier);
+
+                }
+            } catch (IllegalArgumentException e) {
+                verboseOutput.ILLEGAL_UUID(externalIdentifier);
+            }
+        }
+        return new ObjectFactory().createTargetList(new ReferenceList());
+    }
+// TODO Unit test 
+
+    @GET
+    @Produces(MediaType.TEXT_XML)
+    @Path("")
+    @Transactional(readOnly = true)
+    public JAXBElement<AnnotationInfoList> getFilteredAnnotations(@QueryParam("link") String link,
+            @QueryParam("text") String text,
+            @QueryParam("access") String access,
+            @QueryParam("namespace") String namespace,
+            @QueryParam("owner") String ownerExternalId,
+            @QueryParam("after") String after,
+            @QueryParam("before") String before) throws IOException {
+
+        Number userID = this.getUserID();
+        if (userID != null) {
+            try {
+                UUID ownerExternalUUID = (ownerExternalId != null) ? UUID.fromString(ownerExternalId) : null;
+
+                final AnnotationInfoList annotationInfoList = dbIntegrityService.getFilteredAnnotationInfos(ownerExternalUUID, link, text, userID, access, namespace, after, before);
+                return new ObjectFactory().createAnnotationInfoList(annotationInfoList);
+            } catch (IllegalArgumentException e) {
+                verboseOutput.ILLEGAL_UUID(ownerExternalId);
+            }
+        }
+        return new ObjectFactory().createAnnotationInfoList(new AnnotationInfoList());
+    }
+
+    // TODO Unit test    
+    @GET
+    @Produces(MediaType.TEXT_XML)
+    @Path("{annotationid: " + BackendConstants.regExpIdentifier + "}/permissions")
+    @Transactional(readOnly = true)
+    public JAXBElement<UserWithPermissionList> getAnnotationPermissions(@PathParam("annotationid") String externalIdentifier) throws IOException {
+        Number userID = this.getUserID();
+        if (userID != null) {
+            try {
+                final Number annotationID = dbIntegrityService.getResourceInternalIdentifier(UUID.fromString(externalIdentifier), Resource.ANNOTATION);
+                if (annotationID != null) {
+                    if (dbIntegrityService.canRead(userID, annotationID)) {
+                        final UserWithPermissionList permissionList = dbIntegrityService.getPermissions(annotationID, Resource.ANNOTATION);
+                        return new ObjectFactory().createPermissionList(permissionList);
+                    } else {
+                        verboseOutput.FORBIDDEN_ANNOTATION_READING(externalIdentifier, dbIntegrityService.getAnnotationOwner(annotationID).getDisplayName(), dbIntegrityService.getAnnotationOwner(annotationID).getEMail());
+                    }
+                } else {
+                    verboseOutput.ANNOTATION_NOT_FOUND(externalIdentifier);
+                }
+
+            } catch (IllegalArgumentException e) {
+                verboseOutput.ILLEGAL_UUID(externalIdentifier);
+            }
+        }
+        return new ObjectFactory().createUserWithPermissionList(new UserWithPermissionList());
+    }
+///////////////////////////////////////////////////////
+// TODO: how to return the status code? 
+
+    @DELETE
+    @Path("{annotationid: " + BackendConstants.regExpIdentifier + "}")
+    public String deleteAnnotation(@PathParam("annotationid") String externalIdentifier) throws IOException {
+        Number userID = this.getUserID();
+        if (userID != null) {
+            try {
+                final Number annotationID = dbIntegrityService.getResourceInternalIdentifier(UUID.fromString(externalIdentifier), Resource.ANNOTATION);
+                if (annotationID != null) {
+                    if (userID.equals(dbIntegrityService.getAnnotationOwnerID(annotationID)) || dbIntegrityService.getTypeOfUserAccount(userID).equals(admin)) {
+                        int[] resultDelete = dbIntegrityService.deleteAnnotation(annotationID);
+                        String result = Integer.toString(resultDelete[0]);
+                        return result + " annotation(s) deleted.";
+                    } else {
+                        verboseOutput.FORBIDDEN_ANNOTATION_WRITING(externalIdentifier, dbIntegrityService.getAnnotationOwner(annotationID).getDisplayName(), dbIntegrityService.getAnnotationOwner(annotationID).getEMail());
+                    }
+                } else {
+                    verboseOutput.ANNOTATION_NOT_FOUND(externalIdentifier);
+                }
+
+            } catch (IllegalArgumentException e) {
+                verboseOutput.ILLEGAL_UUID(externalIdentifier);
+            }
+        }
+        return "Due to the failure no annotation is deleted.";
+    }
+
+    // TODO: how to return the status code? 
+///////////////////////////////////////////////////////
+    @POST
+    @Consumes(MediaType.APPLICATION_XML)
+    @Produces(MediaType.APPLICATION_XML)
+    @Path("")
+    public JAXBElement<ResponseBody> createAnnotation(Annotation annotation) throws IOException {
+        Number userID = this.getUserID();
+        if (userID != null) {
+            Number annotationID = dbIntegrityService.addUsersAnnotation(userID, annotation);
+            return new ObjectFactory().createResponseBody(dbIntegrityService.makeAnnotationResponseEnvelope(annotationID));
+
+        }
+        return new ObjectFactory().createResponseBody(new ResponseBody());
+    }
+///////////////////////////////////////////////////////
+// TODO: unit test
+
+    @PUT
+    @Consumes(MediaType.APPLICATION_XML)
+    @Produces(MediaType.APPLICATION_XML)
+    @Path("{annotationid: " + BackendConstants.regExpIdentifier + "}")
+    public JAXBElement<ResponseBody> updateAnnotation(@PathParam("annotationid") String externalIdentifier, Annotation annotation) throws IOException {
+        Number userID = this.getUserID();
+        if (userID != null) {
+            String path = uriInfo.getBaseUri().toString();
+            String annotationURI = annotation.getURI();
+
+            if (!(path + "annotations/" + externalIdentifier).equals(annotationURI)) {
+                verboseOutput.IDENTIFIER_MISMATCH(externalIdentifier);
+                return new ObjectFactory().createResponseBody(new ResponseBody());
+            }
+
+            try {
+                final Number annotationID = dbIntegrityService.getResourceInternalIdentifier(UUID.fromString(externalIdentifier), Resource.ANNOTATION);
+                if (annotationID != null) {
+
+                    if (userID != null) {
+                        if (userID.equals(dbIntegrityService.getAnnotationOwnerID(annotationID)) || dbIntegrityService.getTypeOfUserAccount(userID).equals(admin)) {
+                            int updatedRows = dbIntegrityService.updateAnnotation(annotation);
+                            return new ObjectFactory().createResponseBody(dbIntegrityService.makeAnnotationResponseEnvelope(annotationID));
+                        } else {
+                            verboseOutput.FORBIDDEN_PERMISSION_CHANGING(externalIdentifier, dbIntegrityService.getAnnotationOwner(annotationID).getDisplayName(), dbIntegrityService.getAnnotationOwner(annotationID).getEMail());
+                            loggerServer.debug(" Permission changing is the part of the full update of the annotation.");
+                        }
+                    }
+                } else {
+                    verboseOutput.ANNOTATION_NOT_FOUND(externalIdentifier);
+                }
+            } catch (IllegalArgumentException e) {
+                verboseOutput.ILLEGAL_UUID(externalIdentifier);
+            }
+        }
+        return new ObjectFactory().createResponseBody(new ResponseBody());
+    }
+
+    @PUT
+    @Consumes(MediaType.APPLICATION_XML)
+    @Produces(MediaType.APPLICATION_XML)
+    @Path("{annotationid: " + BackendConstants.regExpIdentifier + "}/body")
+    public JAXBElement<ResponseBody> updateAnnotationBody(@PathParam("annotationid") String externalIdentifier, AnnotationBody annotationBody) throws IOException {
+        Number userID = this.getUserID();
+        if (userID != null) {
+            try {
+                final Number annotationID = dbIntegrityService.getResourceInternalIdentifier(UUID.fromString(externalIdentifier), Resource.ANNOTATION);
+                if (annotationID != null) {
+                    if (dbIntegrityService.canWrite(userID, annotationID)) {
+                        int updatedRows = dbIntegrityService.updateAnnotationBody(annotationID, annotationBody);
+                        return new ObjectFactory().createResponseBody(dbIntegrityService.makeAnnotationResponseEnvelope(annotationID));
+                    } else { 
+                        verboseOutput.FORBIDDEN_ANNOTATION_WRITING(externalIdentifier, dbIntegrityService.getAnnotationOwner(annotationID).getDisplayName(), dbIntegrityService.getAnnotationOwner(annotationID).getEMail());
+                    }
+                } else {
+                    verboseOutput.ANNOTATION_NOT_FOUND(externalIdentifier);
+                }
+
+            } catch (IllegalArgumentException e) {
+                verboseOutput.ILLEGAL_UUID(externalIdentifier);
+            }
+        }
+        return new ObjectFactory().createResponseBody(new ResponseBody());
+    }
+
+    @PUT
+    @Consumes(MediaType.APPLICATION_XML)
+    @Produces(MediaType.APPLICATION_XML)
+    @Path("{annotationid: " + BackendConstants.regExpIdentifier + "}/permissions/{userid: " + BackendConstants.regExpIdentifier + "}")
+    public String updatePermission(@PathParam("annotationid") String annotationExternalId,
+            @PathParam("userid") String userExternalId, Permission permission) throws IOException {
+        Number remoteUserID = this.getUserID();
+        if (remoteUserID != null) {
+            try {
+                final Number userID = dbIntegrityService.getResourceInternalIdentifier(UUID.fromString(userExternalId), Resource.PRINCIPAL);
+                if (userID != null) {
+                    try {
+                        final Number annotationID = dbIntegrityService.getResourceInternalIdentifier(UUID.fromString(annotationExternalId), Resource.ANNOTATION);
+                        if (annotationID != null) {
+                            if (remoteUserID.equals(dbIntegrityService.getAnnotationOwnerID(annotationID)) || dbIntegrityService.getTypeOfUserAccount(remoteUserID).equals(admin)) {
+                                int result = (dbIntegrityService.getPermission(annotationID, userID) != null)
+                                        ? dbIntegrityService.updateAnnotationPrincipalPermission(annotationID, userID, permission)
+                                        : dbIntegrityService.addAnnotationPrincipalPermission(annotationID, userID, permission);
+                                return result + " rows are updated/added";
+
+                            } else {
+                                verboseOutput.FORBIDDEN_PERMISSION_CHANGING(annotationExternalId, dbIntegrityService.getAnnotationOwner(annotationID).getDisplayName(), dbIntegrityService.getAnnotationOwner(annotationID).getEMail());
+                            }
+                        } else {
+                            verboseOutput.ANNOTATION_NOT_FOUND(annotationExternalId);
+                        }
+                    } catch (IllegalArgumentException e) {
+                        verboseOutput.ILLEGAL_UUID(annotationExternalId);
+                    }
+                } else {
+                    verboseOutput.PRINCIPAL_NOT_FOUND(userExternalId);
+                }
+            } catch (IllegalArgumentException e) {
+                verboseOutput.ILLEGAL_UUID(userExternalId);
+            }
+        }
+        return "Due to the failure no permissionis updated.";
+    }
+
+    @PUT
+    @Consumes(MediaType.APPLICATION_XML)
+    @Produces(MediaType.APPLICATION_XML)
+    @Path("{annotationid: " + BackendConstants.regExpIdentifier + "}/permissions/")
+    public JAXBElement<ResponseBody> updatePermissions(@PathParam("annotationid") String annotationExternalId, UserWithPermissionList permissions) throws IOException {
+        Number remoteUserID = this.getUserID();
+        if (remoteUserID != null) {
+            try {
+                final Number annotationID = dbIntegrityService.getResourceInternalIdentifier(UUID.fromString(annotationExternalId), Resource.ANNOTATION);
+                if (annotationID != null) {
+                    if (remoteUserID.equals(dbIntegrityService.getAnnotationOwnerID(annotationID)) || dbIntegrityService.getTypeOfUserAccount(remoteUserID).equals(admin)) {
+                        int updatedRows = dbIntegrityService.updatePermissions(annotationID, permissions);
+                        return new ObjectFactory().createResponseBody(dbIntegrityService.makePermissionResponseEnvelope(annotationID, Resource.ANNOTATION));
+                    } else {
+                        verboseOutput.FORBIDDEN_PERMISSION_CHANGING(annotationExternalId, dbIntegrityService.getAnnotationOwner(annotationID).getDisplayName(), dbIntegrityService.getAnnotationOwner(annotationID).getEMail());
+                    }
+                } else {
+                    verboseOutput.ANNOTATION_NOT_FOUND(annotationExternalId);
+                }
+
+
+            } catch (IllegalArgumentException e) {
+                verboseOutput.ILLEGAL_UUID(annotationExternalId);
+            }
+        }
+        return new ObjectFactory().createResponseBody(new ResponseBody());
+
+    }
+
+    @DELETE
+    @Produces(MediaType.TEXT_PLAIN)
+    @Path("{annotationId: " + BackendConstants.regExpIdentifier + "}/user/{userId}/delete")
+    public String deleteUsersPermission(@PathParam("annotationId") String annotationId, @PathParam("userId") String userId) throws IOException {
+        Number remoteUserID = this.getUserID();
+        int deletedRows = 0;
+        if (remoteUserID != null) {
+            try {
+                final Number annotationID = dbIntegrityService.getResourceInternalIdentifier(UUID.fromString(annotationId), Resource.ANNOTATION);
+
+                if (annotationID != null) {
+                    if (remoteUserID.equals(dbIntegrityService.getAnnotationOwnerID(annotationID)) || dbIntegrityService.getTypeOfUserAccount(remoteUserID).equals(admin)) {
+                        Number userID = dbIntegrityService.getResourceInternalIdentifier(UUID.fromString(userId), Resource.PRINCIPAL);
+                        if (userID != null) {
+                            deletedRows = dbIntegrityService.updateAnnotationPrincipalPermission(annotationID, userID, null);
+                        } else {
+                            verboseOutput.PRINCIPAL_NOT_FOUND(userId);
+                        }
+                    } else {
+                        verboseOutput.FORBIDDEN_PERMISSION_CHANGING(annotationId, dbIntegrityService.getAnnotationOwner(annotationID).getDisplayName(), dbIntegrityService.getAnnotationOwner(annotationID).getEMail());
+
+                    }
+                } else {
+                    verboseOutput.ANNOTATION_NOT_FOUND(annotationId);
+                }
+
+            } catch (IllegalArgumentException e) {
+                verboseOutput.ILLEGAL_UUID(annotationId);
+            }
+        }
+        return (deletedRows + " is deleted.");
+    }
+}
Index: /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/java/eu/dasish/annotation/backend/rest/AutheticationResource.java
===================================================================
--- /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/java/eu/dasish/annotation/backend/rest/AutheticationResource.java	(revision 4603)
+++ /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/java/eu/dasish/annotation/backend/rest/AutheticationResource.java	(revision 4603)
@@ -0,0 +1,89 @@
+/*
+ * Copyright (C) 2013 DASISH
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
+ */
+package eu.dasish.annotation.backend.rest;
+
+import eu.dasish.annotation.schema.ObjectFactory;
+import eu.dasish.annotation.schema.User;
+import java.io.IOException;
+import java.sql.SQLException;
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServletRequestWrapper;
+import javax.ws.rs.GET;
+import javax.ws.rs.Path;
+import javax.ws.rs.Produces;
+import javax.ws.rs.core.MediaType;
+import javax.xml.bind.JAXBElement;
+import javax.xml.parsers.ParserConfigurationException;
+import org.springframework.stereotype.Component;
+import org.springframework.transaction.annotation.Transactional;
+
+/**
+ *
+ * @author olhsha
+ */
+@Component
+@Path("/authentication")
+@Transactional(rollbackFor = {Exception.class, SQLException.class, IOException.class, ParserConfigurationException.class})
+public class AutheticationResource extends ResourceResource {
+
+    @GET
+    @Produces(MediaType.TEXT_XML)
+    @Path("user")
+    @Transactional(readOnly = true)
+    public JAXBElement<User> getCurrentUser() throws IOException {
+        Number userID = this.getUserID();
+        if (userID != null) {
+            return new ObjectFactory().createUser(dbIntegrityService.getUser(userID));
+        }
+        return new ObjectFactory().createUser(new User());
+    }
+
+    /* the only request that redirects to the shibboleth login-page
+     * 
+     */
+    @GET
+    @Produces(MediaType.TEXT_XML)
+    @Path("login")
+    @Transactional(readOnly = true)
+    public JAXBElement<User> loginAndGet() throws IOException {
+        String remoteUser = httpServletRequest.getRemoteUser();
+        verboseOutput = new VerboseOutput(httpServletResponse, loggerServer);
+        if (remoteUser != null) {
+            dbIntegrityService.setRemoteUser(remoteUser);
+            dbIntegrityService.setServiceURI(uriInfo.getBaseUri().toString());
+            final Number remoteUserID = dbIntegrityService.getUserInternalIDFromRemoteID(remoteUser);
+            if (remoteUserID != null) {
+                return new ObjectFactory().createUser(dbIntegrityService.getUser(remoteUserID));
+            }
+        }
+        return new ObjectFactory().createUser(new User());
+    }
+
+    @GET
+    @Produces(MediaType.TEXT_XML)
+    @Path("logout")
+    @Transactional(readOnly = true)
+    public void logout() throws IOException, ServletException {
+        Number remoteUserID = this.getUserID();
+        if (remoteUserID != null) {
+            dbIntegrityService.setRemoteUser(null);
+            dbIntegrityService.setServiceURI(null);
+            verboseOutput.LOGOUT();
+        }
+    }
+}
Index: /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/java/eu/dasish/annotation/backend/rest/CachedRepresentationResource.java
===================================================================
--- /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/java/eu/dasish/annotation/backend/rest/CachedRepresentationResource.java	(revision 4603)
+++ /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/java/eu/dasish/annotation/backend/rest/CachedRepresentationResource.java	(revision 4603)
@@ -0,0 +1,108 @@
+/*
+ * Copyright (C) 2013 DASISH
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
+ */
+package eu.dasish.annotation.backend.rest;
+
+import eu.dasish.annotation.backend.BackendConstants;
+import eu.dasish.annotation.backend.Resource;
+import eu.dasish.annotation.backend.dao.DBIntegrityService;
+import eu.dasish.annotation.schema.CachedRepresentationInfo;
+import eu.dasish.annotation.schema.ObjectFactory;
+import java.awt.image.BufferedImage;
+import java.io.IOException;
+import java.io.InputStream;
+import java.sql.SQLException;
+import java.util.UUID;
+import javax.imageio.ImageIO;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import javax.ws.rs.GET;
+import javax.ws.rs.Path;
+import javax.ws.rs.PathParam;
+import javax.ws.rs.Produces;
+import javax.ws.rs.core.Context;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.UriInfo;
+import javax.xml.bind.JAXBElement;
+import javax.xml.parsers.ParserConfigurationException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+import org.springframework.transaction.annotation.Transactional;
+
+/**
+ *
+ * @author olhsha
+ */
+@Component
+@Path("/cached")
+@Transactional(rollbackFor = {Exception.class, SQLException.class, IOException.class, ParserConfigurationException.class})
+public class CachedRepresentationResource extends ResourceResource {
+
+    public void setHttpRequest(HttpServletRequest request) {
+        this.httpServletRequest = request;
+    }
+
+    // TODOD both unit tests
+    //changed path, /Target/cached part is removed
+    @GET
+    @Produces(MediaType.TEXT_XML)
+    @Path("{cachedid: " + BackendConstants.regExpIdentifier + "}/metadata")
+    @Transactional(readOnly = true)
+    public JAXBElement<CachedRepresentationInfo> getCachedRepresentationInfo(@PathParam("cachedid") String externalId) throws SQLException, IOException {
+        Number remoteUserID = this.getUserID();
+        if (remoteUserID != null) {
+            try {
+                final Number cachedID = dbIntegrityService.getResourceInternalIdentifier(UUID.fromString(externalId), Resource.CACHED_REPRESENTATION);
+                if (cachedID != null) {
+                    final CachedRepresentationInfo cachedInfo = dbIntegrityService.getCachedRepresentationInfo(cachedID);
+                    return new ObjectFactory().createCashedRepresentationInfo(cachedInfo);
+                } else {
+                    verboseOutput.CACHED_REPRESENTATION_NOT_FOUND(externalId);
+                }
+            } catch (IllegalArgumentException e) {
+                verboseOutput.ILLEGAL_UUID(externalId);
+            }
+        }
+        return new ObjectFactory().createCashedRepresentationInfo(new CachedRepresentationInfo());
+    }
+
+    @GET
+    @Produces({"image/jpeg", "image/png"})
+    @Path("{cachedid: " + BackendConstants.regExpIdentifier + "}/content")
+    @Transactional(readOnly = true)
+    public BufferedImage getCachedRepresentationContent(@PathParam("cachedid") String externalId) throws SQLException, IOException {
+        Number remoteUserID = this.getUserID();
+        if (remoteUserID != null) {
+            try {
+                final Number cachedID = dbIntegrityService.getResourceInternalIdentifier(UUID.fromString(externalId), Resource.CACHED_REPRESENTATION);
+                if (cachedID != null) {
+                    InputStream dbRespond = dbIntegrityService.getCachedRepresentationBlob(cachedID);
+                    ImageIO.setUseCache(false);
+                    BufferedImage result = ImageIO.read(dbRespond);
+                    return result;
+                } else {
+                    verboseOutput.ANNOTATION_NOT_FOUND(externalId);
+                }
+            } catch (IllegalArgumentException e) {
+                verboseOutput.ILLEGAL_UUID(externalId);
+            }
+        } 
+        return null;
+    }
+}
Index: /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/java/eu/dasish/annotation/backend/rest/DebugResource.java
===================================================================
--- /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/java/eu/dasish/annotation/backend/rest/DebugResource.java	(revision 4603)
+++ /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/java/eu/dasish/annotation/backend/rest/DebugResource.java	(revision 4603)
@@ -0,0 +1,147 @@
+/*
+ * Copyright (C) 2013 DASISH
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
+ */
+package eu.dasish.annotation.backend.rest;
+
+import eu.dasish.annotation.schema.AnnotationInfoList;
+import eu.dasish.annotation.schema.ObjectFactory;
+import java.io.BufferedReader;
+import java.io.FileReader;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.UUID;
+import javax.ws.rs.GET;
+import javax.ws.rs.PUT;
+import javax.ws.rs.Path;
+import javax.ws.rs.PathParam;
+import javax.ws.rs.Produces;
+import javax.ws.rs.core.MediaType;
+import javax.xml.bind.JAXBElement;
+import org.springframework.stereotype.Component;
+import org.springframework.transaction.annotation.Transactional;
+
+/**
+ *
+ * @author olhsha
+ */
+@Component
+@Path("/debug")
+public class DebugResource extends ResourceResource {
+
+    private final String developer = "developer";
+
+    @GET
+    @Produces(MediaType.TEXT_XML)
+    @Path("annotations")
+    @Transactional(readOnly = true)
+    public JAXBElement<AnnotationInfoList> getAllAnnotations() throws IOException {
+        Number remoteUserID = this.getUserID();
+        if (remoteUserID != null) {
+            String typeOfAccount = dbIntegrityService.getTypeOfUserAccount(remoteUserID);
+            if (typeOfAccount.equals(admin) || typeOfAccount.equals(developer)) {
+                final AnnotationInfoList annotationInfoList = dbIntegrityService.getAllAnnotationInfos();
+                return new ObjectFactory().createAnnotationInfoList(annotationInfoList);
+            } else {
+                verboseOutput.DEVELOPER_RIGHTS_EXPECTED();
+            }
+        }
+        return new ObjectFactory().createAnnotationInfoList(new AnnotationInfoList());
+    }
+
+    @GET
+    @Produces(MediaType.TEXT_PLAIN)
+    @Path("/logDatabase/{n}")
+    @Transactional(readOnly = true)
+    public String getDasishBackendLog(@PathParam("n") int n) throws IOException {
+        Number remoteUserID = this.getUserID();
+        if (remoteUserID != null) {
+            String typeOfAccount = dbIntegrityService.getTypeOfUserAccount(remoteUserID);
+            if (typeOfAccount.equals(admin) || typeOfAccount.equals(developer)) {
+                return logFile("eu.dasish.annotation.backend.logDatabaseLocation", n);
+            } else {
+                verboseOutput.DEVELOPER_RIGHTS_EXPECTED();
+            }
+        }
+        return " ";
+    }
+
+    @GET
+    @Produces(MediaType.TEXT_PLAIN)
+    @Path("/remoteID")
+    @Transactional(readOnly = true)
+    public String getLoggedInRemoteID(){
+        return dbIntegrityService.getRemoteUser();
+    }
+
+    /////
+    @GET
+    @Produces(MediaType.TEXT_PLAIN)
+    @Path("/logServer/{n}")
+    @Transactional(readOnly = true)
+    public String getDasishServerLog(@PathParam("n") int n) throws IOException {
+        Number remoteUserID = this.getUserID();
+        if (remoteUserID != null) {
+            String typeOfAccount = dbIntegrityService.getTypeOfUserAccount(remoteUserID);
+            if (typeOfAccount.equals(admin) || typeOfAccount.equals(developer)) {
+                return logFile("eu.dasish.annotation.backend.logServerLocation", n);
+            } else {
+                verboseOutput.DEVELOPER_RIGHTS_EXPECTED();
+            }
+        }
+        return " ";
+
+    }
+
+    //////////////////////////////////
+    @PUT
+    @Produces(MediaType.TEXT_XML)
+    @Path("account/{userId}/make/{account}")
+    @Transactional(readOnly = true)
+    public String updateUsersAccount(@PathParam("userId") String userId, @PathParam("account") String account) throws IOException {
+        Number remoteUserID = this.getUserID();
+        if (remoteUserID != null) {
+            String typeOfAccount = dbIntegrityService.getTypeOfUserAccount(remoteUserID);
+            if (typeOfAccount.equals(admin)) {
+                final boolean update = dbIntegrityService.updateAccount(UUID.fromString(userId), account);
+                return (update ? "The account is updated" : "The account is not updated, see the log.");
+            } else {
+                verboseOutput.ADMIN_RIGHTS_EXPECTED(dbIntegrityService.getDataBaseAdmin().getDisplayName(), dbIntegrityService.getDataBaseAdmin().getEMail());
+            }
+        } 
+        return " ";
+    }
+
+    ///////////////////////////////////////////////////
+    private String logFile(String location, int n) throws IOException {
+        BufferedReader reader = new BufferedReader(new FileReader(context.getInitParameter(location)));
+        List<String> lines = new ArrayList<String>();
+        StringBuilder result = new StringBuilder();
+        int i = 0;
+        String line;
+        while ((line = reader.readLine()) != null) {
+            lines.add(line);
+            i++;
+        }
+        // want to read the last n rows, i.e. the rows (i-1), (i-1-1),...,(i-1-(n-1))
+        int last = (i > n) ? (i - n) : 0;
+        for (int j = i - 1; j >= last; j--) {
+            result.append(lines.get(j)).append("\n");
+        }
+        return result.toString();
+    }
+}
Index: /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/java/eu/dasish/annotation/backend/rest/JaxbMarshallerFactory.java
===================================================================
--- /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/java/eu/dasish/annotation/backend/rest/JaxbMarshallerFactory.java	(revision 4603)
+++ /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/java/eu/dasish/annotation/backend/rest/JaxbMarshallerFactory.java	(revision 4603)
@@ -0,0 +1,57 @@
+/*
+ * Copyright (C) 2013 DASISH
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
+ */
+package eu.dasish.annotation.backend.rest;
+
+import java.lang.Class;
+import javax.xml.bind.JAXBContext;
+import javax.xml.bind.JAXBException;
+import javax.xml.bind.Marshaller;
+import javax.xml.bind.PropertyException;
+
+/**
+ *
+ * @author olhsha
+ */
+public class JaxbMarshallerFactory {
+    
+    private JAXBContext context;
+    private Marshaller marshaller;
+    // overwritten by the context.xml's 
+    private String schemaLocation = "http://www.dasish.eu/ns/addit file:/Users/olhsha/repositories/DASISH/t5.6/schema/trunk/annotator-schema/src/main/target/DASISH-schema.xsd";
+    
+    public JaxbMarshallerFactory() throws Exception {
+        
+    }
+    
+    public String getSchemaLocation() {
+        return schemaLocation;
+    }
+    
+    public void setSchemaLocation(String schemaLocation) throws PropertyException {
+        this.schemaLocation = schemaLocation;
+    }
+    
+    public Marshaller createMarshaller(Class<?> type) throws JAXBException{
+        context = JAXBContext.newInstance(type);
+        marshaller = context.createMarshaller();        
+        marshaller.setProperty(Marshaller.JAXB_SCHEMA_LOCATION, schemaLocation);
+        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
+        marshaller.setProperty(Marshaller.JAXB_FRAGMENT, false);
+        return marshaller;
+    }
+}
Index: /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/java/eu/dasish/annotation/backend/rest/NotebookResource.java
===================================================================
--- /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/java/eu/dasish/annotation/backend/rest/NotebookResource.java	(revision 4603)
+++ /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/java/eu/dasish/annotation/backend/rest/NotebookResource.java	(revision 4603)
@@ -0,0 +1,211 @@
+/*
+ * Copyright (C) 2013 DASISH
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
+ */
+package eu.dasish.annotation.backend.rest;
+
+import eu.dasish.annotation.backend.BackendConstants;
+import eu.dasish.annotation.backend.Resource;
+import eu.dasish.annotation.backend.dao.DBIntegrityService;
+import eu.dasish.annotation.schema.Notebook;
+import eu.dasish.annotation.schema.NotebookInfo;
+import eu.dasish.annotation.schema.NotebookInfoList;
+import eu.dasish.annotation.schema.ObjectFactory;
+import eu.dasish.annotation.schema.Permission;
+import eu.dasish.annotation.schema.ReferenceList;
+import eu.dasish.annotation.schema.ResponseBody;
+import java.io.IOException;
+import java.sql.SQLException;
+import java.util.UUID;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import javax.ws.rs.Consumes;
+import javax.ws.rs.GET;
+import javax.ws.rs.PUT;
+import javax.ws.rs.Path;
+import javax.ws.rs.PathParam;
+import javax.ws.rs.Produces;
+import javax.ws.rs.QueryParam;
+import javax.ws.rs.core.Context;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.UriInfo;
+import javax.ws.rs.ext.Providers;
+import javax.xml.bind.JAXBElement;
+import javax.xml.parsers.ParserConfigurationException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+import org.springframework.transaction.annotation.Transactional;
+
+/**
+ * Created on : Jun 11, 2013, 5:10:55 PM
+ *
+ * @author Peter Withers <peter.withers@mpi.nl>
+ */
+@Component
+@Path("/notebooks")
+@Transactional(rollbackFor = {Exception.class, SQLException.class, IOException.class, ParserConfigurationException.class})
+public class NotebookResource extends ResourceResource {
+
+    public NotebookResource() {
+    }
+
+    // changed w.r.t.the spec, query parameter persmission is added
+    @GET
+    @Produces(MediaType.APPLICATION_XML)
+    @Path("")
+    @Transactional(readOnly = true)
+    public JAXBElement<NotebookInfoList> getNotebookInfos(@QueryParam("permission") String permissionMode) throws IOException {
+        dbIntegrityService.setServiceURI(uriInfo.getBaseUri().toString());
+        Number remoteUserID = this.getUserID();
+        if (remoteUserID != null) {
+            if (permissionMode.equalsIgnoreCase("reader") || permissionMode.equalsIgnoreCase("writer") || permissionMode.equalsIgnoreCase("owner")) {
+                NotebookInfoList notebookInfos = dbIntegrityService.getNotebooks(remoteUserID, permissionMode);
+                return new ObjectFactory().createNotebookInfoList(notebookInfos);
+            } else {
+                verboseOutput.INVALID_PERMISSION_MODE(permissionMode);
+            }
+        }
+        return (new ObjectFactory()).createNotebookInfoList(new NotebookInfoList());
+    }
+
+    @GET
+    @Produces(MediaType.APPLICATION_XML)
+    @Path("owned")
+    @Transactional(readOnly = true)
+    public JAXBElement<ReferenceList> getOwnedNotebooks() throws IOException {
+        Number remoteUserID = this.getUserID();
+        if (remoteUserID != null) {
+            ReferenceList references = dbIntegrityService.getNotebooksOwnedBy(remoteUserID);
+            return new ObjectFactory().createReferenceList(references);
+        }
+        return new ObjectFactory().createReferenceList(new ReferenceList());
+    }
+
+    @GET
+    @Produces(MediaType.APPLICATION_XML)
+    @Path("{notebookid: " + BackendConstants.regExpIdentifier + "}/{permission}")
+    @Transactional(readOnly = true)
+    public JAXBElement<ReferenceList> getPrincipals(@PathParam("notebookid") String externalIdentifier, @PathParam("permission") String permissionMode) throws IOException {
+        Number remoteUserID = this.getUserID();
+        if (remoteUserID != null) {
+            Number notebookID = dbIntegrityService.getResourceInternalIdentifier(UUID.fromString(externalIdentifier), Resource.NOTEBOOK);
+            if (notebookID != null) {
+                if (dbIntegrityService.hasAccess(notebookID, remoteUserID, Permission.fromValue("reader"))) {
+                    ReferenceList principals = dbIntegrityService.getPrincipals(notebookID, permissionMode);
+                    return new ObjectFactory().createReferenceList(principals);
+                } else {
+                    verboseOutput.FORBIDDEN_NOTEBOOK_READING(externalIdentifier, dbIntegrityService.getAnnotationOwner(notebookID).getDisplayName(), dbIntegrityService.getAnnotationOwner(notebookID).getEMail());
+                }
+            } else {
+                verboseOutput.NOTEBOOK_NOT_FOUND(externalIdentifier);
+            }
+        }
+        return new ObjectFactory().createReferenceList(new ReferenceList());
+    }
+
+    // Notebook and NotebookInfo (metadata) schemata may be changed
+    // 1) we do not have information "private notebook" directly in the xml, but we have readers and writers in the schema
+    //so if both are empty then we see that it is private for the owner
+    // or shall we change the scheme? for notebooks
+    // 2) d we need to include the reference list of annotations in teh metadata of the notebook
+    @GET
+    @Produces(MediaType.APPLICATION_XML)
+    @Path("{notebookid: " + BackendConstants.regExpIdentifier + "}/metadata")
+    @Transactional(readOnly = true)
+    public JAXBElement<Notebook> getNotebook(@PathParam("notebookid") String externalIdentifier) throws IOException {
+        Number remoteUserID = this.getUserID();
+        if (remoteUserID != null) {
+            Number notebookID = dbIntegrityService.getResourceInternalIdentifier(UUID.fromString(externalIdentifier), Resource.NOTEBOOK);
+            if (notebookID != null) {
+                if (dbIntegrityService.hasAccess(notebookID, remoteUserID, Permission.fromValue("reader"))) {
+                    Notebook notebook = dbIntegrityService.getNotebook(notebookID);
+                    return new ObjectFactory().createNotebook(notebook);
+                } else {
+                    verboseOutput.FORBIDDEN_NOTEBOOK_READING(externalIdentifier, dbIntegrityService.getAnnotationOwner(notebookID).getDisplayName(), dbIntegrityService.getAnnotationOwner(notebookID).getEMail());
+                }
+            } else {
+                verboseOutput.NOTEBOOK_NOT_FOUND(externalIdentifier);
+            }
+        }
+        return new ObjectFactory().createNotebook(new Notebook());
+    }
+
+    @GET
+    @Produces(MediaType.APPLICATION_XML)
+    @Path("{notebookid: " + BackendConstants.regExpIdentifier + "}")
+    @Transactional(readOnly = true)
+    public JAXBElement<ReferenceList> getNotebookAnnotations(@PathParam("notebookid") String externalIdentifier,
+            @QueryParam("maximumAnnotations") int maximumAnnotations,
+            @QueryParam("startAnnotation") int startAnnotations,
+            @QueryParam("orderBy") String orderBy,
+            @QueryParam("descending") boolean desc) throws IOException {
+
+        Number remoteUserID = this.getUserID();
+        if (remoteUserID != null) {
+            Number notebookID = dbIntegrityService.getResourceInternalIdentifier(UUID.fromString(externalIdentifier), Resource.NOTEBOOK);
+            if (notebookID != null) {
+                if (dbIntegrityService.hasAccess(notebookID, remoteUserID, Permission.fromValue("reader"))) {
+                    ReferenceList annotations = dbIntegrityService.getAnnotationsForNotebook(notebookID, startAnnotations, maximumAnnotations, orderBy, desc);
+                    return new ObjectFactory().createReferenceList(annotations);
+                } else {
+                    verboseOutput.FORBIDDEN_NOTEBOOK_READING(externalIdentifier, dbIntegrityService.getAnnotationOwner(notebookID).getDisplayName(), dbIntegrityService.getAnnotationOwner(notebookID).getEMail());
+                }
+            } else {
+                verboseOutput.NOTEBOOK_NOT_FOUND(externalIdentifier);
+            }
+        }
+        return new ObjectFactory().createReferenceList(new ReferenceList());
+    }
+
+    @PUT
+    @Consumes(MediaType.APPLICATION_XML)
+    @Produces(MediaType.APPLICATION_XML)
+    @Path("{notebookid: " + BackendConstants.regExpIdentifier + "}")
+    public JAXBElement<ResponseBody> updateNotebookInfo(@PathParam("notebookid") String externalIdentifier, NotebookInfo notebookInfo) throws IOException {
+
+        Number remoteUserID = this.getUserID();
+        if (remoteUserID != null) {
+            String path = uriInfo.getBaseUri().toString();
+            String notebookURI = notebookInfo.getRef();
+            if (!(path + "notebook/" + externalIdentifier).equals(notebookURI)) {
+                verboseOutput.IDENTIFIER_MISMATCH(externalIdentifier);
+                return new ObjectFactory().createResponseBody(new ResponseBody());
+            }
+
+            try {
+                final Number notebookID = dbIntegrityService.getResourceInternalIdentifier(UUID.fromString(externalIdentifier), Resource.NOTEBOOK);
+                if (notebookID != null) {
+                    if (remoteUserID.equals(dbIntegrityService.getNotebookOwner(notebookID)) || dbIntegrityService.getTypeOfUserAccount(remoteUserID).equals(admin)) {
+                        boolean success = dbIntegrityService.updateNotebookMetadata(notebookID, notebookInfo);
+                        if (success) {
+                            return new ObjectFactory().createResponseBody(dbIntegrityService.makeNotebookResponseEnvelope(notebookID));
+                        }
+                    } else {
+                        verboseOutput.FORBIDDEN_PERMISSION_CHANGING(externalIdentifier, dbIntegrityService.getAnnotationOwner(notebookID).getDisplayName(), dbIntegrityService.getAnnotationOwner(notebookID).getEMail());
+                        loggerServer.debug(" Ownership changing is the part of the full update of the notebook metadadata.");
+                    }
+                } else {
+                    verboseOutput.NOTEBOOK_NOT_FOUND(externalIdentifier);
+                }
+            } catch (IllegalArgumentException e) {
+                verboseOutput.ILLEGAL_UUID(externalIdentifier);
+            }
+        }
+        return new ObjectFactory().createResponseBody(new ResponseBody());
+    }
+}
Index: /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/java/eu/dasish/annotation/backend/rest/ResourceJaxbMarshallerProvider.java
===================================================================
--- /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/java/eu/dasish/annotation/backend/rest/ResourceJaxbMarshallerProvider.java	(revision 4603)
+++ /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/java/eu/dasish/annotation/backend/rest/ResourceJaxbMarshallerProvider.java	(revision 4603)
@@ -0,0 +1,52 @@
+/*
+ * Copyright (C) 2013 DASISH
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
+ */
+package eu.dasish.annotation.backend.rest;
+
+import javax.ws.rs.ext.ContextResolver;
+import javax.ws.rs.ext.Provider;
+import javax.xml.bind.JAXBException;
+import javax.xml.bind.Marshaller;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+
+/**
+ *
+ * @author olhsha
+ */
+@Provider
+@Component
+public class ResourceJaxbMarshallerProvider implements ContextResolver<Marshaller> {
+
+    @Autowired
+    private JaxbMarshallerFactory jaxbMarshallerFactory;
+
+    /*
+     * ------------------------
+     * Interface Implementation
+     * ------------------------
+     */
+    @Override
+    public Marshaller getContext(Class<?> type) {
+        try{
+           return jaxbMarshallerFactory.createMarshaller(type);
+        } catch (JAXBException e) {
+            System.out.println("Cannot create a marshaller for type "+type.getCanonicalName());
+            return null;
+        }
+    }
+}
Index: /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/java/eu/dasish/annotation/backend/rest/ResourceResource.java
===================================================================
--- /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/java/eu/dasish/annotation/backend/rest/ResourceResource.java	(revision 4603)
+++ /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/java/eu/dasish/annotation/backend/rest/ResourceResource.java	(revision 4603)
@@ -0,0 +1,73 @@
+/*
+ * Copyright (C) 2013 DASISH
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
+ */
+package eu.dasish.annotation.backend.rest;
+
+import eu.dasish.annotation.backend.dao.DBIntegrityService;
+import java.io.IOException;
+import javax.servlet.ServletContext;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import javax.ws.rs.core.Context;
+import javax.ws.rs.core.UriInfo;
+import javax.ws.rs.ext.Providers;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+
+/**
+ *
+ * @author olhsha
+ */
+public class ResourceResource {
+
+    @Autowired
+    protected DBIntegrityService dbIntegrityService;
+    @Context
+    protected HttpServletRequest httpServletRequest;
+    @Context
+    protected HttpServletResponse httpServletResponse;
+    @Context
+    protected UriInfo uriInfo;
+    @Context
+    protected Providers providers;
+    @Context
+    protected ServletContext context;
+    protected Logger loggerServer = LoggerFactory.getLogger(HttpServletResponse.class);
+    protected VerboseOutput verboseOutput;
+    protected String admin = "admin";
+    protected String anonym = "anonymous";
+    
+    public Number getUserID() throws IOException {
+        verboseOutput = new VerboseOutput(httpServletResponse, loggerServer);
+        String remoteUser = dbIntegrityService.getRemoteUser();        
+        if (remoteUser != null) {
+            if (!remoteUser.equals(anonym)) {
+                final Number userID = dbIntegrityService.getUserInternalIDFromRemoteID(remoteUser);
+                if (userID != null) {
+                    return userID;
+                } 
+                verboseOutput.REMOTE_PRINCIPAL_NOT_FOUND(remoteUser,dbIntegrityService.getDataBaseAdmin().getDisplayName(), dbIntegrityService.getDataBaseAdmin().getEMail());
+                return null;
+            }
+        }
+
+        verboseOutput.NOT_LOGGED_IN(dbIntegrityService.getDataBaseAdmin().getDisplayName(), dbIntegrityService.getDataBaseAdmin().getEMail());
+        return null;
+
+    }
+}
Index: /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/java/eu/dasish/annotation/backend/rest/TargetResource.java
===================================================================
--- /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/java/eu/dasish/annotation/backend/rest/TargetResource.java	(revision 4603)
+++ /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/java/eu/dasish/annotation/backend/rest/TargetResource.java	(revision 4603)
@@ -0,0 +1,166 @@
+/*
+ * Copyright (C) 2013 DASISH
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
+ */
+package eu.dasish.annotation.backend.rest;
+
+import com.sun.jersey.multipart.BodyPartEntity;
+import com.sun.jersey.multipart.MultiPart;
+import eu.dasish.annotation.backend.BackendConstants;
+import eu.dasish.annotation.backend.Resource;
+import eu.dasish.annotation.schema.CachedRepresentationInfo;
+import eu.dasish.annotation.schema.ObjectFactory;
+import eu.dasish.annotation.schema.ReferenceList;
+import eu.dasish.annotation.schema.Target;
+import java.io.IOException;
+import java.io.InputStream;
+import java.sql.SQLException;
+import java.util.UUID;
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.Consumes;
+import javax.ws.rs.DELETE;
+import javax.ws.rs.GET;
+import javax.ws.rs.POST;
+import javax.ws.rs.Path;
+import javax.ws.rs.PathParam;
+import javax.ws.rs.Produces;
+import javax.ws.rs.core.MediaType;
+import javax.xml.bind.JAXBElement;
+import javax.xml.parsers.ParserConfigurationException;
+import org.springframework.stereotype.Component;
+import org.springframework.transaction.annotation.Transactional;
+
+/**
+ *
+ * @author olhsha
+ */
+/**
+ *
+ * @author olhsha
+ */
+@Component
+@Path("/targets")
+@Transactional(rollbackFor = {Exception.class, SQLException.class, IOException.class, ParserConfigurationException.class})
+public class TargetResource extends ResourceResource {
+
+    public void setHttpRequest(HttpServletRequest request) {
+        this.httpServletRequest = request;
+    }
+
+    public TargetResource() {
+    }
+
+    // TODOD both unit tests
+    @GET
+    @Produces(MediaType.TEXT_XML)
+    @Path("{targetid: " + BackendConstants.regExpIdentifier + "}")
+    @Transactional(readOnly = true)
+    public JAXBElement<Target> getTarget(@PathParam("targetid") String externalIdentifier) throws SQLException, IOException {
+        Number remoteUserID = this.getUserID();
+        if (remoteUserID != null) {
+            try {
+                final Number targetID = dbIntegrityService.getResourceInternalIdentifier(UUID.fromString(externalIdentifier), Resource.TARGET);
+                if (targetID != null) {
+                    final Target target = dbIntegrityService.getTarget(targetID);
+                    return new ObjectFactory().createTarget(target);
+                } else {
+                    verboseOutput.TARGET_NOT_FOUND(externalIdentifier);
+                }
+            } catch (IllegalArgumentException e) {
+                verboseOutput.ILLEGAL_UUID(externalIdentifier);
+            }
+        }
+        return new ObjectFactory().createTarget(new Target());
+    }
+
+    // TODOD both unit tests
+    @GET
+    @Produces(MediaType.TEXT_XML)
+    @Path("{targetid: " + BackendConstants.regExpIdentifier + "}/versions")
+    @Transactional(readOnly = true)
+    public JAXBElement<ReferenceList> getSiblingTargets(@PathParam("targetid") String externalIdentifier) throws SQLException, IOException {
+        Number remoteUserID = this.getUserID();
+        if (remoteUserID != null) {
+            try {
+                final Number targetID = dbIntegrityService.getResourceInternalIdentifier(UUID.fromString(externalIdentifier), Resource.TARGET);
+                if (targetID != null) {
+                    final ReferenceList siblings = dbIntegrityService.getTargetsForTheSameLinkAs(targetID);
+                    return new ObjectFactory().createReferenceList(siblings);
+                } else {
+                    verboseOutput.TARGET_NOT_FOUND(externalIdentifier);
+                }
+            } catch (IllegalArgumentException e) {
+                verboseOutput.ILLEGAL_UUID(externalIdentifier);
+            }
+        }
+        return new ObjectFactory().createReferenceList(new ReferenceList());
+    }
+
+    @POST
+    @Consumes("multipart/mixed")
+    @Produces(MediaType.APPLICATION_XML)
+    @Path("{targetid: " + BackendConstants.regExpIdentifier + "}/fragment/{fragmentDescriptor}/cached")
+    public JAXBElement<CachedRepresentationInfo> postCached(@PathParam("targetid") String targetIdentifier,
+            @PathParam("fragmentDescriptor") String fragmentDescriptor,
+            MultiPart multiPart) throws SQLException, IOException {
+        Number remoteUserID = this.getUserID();
+        if (remoteUserID != null) {
+            try {
+                final Number targetID = dbIntegrityService.getResourceInternalIdentifier(UUID.fromString(targetIdentifier), Resource.TARGET);
+                if (targetID != null) {
+                    CachedRepresentationInfo metadata = multiPart.getBodyParts().get(0).getEntityAs(CachedRepresentationInfo.class);
+                    BodyPartEntity bpe = (BodyPartEntity) multiPart.getBodyParts().get(1).getEntity();
+                    InputStream cachedSource = bpe.getInputStream();
+                    final Number[] respondDB = dbIntegrityService.addCachedForTarget(targetID, fragmentDescriptor, metadata, cachedSource);
+                    final CachedRepresentationInfo cachedInfo = dbIntegrityService.getCachedRepresentationInfo(respondDB[1]);
+                    return new ObjectFactory().createCashedRepresentationInfo(cachedInfo);
+                } else {
+                    verboseOutput.TARGET_NOT_FOUND(targetIdentifier);
+                }
+            } catch (IllegalArgumentException e) {
+                verboseOutput.ILLEGAL_UUID(targetIdentifier);
+            }
+        }
+        return new ObjectFactory().createCashedRepresentationInfo(new CachedRepresentationInfo());
+    }
+
+    @DELETE
+    @Path("{targetid: " + BackendConstants.regExpIdentifier + "}/cached/{cachedid: " + BackendConstants.regExpIdentifier + "}")
+    public String deleteCachedForTarget(@PathParam("targetid") String targetExternalIdentifier,
+            @PathParam("cachedid") String cachedExternalIdentifier) throws SQLException, IOException {
+        Number remoteUserID = this.getUserID();
+        if (remoteUserID != null) {
+            try {
+                final Number targetID = dbIntegrityService.getResourceInternalIdentifier(UUID.fromString(targetExternalIdentifier), Resource.TARGET);
+                if (targetID != null) {
+                    final Number cachedID = dbIntegrityService.getResourceInternalIdentifier(UUID.fromString(cachedExternalIdentifier), Resource.CACHED_REPRESENTATION);
+                    if (cachedID != null) {
+                        int[] resultDelete = dbIntegrityService.deleteCachedRepresentationOfTarget(targetID, cachedID);
+                        String result = Integer.toString(resultDelete[0]);
+                        return result + " pair(s) target-cached deleted.";
+                    } else {
+                        verboseOutput.CACHED_REPRESENTATION_NOT_FOUND(cachedExternalIdentifier);
+                    }
+                } else {
+                    verboseOutput.TARGET_NOT_FOUND(targetExternalIdentifier);
+                }
+            } catch (IllegalArgumentException e) {
+                verboseOutput.ILLEGAL_UUID(targetExternalIdentifier);
+            }
+        }
+        return " ";
+    }
+}
Index: /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/java/eu/dasish/annotation/backend/rest/UserResource.java
===================================================================
--- /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/java/eu/dasish/annotation/backend/rest/UserResource.java	(revision 4603)
+++ /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/java/eu/dasish/annotation/backend/rest/UserResource.java	(revision 4603)
@@ -0,0 +1,252 @@
+/*
+ * Copyright (C) 2013 DASISH
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
+ */
+package eu.dasish.annotation.backend.rest;
+
+import eu.dasish.annotation.backend.Resource;
+import eu.dasish.annotation.backend.dao.DBIntegrityService;
+import eu.dasish.annotation.schema.CurrentUserInfo;
+import eu.dasish.annotation.schema.ObjectFactory;
+import eu.dasish.annotation.schema.User;
+import java.io.IOException;
+import java.sql.SQLException;
+import java.util.UUID;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import javax.ws.rs.Consumes;
+import javax.ws.rs.DELETE;
+import javax.ws.rs.GET;
+import javax.ws.rs.POST;
+import javax.ws.rs.PUT;
+import javax.ws.rs.Path;
+import javax.ws.rs.PathParam;
+import javax.ws.rs.Produces;
+import javax.ws.rs.QueryParam;
+import javax.ws.rs.core.Context;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.UriInfo;
+import javax.xml.bind.JAXBElement;
+import javax.xml.parsers.ParserConfigurationException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+import org.springframework.transaction.annotation.Transactional;
+
+/**
+ *
+ * @author olhsha
+ */
+@Component
+@Path("/users")
+@Transactional(rollbackFor = {Exception.class, SQLException.class, IOException.class, ParserConfigurationException.class})
+public class UserResource extends ResourceResource{
+
+  
+
+    public void setHttpRequest(HttpServletRequest request) {
+        this.httpServletRequest = request;
+    }
+
+    public UserResource() {
+    }
+
+    @GET
+    @Produces(MediaType.TEXT_XML)
+    @Path("{userid}")
+    @Transactional(readOnly = true)
+    public JAXBElement<User> getUser(@PathParam("userid") String externalIdentifier) throws SQLException, IOException {
+       Number remoteUserID = this.getUserID();
+       if (remoteUserID != null) {
+            try {
+                final Number userID = dbIntegrityService.getResourceInternalIdentifier(UUID.fromString(externalIdentifier), Resource.PRINCIPAL);
+                if (userID != null) {
+                    final User user = dbIntegrityService.getUser(userID);
+                    return new ObjectFactory().createUser(user);
+                } else {
+                    verboseOutput.PRINCIPAL_NOT_FOUND(externalIdentifier);
+                }
+            } catch (IllegalArgumentException e) {
+                verboseOutput.ILLEGAL_UUID(externalIdentifier);
+            }
+        } 
+        return new ObjectFactory().createUser(new User());
+    }
+    
+    @GET
+    @Produces(MediaType.TEXT_XML)
+    @Path("admin")
+    @Transactional(readOnly = true)
+    public String getAdmin() throws IOException {
+       Number remoteUserID = this.getUserID();
+       if (remoteUserID != null) {
+           return "The admin of the server database "+ dbIntegrityService.getDataBaseAdmin().getDisplayName()+" is availiable via e-mail "+dbIntegrityService.getDataBaseAdmin().getEMail();
+        } 
+        return "You are not geconginsed as a registered user.";
+    }
+
+    @GET
+    @Produces(MediaType.TEXT_XML)
+    @Path("/info")
+    @Transactional(readOnly = true)
+    public JAXBElement<User> getUserByInfo(@QueryParam("email") String email) throws SQLException, IOException {
+        Number remoteUserID = this.getUserID();
+        if (remoteUserID != null) {
+            final User user = dbIntegrityService.getUserByInfo(email);
+            if (user != null) {
+                return new ObjectFactory().createUser(user);
+            } else {
+                verboseOutput.PRINCIPAL_NOT_FOUND_BY_INFO(email);
+            }
+        } 
+        return new ObjectFactory().createUser(new User());
+    }
+
+    @GET
+    @Produces(MediaType.TEXT_XML)
+    @Path("{userid}/current")
+    @Transactional(readOnly = true)
+    public JAXBElement<CurrentUserInfo> getCurrentUserInfo(@PathParam("userid") String externalIdentifier) throws IOException {
+        Number remoteUserID = this.getUserID();
+        if (remoteUserID != null) {
+            try {
+                final Number userID = dbIntegrityService.getResourceInternalIdentifier(UUID.fromString(externalIdentifier), Resource.PRINCIPAL);
+                if (userID != null) {
+                    final CurrentUserInfo userInfo = new CurrentUserInfo();
+                    userInfo.setRef(dbIntegrityService.getResourceURI(userID, Resource.PRINCIPAL));
+                    userInfo.setCurrentUser(ifLoggedIn(userID));
+                    return new ObjectFactory().createCurrentUserInfo(userInfo);
+                } else {
+                    verboseOutput.PRINCIPAL_NOT_FOUND(externalIdentifier);
+                }
+            } catch (IllegalArgumentException e) {
+                verboseOutput.ILLEGAL_UUID(externalIdentifier);
+            }
+        }
+        return new ObjectFactory().createCurrentUserInfo(new CurrentUserInfo());
+    }
+
+  
+
+    @POST
+    @Consumes(MediaType.APPLICATION_XML)
+    @Produces(MediaType.APPLICATION_XML)
+    @Path("{remoteId}")
+    public JAXBElement<User> addUser(@PathParam("remoteId") String remoteId, User user) throws SQLException, IOException {
+        Number remoteUserID = this.getUserID();
+        if (remoteUserID != null) {
+            if (dbIntegrityService.getTypeOfUserAccount(remoteUserID).equals(admin)) {
+                final Number userID = dbIntegrityService.addUser(user, remoteId);
+                if (userID != null) {
+                    final User addedUser = dbIntegrityService.getUser(userID);
+                    return new ObjectFactory().createUser(addedUser);
+                } else {
+                    verboseOutput.PRINCIPAL_IS_NOT_ADDED_TO_DB();
+                }
+            } else {
+                verboseOutput.ADMIN_RIGHTS_EXPECTED(dbIntegrityService.getDataBaseAdmin().getDisplayName(), dbIntegrityService.getDataBaseAdmin().getEMail());
+            }
+        } 
+        return new ObjectFactory().createUser(new User());
+    }
+
+    @PUT
+    @Consumes(MediaType.APPLICATION_XML)
+    @Produces(MediaType.APPLICATION_XML)
+    @Path("")
+    public JAXBElement<User> updateUser(User user) throws IOException {
+       Number remoteUserID = this.getUserID();
+        if (remoteUserID != null) {
+            if (dbIntegrityService.getTypeOfUserAccount(remoteUserID).equals(admin)) {
+                final Number userID = dbIntegrityService.updateUser(user);
+                if (userID != null) {
+                    final User addedUser = dbIntegrityService.getUser(userID);
+                    return new ObjectFactory().createUser(addedUser);
+                } else {
+                    verboseOutput.PRINCIPAL_NOT_FOUND(user.getURI());
+                }
+            } else {
+                verboseOutput.ADMIN_RIGHTS_EXPECTED(dbIntegrityService.getDataBaseAdmin().getDisplayName(), dbIntegrityService.getDataBaseAdmin().getEMail());
+            }
+        } 
+        return new ObjectFactory().createUser(new User());
+    }
+
+    @PUT
+    @Produces(MediaType.TEXT_PLAIN)
+    @Path("{externalId}/account/{accountType}")
+    public String updateUserAccount(@PathParam("externalId") String externalId, @PathParam("accountType") String accountType) throws IOException {
+        Number remoteUserID = this.getUserID();
+        if (remoteUserID != null) {
+            if (dbIntegrityService.getTypeOfUserAccount(remoteUserID).equals(admin)) {
+                final boolean updated = dbIntegrityService.updateAccount(UUID.fromString(externalId), accountType);
+                if (updated) {
+                    return "The account was updated to " + dbIntegrityService.getTypeOfUserAccount(dbIntegrityService.getResourceInternalIdentifier(UUID.fromString(externalId), Resource.PRINCIPAL));
+                } else {
+                    verboseOutput.ACCOUNT_IS_NOT_UPDATED();
+                }
+            } else {
+                verboseOutput.ADMIN_RIGHTS_EXPECTED(dbIntegrityService.getDataBaseAdmin().getDisplayName(), dbIntegrityService.getDataBaseAdmin().getEMail());
+            }
+        } 
+        return " ";
+    }
+
+    @DELETE
+    @Path("{userId}")
+    public String deleteUser(@PathParam("userId") String externalIdentifier) throws IOException {
+       Number remoteUserID = this.getUserID();
+        if (remoteUserID != null) {
+            if (dbIntegrityService.getTypeOfUserAccount(remoteUserID).equals(admin)) {
+                final Number userID = dbIntegrityService.getResourceInternalIdentifier(UUID.fromString(externalIdentifier), Resource.PRINCIPAL);
+                if (userID != null) {
+                    final Integer result = dbIntegrityService.deleteUser(userID);
+                    return "There is " + result.toString() + " row deleted";
+                } else {
+                    verboseOutput.PRINCIPAL_NOT_FOUND(externalIdentifier);
+                }
+            } else {
+                verboseOutput.ADMIN_RIGHTS_EXPECTED(dbIntegrityService.getDataBaseAdmin().getDisplayName(), dbIntegrityService.getDataBaseAdmin().getEMail());
+            }
+        } 
+        return " ";
+    }
+
+    @DELETE
+    @Path("{userId}/safe")
+    public String deleteUserSafe(@PathParam("userId") String externalIdentifier) throws IOException {
+       Number remoteUserID = this.getUserID();
+        if (remoteUserID != null) {
+            if (dbIntegrityService.getTypeOfUserAccount(remoteUserID).equals(admin)) {
+                final Number userID = dbIntegrityService.getResourceInternalIdentifier(UUID.fromString(externalIdentifier), Resource.PRINCIPAL);
+                if (userID != null) {
+                    final Integer result = dbIntegrityService.deleteUserSafe(userID);
+                    return "There is " + result.toString() + " row deleted";
+                } else {
+                    verboseOutput.PRINCIPAL_NOT_FOUND(externalIdentifier);
+                }
+            } else {
+                verboseOutput.ADMIN_RIGHTS_EXPECTED(dbIntegrityService.getDataBaseAdmin().getDisplayName(), dbIntegrityService.getDataBaseAdmin().getEMail());
+            }
+        } 
+        return " ";
+    }
+
+    private boolean ifLoggedIn(Number userID) {
+        return (dbIntegrityService.getRemoteUser()).equals(dbIntegrityService.getUserRemoteID(userID));
+    }
+}
Index: /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/java/eu/dasish/annotation/backend/rest/VerboseOutput.java
===================================================================
--- /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/java/eu/dasish/annotation/backend/rest/VerboseOutput.java	(revision 4603)
+++ /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/java/eu/dasish/annotation/backend/rest/VerboseOutput.java	(revision 4603)
@@ -0,0 +1,212 @@
+/*
+ * Copyright (C) 2013 DASISH
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
+ */
+package eu.dasish.annotation.backend.rest;
+
+import java.io.IOException;
+import javax.servlet.http.HttpServletResponse;
+import org.slf4j.Logger;
+
+/**
+ *
+ * @author olhsha
+ */
+public class VerboseOutput {
+
+    private HttpServletResponse httpServletResponse;
+    private Logger logger;
+
+    private class MessageStatus {
+
+        String message;
+        int status;
+
+        public MessageStatus(String msg, int status) {
+            message = msg;
+            this.status = status;
+        }
+    }
+
+    public VerboseOutput(HttpServletResponse httpServletResponse, Logger logger) {
+        this.httpServletResponse = httpServletResponse;
+        this.logger = logger;
+    }
+
+    private MessageStatus _NOT_LOGGED_IN(String adminName, String adminEmail) {
+        return new MessageStatus(" The user is not logged-in or its remote login is corrupted by setting to null. In the latter case contact the admin "+adminName+" via the e-mail "+adminEmail, HttpServletResponse.SC_UNAUTHORIZED);
+    }
+
+    private MessageStatus _FORBIDDEN_RESOURCE_ACTION(String identifier, String resource, String action, String ownerName, String ownerEMail) {
+        return new MessageStatus(" The logged-in principal cannot "+action+" the "+resource+" with the identifier " + identifier+ ". Contact the resource's owner "+ownerName+" via the e-mail "+ownerEMail, HttpServletResponse.SC_FORBIDDEN);
+    }
+
+
+    private MessageStatus _ILLEGAL_UUID(String identifier) {
+        return new MessageStatus("The string '" + identifier + "' is not a valid UUID.", HttpServletResponse.SC_BAD_REQUEST);
+    }
+
+    private MessageStatus _REMOTE_PRINCIPAL_NOT_FOUND(String remoteID, String adminName, String adminEmail) {
+        return new MessageStatus("The logged in principal with the remote ID " + remoteID + " is not found in the database or his/her internal DB identifier is corrupted by setting to null. Contact the database admin "+adminName+" by the e-mail "+adminEmail, HttpServletResponse.SC_NOT_FOUND);
+    }
+
+    private MessageStatus resourceNotFound(String externalIdentifier, String resourceType) {
+        return new MessageStatus("A(n) " + resourceType + " with the indentifier " + externalIdentifier + " is not found in the database, or its internal database identifier is corrupted by setting to null.", HttpServletResponse.SC_NOT_FOUND);
+    }
+
+  
+    private MessageStatus _PRINCIPAL_NOT_FOUND(String externalIdentifier) {
+        return resourceNotFound(externalIdentifier, "principal");
+    }
+
+    private MessageStatus _ANNOTATION_NOT_FOUND(String externalIdentifier) {
+        return resourceNotFound(externalIdentifier, "annotation");
+    }
+
+    private MessageStatus _NOTEBOOK_NOT_FOUND(String externalIdentifier) {
+        return resourceNotFound(externalIdentifier, "notebook");
+    }
+
+    private MessageStatus _TARGET_NOT_FOUND(String externalIdentifier) {
+        return resourceNotFound(externalIdentifier, "target");
+    }
+
+    private MessageStatus _CACHED_REPRESENTATION_NOT_FOUND(String externalIdentifier) {
+        return resourceNotFound(externalIdentifier, "cached representation");
+    }
+
+    private MessageStatus _INVALID_PERMISSION_MODE(String permissionMode) {
+        return new MessageStatus(permissionMode + " is an invalid permission value, which must be either owner, or reader, or writer.", HttpServletResponse.SC_BAD_REQUEST);
+    }
+
+    private MessageStatus _IDENTIFIER_MISMATCH(String identifier) {
+        return new MessageStatus("Wrong request: the annotation (notebook) identifier   " + identifier + " and the annotation (notebook) ID from the request body do not match.", HttpServletResponse.SC_BAD_REQUEST);
+    }
+
+    private MessageStatus _ADMIN_RIGHTS_EXPECTED(String adminName, String adminEmail) {
+        return new MessageStatus("The request can be performed only by the principal with the admin rights. Contact the admin "+adminName+" via e-mail "+adminEmail, HttpServletResponse.SC_FORBIDDEN);
+    }
+
+    private MessageStatus _DEVELOPER_RIGHTS_EXPECTED() {
+        return new MessageStatus("The request can be performed only by the principal with the developer's or admin rights. The logged in principal does not have either developer's or admin rights.", HttpServletResponse.SC_FORBIDDEN);
+    }
+
+    private MessageStatus _PRINCIPAL_NOT_FOUND_BY_INFO(String email) {
+        return new MessageStatus("The principal with the info (e-mail) " + email + " is not found in the database.", HttpServletResponse.SC_NOT_FOUND);
+    }
+
+    private MessageStatus _PRINCIPAL_IS_NOT_ADDED_TO_DB() {
+        return new MessageStatus("The principal is not added the database, probably becuase another principal with the same e-mail already exists in the data base.", HttpServletResponse.SC_BAD_REQUEST);
+    }
+
+    private MessageStatus _ACCOUNT_IS_NOT_UPDATED() {
+        return new MessageStatus("The account is not updated", HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+    }
+    
+    private MessageStatus _LOGOUT() {
+        return new MessageStatus("You are logged out.", HttpServletResponse.SC_UNAUTHORIZED);
+    }
+
+    private void sendMessage(MessageStatus msg) throws IOException {
+        logger.debug(msg.status + ": " + msg.message);
+        httpServletResponse.sendError(msg.status, msg.message);
+    }
+
+    ///////////////////////////////
+    public void NOT_LOGGED_IN(String adminName, String adminEmail) throws IOException {
+        this.sendMessage(this._NOT_LOGGED_IN(adminName, adminEmail));
+    }
+
+    public void FORBIDDEN_NOTEBOOK_READING(String identifier, String ownerName, String ownerEMail) throws IOException {
+        this.sendMessage(this._FORBIDDEN_RESOURCE_ACTION(identifier, "notebook", "read", ownerName, ownerEMail));
+    }
+
+    public void FORBIDDEN_NOTEBOOK_WRITING(String identifier, String ownerName, String ownerEMail) throws IOException {
+         this.sendMessage(this._FORBIDDEN_RESOURCE_ACTION(identifier, "notebook", "write", ownerName, ownerEMail));
+    }
+
+    public void FORBIDDEN_ANNOTATION_READING(String identifier, String ownerName, String ownerEMail) throws IOException {
+         this.sendMessage(this._FORBIDDEN_RESOURCE_ACTION(identifier, "annotation", "read", ownerName, ownerEMail));;
+    }
+
+    public void FORBIDDEN_ANNOTATION_WRITING(String identifier, String ownerName, String ownerEMail) throws IOException {
+         this.sendMessage(this._FORBIDDEN_RESOURCE_ACTION(identifier, "annotation", "write", ownerName, ownerEMail));
+    }
+
+    public void FORBIDDEN_PERMISSION_CHANGING(String identifier, String ownerName, String ownerEMail) throws IOException {
+         this.sendMessage(this._FORBIDDEN_RESOURCE_ACTION(identifier, "resource","change", ownerName, ownerEMail));
+    }
+
+    public void ILLEGAL_UUID(String identifier) throws IOException {
+        this.sendMessage(this._ILLEGAL_UUID(identifier));
+    }
+
+    public void REMOTE_PRINCIPAL_NOT_FOUND(String remoteID, String adminName, String adminEmail) throws IOException {
+        this.sendMessage(this._REMOTE_PRINCIPAL_NOT_FOUND(remoteID, adminName, adminEmail));
+    }
+
+    public void PRINCIPAL_NOT_FOUND(String externalIdentifier) throws IOException {
+        this.sendMessage(this._PRINCIPAL_NOT_FOUND(externalIdentifier));
+    }
+
+    public void ANNOTATION_NOT_FOUND(String externalIdentifier) throws IOException {
+        this.sendMessage(this._ANNOTATION_NOT_FOUND(externalIdentifier));
+    }
+
+    public void NOTEBOOK_NOT_FOUND(String externalIdentifier) throws IOException {
+        this.sendMessage(this._NOTEBOOK_NOT_FOUND(externalIdentifier));
+    }
+
+    public void TARGET_NOT_FOUND(String externalIdentifier) throws IOException {
+        this.sendMessage(this._TARGET_NOT_FOUND(externalIdentifier));
+    }
+
+    public void CACHED_REPRESENTATION_NOT_FOUND(String externalIdentifier) throws IOException {
+        this.sendMessage(this._CACHED_REPRESENTATION_NOT_FOUND(externalIdentifier));
+    }
+
+    public void INVALID_PERMISSION_MODE(String permissionMode) throws IOException {
+        this.sendMessage(this._INVALID_PERMISSION_MODE(permissionMode));
+    }
+
+    public void IDENTIFIER_MISMATCH(String externalIdentifier) throws IOException {
+        this.sendMessage(this._IDENTIFIER_MISMATCH(externalIdentifier));
+    }
+
+    public void ADMIN_RIGHTS_EXPECTED(String adminName, String adminEmail) throws IOException {
+        this.sendMessage(this._ADMIN_RIGHTS_EXPECTED(adminName, adminEmail));
+    }
+
+    public void DEVELOPER_RIGHTS_EXPECTED() throws IOException {
+        this.sendMessage(this._DEVELOPER_RIGHTS_EXPECTED());
+    }
+
+    public void PRINCIPAL_NOT_FOUND_BY_INFO(String email) throws IOException {
+        this.sendMessage(this._PRINCIPAL_NOT_FOUND_BY_INFO(email));
+    }
+
+    public void PRINCIPAL_IS_NOT_ADDED_TO_DB() throws IOException {
+        this.sendMessage(this._PRINCIPAL_IS_NOT_ADDED_TO_DB());
+    }
+
+    public void ACCOUNT_IS_NOT_UPDATED() throws IOException {
+        this.sendMessage(this._ACCOUNT_IS_NOT_UPDATED());
+    }
+    
+    public void LOGOUT() throws IOException {
+        this.sendMessage(this._LOGOUT());
+    }
+}
Index: /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/resources/catalog.cat
===================================================================
--- /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/resources/catalog.cat	(revision 4603)
+++ /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/resources/catalog.cat	(revision 4603)
@@ -0,0 +1,1 @@
+REWRITE_SYSTEM "http://www.w3.org/2005/08/" "."
Index: /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/resources/log4j.xml
===================================================================
--- /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/resources/log4j.xml	(revision 4603)
+++ /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/resources/log4j.xml	(revision 4603)
@@ -0,0 +1,111 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+Copyright (C) 2013 DASISH
+
+This program is free software; you can redistribute it and/or
+modify it under the terms of the GNU General Public License
+as published by the Free Software Foundation; either version 2
+of the License, or (at your option) any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
+-->
+<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
+<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
+    
+    <appender class="org.apache.log4j.DailyRollingFileAppender" name="ROOT">
+        <param value="${catalina.base}/logs/dasishRoot.log" name="File"/>
+        <layout class="org.apache.log4j.PatternLayout">
+            <param value="%d %p [%c#%M:%L] - %m%n" name="ConversionPattern"/>
+        </layout>
+    </appender>
+    
+    <appender class="org.apache.log4j.DailyRollingFileAppender" name="DATABASE">
+        <param value="${catalina.base}/logs/dasishDatabase.log" name="File"/>
+        <layout class="org.apache.log4j.PatternLayout">
+            <param value="%d %p [%c#%M:%L] - %m%n" name="ConversionPattern"/>
+        </layout>
+    </appender>
+    
+    <appender class="org.apache.log4j.DailyRollingFileAppender" name="SERVER">
+        <param value="${catalina.base}/logs/dasishServer.log" name="File"/>
+        <layout class="org.apache.log4j.PatternLayout">
+            <param value="%d %p [%c#%M:%L] - %m%n" name="ConversionPattern"/>
+        </layout>
+    </appender>
+    
+  
+    <logger name="eu.dasish.annotation.backend.rest.AnnotationResource"  additivity="false">
+        <level value="debug"/>
+        <appender-ref ref="DATABASE"/>
+    </logger>
+    <logger name="eu.dasish.annotation.backend.rest.TargetResource" additivity="false">
+        <level value="debug"/>
+        <appender-ref ref="DATABASE"/>
+    </logger>
+    <logger name="eu.dasish.annotation.backend.rest.UserResource" additivity="false">
+        <level value="debug"/>
+        <appender-ref ref="DATABASE"/>
+    </logger>
+    <logger name="eu.dasish.annotation.backend.rest.CachedRepresentationResource" additivity="false">
+        <level value="debug"/>
+        <appender-ref ref="DATABASE"/>
+    </logger>
+    <logger name="eu.dasish.annotation.backend.rest.DebugResource" additivity="false">
+        <level value="debug"/>
+        <appender-ref ref="DATABASE"/>
+    </logger>
+   
+     <logger name="eu.dasish.annotation.backend.dao.impl.JdbcResourceDao" additivity="false">
+        <level value="debug"/>
+        <appender-ref ref="DATABASE"/>
+    </logger>
+    
+    <logger name="eu.dasish.annotation.backend.dao.impl.JdbcAnnotationDao" additivity="false">
+        <level value="debug"/>
+        <appender-ref ref="DATABASE"/>
+    </logger>
+    
+     <logger name="eu.dasish.annotation.backend.dao.impl.JdbcTargetDao" additivity="false">
+        <level value="debug"/>
+        <appender-ref ref="DATABASE"/>
+    </logger>
+    
+     <logger name="eu.dasish.annotation.backend.dao.impl.JdbcUserDao" additivity="false">
+        <level value="debug"/>
+        <appender-ref ref="DATABASE"/>
+    </logger>
+    
+     <logger name="eu.dasish.annotation.backend.dao.impl.JdbcCachedRepresentationDao" additivity="false">
+        <level value="debug"/>
+        <appender-ref ref="DATABASE"/>
+    </logger>
+    
+    <logger name="javax.servlet.http.HttpServletResponse" additivity="false">
+        <level value="debug"/>
+        <appender-ref ref="SERVER"/>
+        <appender-ref ref="DATABASE"/>
+    </logger>
+    
+    
+    <logger name="org.springframework">
+        <level value="off"/>
+        <appender-ref ref="SERVER"/>
+        <appender-ref ref="DATABASE"/>
+    </logger>
+
+    
+    <root>
+        <level value="info"/>
+        <appender-ref ref="ROOT"/>  
+        <appender-ref ref="SERVER"/> 
+        <appender-ref ref="DATABASE"/> 
+    </root>
+    
+</log4j:configuration>
Index: /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/resources/spring-config/annotationDao.xml
===================================================================
--- /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/resources/spring-config/annotationDao.xml	(revision 4603)
+++ /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/resources/spring-config/annotationDao.xml	(revision 4603)
@@ -0,0 +1,29 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+
+    Copyright (C) 2013 DASISH
+
+    This program is free software; you can redistribute it and/or
+    modify it under the terms of the GNU General Public License
+    as published by the Free Software Foundation; either version 2
+    of the License, or (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License
+    along with this program; if not, write to the Free Software
+    Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+-->
+<beans xmlns="http://www.springframework.org/schema/beans"
+       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+
+       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
+">
+    <bean class="eu.dasish.annotation.backend.dao.impl.JdbcAnnotationDao">
+        <constructor-arg ref="dataSource"/>
+    </bean>
+</beans>
Index: /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/resources/spring-config/cachedRepresentationDao.xml
===================================================================
--- /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/resources/spring-config/cachedRepresentationDao.xml	(revision 4603)
+++ /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/resources/spring-config/cachedRepresentationDao.xml	(revision 4603)
@@ -0,0 +1,28 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+
+    Copyright (C) 2013 DASISH
+
+    This program is free software; you can redistribute it and/or
+    modify it under the terms of the GNU General Public License
+    as published by the Free Software Foundation; either version 2
+    of the License, or (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License
+    along with this program; if not, write to the Free Software
+    Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+-->
+<beans xmlns="http://www.springframework.org/schema/beans"
+       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
+">
+<bean class="eu.dasish.annotation.backend.dao.impl.JdbcCachedRepresentationDao">
+        <constructor-arg ref="dataSource"/>
+    </bean>
+</beans>
Index: /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/resources/spring-config/componentscan.xml
===================================================================
--- /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/resources/spring-config/componentscan.xml	(revision 4603)
+++ /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/resources/spring-config/componentscan.xml	(revision 4603)
@@ -0,0 +1,27 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+
+    Copyright (C) 2013 DASISH
+
+    This program is free software; you can redistribute it and/or
+    modify it under the terms of the GNU General Public License
+    as published by the Free Software Foundation; either version 2
+    of the License, or (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License
+    along with this program; if not, write to the Free Software
+    Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+-->
+<beans xmlns="http://www.springframework.org/schema/beans"
+       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+       xmlns:context="http://www.springframework.org/schema/context"
+       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
+          http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
+    <context:component-scan base-package="eu.dasish.annotation.backend.rest" />
+</beans>
Index: /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/resources/spring-config/dataSource.xml
===================================================================
--- /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/resources/spring-config/dataSource.xml	(revision 4603)
+++ /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/resources/spring-config/dataSource.xml	(revision 4603)
@@ -0,0 +1,32 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+
+    Copyright (C) 2013 DASISH
+
+    This program is free software; you can redistribute it and/or
+    modify it under the terms of the GNU General Public License
+    as published by the Free Software Foundation; either version 2
+    of the License, or (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License
+    along with this program; if not, write to the Free Software
+    Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+-->
+<beans xmlns="http://www.springframework.org/schema/beans"
+       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+       xmlns:context="http://www.springframework.org/schema/context"
+
+       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
+          http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
+">
+    <bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
+        <property name="jndiName" value="java:comp/env/jdbc/DASISHAnnotator"/>   
+        <property name="resourceRef" value="true" />
+    </bean>
+</beans>
Index: /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/resources/spring-config/dbIntegrityService.xml
===================================================================
--- /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/resources/spring-config/dbIntegrityService.xml	(revision 4603)
+++ /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/resources/spring-config/dbIntegrityService.xml	(revision 4603)
@@ -0,0 +1,28 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+
+    Copyright (C) 2013 DASISH
+
+    This program is free software; you can redistribute it and/or
+    modify it under the terms of the GNU General Public License
+    as published by the Free Software Foundation; either version 2
+    of the License, or (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License
+    along with this program; if not, write to the Free Software
+    Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+-->
+<beans xmlns="http://www.springframework.org/schema/beans"
+       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+
+       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
+">
+    <bean class="eu.dasish.annotation.backend.dao.impl.DBIntegrityServiceImlp">
+    </bean>
+</beans>
Index: /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/resources/spring-config/jaxbMarshallerFactory.xml
===================================================================
--- /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/resources/spring-config/jaxbMarshallerFactory.xml	(revision 4603)
+++ /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/resources/spring-config/jaxbMarshallerFactory.xml	(revision 4603)
@@ -0,0 +1,36 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+
+    Copyright (C) 2013 DASISH
+
+    This program is free software; you can redistribute it and/or
+    modify it under the terms of the GNU General Public License
+    as published by the Free Software Foundation; either version 2
+    of the License, or (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License
+    along with this program; if not, write to the Free Software
+    Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+-->
+<beans xmlns="http://www.springframework.org/schema/beans"
+       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+
+       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
+">
+    
+    <!-- Load properties from context.xml via servlet container -->
+    <bean
+        class="org.springframework.web.context.support.ServletContextPropertyPlaceholderConfigurer">
+        <property name="ignoreUnresolvablePlaceholders" value="true" />
+    </bean>
+    <bean id="jaxbMarshallerFactory" class="eu.dasish.annotation.backend.rest.JaxbMarshallerFactory">
+        <property name="schemaLocation"
+                 value="${eu.dasish.annotation.backend.schemaLocation}" />
+    </bean>
+</beans>
Index: /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/resources/spring-config/notebookDao.xml
===================================================================
--- /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/resources/spring-config/notebookDao.xml	(revision 4603)
+++ /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/resources/spring-config/notebookDao.xml	(revision 4603)
@@ -0,0 +1,29 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+
+    Copyright (C) 2013 DASISH
+
+    This program is free software; you can redistribute it and/or
+    modify it under the terms of the GNU General Public License
+    as published by the Free Software Foundation; either version 2
+    of the License, or (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License
+    along with this program; if not, write to the Free Software
+    Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+-->
+<beans xmlns="http://www.springframework.org/schema/beans"
+       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+
+       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
+">
+    <bean class="eu.dasish.annotation.backend.dao.impl.JdbcNotebookDao">
+        <constructor-arg ref="dataSource"/>
+    </bean>
+</beans>
Index: /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/resources/spring-config/targetDao.xml
===================================================================
--- /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/resources/spring-config/targetDao.xml	(revision 4603)
+++ /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/resources/spring-config/targetDao.xml	(revision 4603)
@@ -0,0 +1,29 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+
+    Copyright (C) 2013 DASISH
+
+    This program is free software; you can redistribute it and/or
+    modify it under the terms of the GNU General Public License
+    as published by the Free Software Foundation; either version 2
+    of the License, or (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License
+    along with this program; if not, write to the Free Software
+    Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+-->
+<beans xmlns="http://www.springframework.org/schema/beans"
+       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+
+       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
+">
+   <bean class="eu.dasish.annotation.backend.dao.impl.JdbcTargetDao">
+        <constructor-arg ref="dataSource"/>
+    </bean>
+</beans>
Index: /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/resources/spring-config/userDao.xml
===================================================================
--- /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/resources/spring-config/userDao.xml	(revision 4603)
+++ /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/resources/spring-config/userDao.xml	(revision 4603)
@@ -0,0 +1,29 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+
+    Copyright (C) 2013 DASISH
+
+    This program is free software; you can redistribute it and/or
+    modify it under the terms of the GNU General Public License
+    as published by the Free Software Foundation; either version 2
+    of the License, or (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License
+    along with this program; if not, write to the Free Software
+    Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+-->
+<beans xmlns="http://www.springframework.org/schema/beans"
+       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+
+       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
+">
+    <bean class="eu.dasish.annotation.backend.dao.impl.JdbcUserDao">
+        <constructor-arg ref="dataSource"/>
+    </bean>
+</beans>
Index: /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/resources/xml.xsd
===================================================================
--- /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/resources/xml.xsd	(revision 4603)
+++ /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/resources/xml.xsd	(revision 4603)
@@ -0,0 +1,146 @@
+<?xml version='1.0'?>
+<xs:schema targetNamespace="http://www.w3.org/XML/1998/namespace" xmlns:xs="http://www.w3.org/2001/XMLSchema" xml:lang="en">
+
+ <xs:annotation>
+  <xs:documentation>
+   See http://www.w3.org/XML/1998/namespace.html and
+   http://www.w3.org/TR/REC-xml for information about this namespace.
+
+    This schema document describes the XML namespace, in a form
+    suitable for import by other schema documents.  
+
+    Note that local names in this namespace are intended to be defined
+    only by the World Wide Web Consortium or its subgroups.  The
+    following names are currently defined in this namespace and should
+    not be used with conflicting semantics by any Working Group,
+    specification, or document instance:
+
+    base (as an attribute name): denotes an attribute whose value
+         provides a URI to be used as the base for interpreting any
+         relative URIs in the scope of the element on which it
+         appears; its value is inherited.  This name is reserved
+         by virtue of its definition in the XML Base specification.
+
+    id   (as an attribute name): denotes an attribute whose value
+         should be interpreted as if declared to be of type ID.
+         The xml:id specification is not yet a W3C Recommendation,
+         but this attribute is included here to facilitate experimentation
+         with the mechanisms it proposes.  Note that it is _not_ included
+         in the specialAttrs attribute group.
+
+    lang (as an attribute name): denotes an attribute whose value
+         is a language code for the natural language of the content of
+         any element; its value is inherited.  This name is reserved
+         by virtue of its definition in the XML specification.
+  
+    space (as an attribute name): denotes an attribute whose
+         value is a keyword indicating what whitespace processing
+         discipline is intended for the content of the element; its
+         value is inherited.  This name is reserved by virtue of its
+         definition in the XML specification.
+
+    Father (in any context at all): denotes Jon Bosak, the chair of 
+         the original XML Working Group.  This name is reserved by 
+         the following decision of the W3C XML Plenary and 
+         XML Coordination groups:
+
+             In appreciation for his vision, leadership and dedication
+             the W3C XML Plenary on this 10th day of February, 2000
+             reserves for Jon Bosak in perpetuity the XML name
+             xml:Father
+  </xs:documentation>
+ </xs:annotation>
+
+ <xs:annotation>
+  <xs:documentation>This schema defines attributes and an attribute group
+        suitable for use by
+        schemas wishing to allow xml:base, xml:lang, xml:space or xml:id
+        attributes on elements they define.
+
+        To enable this, such a schema must import this schema
+        for the XML namespace, e.g. as follows:
+        &lt;schema . . .>
+         . . .
+         &lt;import namespace="http://www.w3.org/XML/1998/namespace"
+                    schemaLocation="http://www.w3.org/2005/08/xml.xsd"/>
+
+        Subsequently, qualified reference to any of the attributes
+        or the group defined below will have the desired effect, e.g.
+
+        &lt;type . . .>
+         . . .
+         &lt;attributeGroup ref="xml:specialAttrs"/>
+ 
+         will define a type which will schema-validate an instance
+         element with any of those attributes</xs:documentation>
+ </xs:annotation>
+
+ <xs:annotation>
+  <xs:documentation>In keeping with the XML Schema WG's standard versioning
+   policy, this schema document will persist at
+   http://www.w3.org/2005/08/xml.xsd.
+   At the date of issue it can also be found at
+   http://www.w3.org/2001/xml.xsd.
+   The schema document at that URI may however change in the future,
+   in order to remain compatible with the latest version of XML Schema
+   itself, or with the XML namespace itself.  In other words, if the XML
+   Schema or XML namespaces change, the version of this document at
+   http://www.w3.org/2001/xml.xsd will change
+   accordingly; the version at
+   http://www.w3.org/2005/08/xml.xsd will not change.
+  </xs:documentation>
+ </xs:annotation>
+
+ <xs:attribute name="lang">
+  <xs:annotation>
+   <xs:documentation>Attempting to install the relevant ISO 2- and 3-letter
+         codes as the enumerated possible values is probably never
+         going to be a realistic possibility.  See
+         RFC 3066 at http://www.ietf.org/rfc/rfc3066.txt and the IANA registry
+         at http://www.iana.org/assignments/lang-tag-apps.htm for
+         further information.
+
+         The union allows for the 'un-declaration' of xml:lang with
+         the empty string.</xs:documentation>
+  </xs:annotation>
+  <xs:simpleType>
+   <xs:union memberTypes="xs:language">
+    <xs:simpleType>    
+     <xs:restriction base="xs:string">
+      <xs:enumeration value=""/>
+     </xs:restriction>
+    </xs:simpleType>
+   </xs:union>
+  </xs:simpleType>
+ </xs:attribute>
+
+ <xs:attribute name="space">
+  <xs:simpleType>
+   <xs:restriction base="xs:NCName">
+    <xs:enumeration value="default"/>
+    <xs:enumeration value="preserve"/>
+   </xs:restriction>
+  </xs:simpleType>
+ </xs:attribute>
+
+ <xs:attribute name="base" type="xs:anyURI">
+  <xs:annotation>
+   <xs:documentation>See http://www.w3.org/TR/xmlbase/ for
+                     information about this attribute.</xs:documentation>
+  </xs:annotation>
+ </xs:attribute>
+ 
+ <xs:attribute name="id" type="xs:ID">
+  <xs:annotation>
+   <xs:documentation>See http://www.w3.org/TR/xml-id/ for
+                     information about this attribute.</xs:documentation>
+  </xs:annotation>
+ </xs:attribute>
+
+ <xs:attributeGroup name="specialAttrs">
+  <xs:attribute ref="xml:base"/>
+  <xs:attribute ref="xml:lang"/>
+  <xs:attribute ref="xml:space"/>
+ </xs:attributeGroup>
+
+</xs:schema>
Index: /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/sql/DashishAnnotatorCreate.sql
===================================================================
--- /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/sql/DashishAnnotatorCreate.sql	(revision 4603)
+++ /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/sql/DashishAnnotatorCreate.sql	(revision 4603)
@@ -0,0 +1,162 @@
+--
+-- Copyright (C) 2013 DASISH
+--
+-- This program is free software; you can redistribute it and/or
+-- modify it under the terms of the GNU General Public License
+-- as published by the Free Software Foundation; either version 2
+-- of the License, or (at your option) any later version.
+--
+-- This program is distributed in the hope that it will be useful,
+-- but WITHOUT ANY WARRANTY; without even the implied warranty of
+-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+-- GNU General Public License for more details.
+--
+-- You should have received a copy of the GNU General Public License
+-- along with this program; if not, write to the Free Software
+-- Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+--
+
+--
+-- PostgreSQL database dump
+--
+
+-- Dumped from database version 9.2.4
+-- Dumped by pg_dump version 9.2.2
+-- Started on 2013-06-14 14:36:28 CEST
+
+SET client_encoding = 'UTF8';
+
+CREATE DATABASE "DASISHAnnotator" WITH TEMPLATE = template0 ENCODING = 'UTF8' LC_COLLATE = 'C' LC_CTYPE = 'C';
+
+
+\connect "DASISHAnnotator"
+
+SET client_encoding = 'UTF8';
+
+SET default_with_oids = false;
+
+SET TIME ZONE LOCAL;
+
+
+CREATE TABLE principal (
+    principal_id SERIAL UNIQUE NOT NULL,
+    external_id text UNIQUE NOT NULL,
+    remote_id text UNIQUE NOT NULL,
+    principal_name text,
+    e_mail text,
+    account text
+);
+
+CREATE TABLE notebook (
+    notebook_id SERIAL UNIQUE NOT NULL,
+    external_id text UNIQUE NOT NULL,
+    owner_id integer REFERENCES principal(principal_id),
+    last_modified timestamp default (current_timestamp AT TIME ZONE 'UTC'),
+    title text
+);
+
+
+CREATE TABLE annotation (
+    annotation_id SERIAL UNIQUE NOT NULL, 
+    external_id text UNIQUE NOT NULL,
+    owner_id integer REFERENCES principal(principal_id),
+    last_modified timestamp default (current_timestamp AT TIME ZONE 'UTC'),
+    headline text,
+    body_text text,
+    body_mimetype text,
+    is_xml BOOLEAN
+);
+
+
+
+CREATE TABLE target (
+    target_id SERIAL UNIQUE NOT NULL,
+    external_id text UNIQUE NOT NULL,
+    last_modified timestamp default (current_timestamp AT TIME ZONE 'UTC'),
+    link_uri text, 
+    version text,
+    fragment_descriptor text
+);
+
+CREATE TABLE cached_representation (
+    cached_representation_id SERIAL UNIQUE NOT NULL,
+    external_id text UNIQUE NOT NULL,
+    mime_type text,
+    tool text,
+    type_ text, 
+    file_ bytea 
+);
+
+
+
+CREATE TABLE permission_ (
+  permission_mode text UNIQUE NOT NULL
+);
+
+-----------------------------------------------------------------------
+--------------------- JOINT TABLES ------------------------------------
+
+CREATE TABLE annotations_targets (
+   annotation_id integer REFERENCES annotation(annotation_id), -- defining a foreign key: there must be a uniquely defined row in "annotation", that is defined by "annotation_id"
+   target_id integer REFERENCES target(target_id),
+   unique(annotation_id, target_id)
+);
+
+
+
+CREATE TABLE notebooks_annotations (
+    notebook_id integer REFERENCES notebook(notebook_id),
+    annotation_id integer REFERENCES annotation(annotation_id),
+    unique(notebook_id, annotation_id)
+);
+
+CREATE TABLE targets_cached_representations (
+    target_id integer REFERENCES target(target_id),
+    cached_representation_id integer REFERENCES cached_representation(cached_representation_id),
+    fragment_descriptor_in_cached text,
+    unique(target_id, cached_representation_id)
+);
+
+
+
+CREATE TABLE annotations_principals_permissions (
+annotation_id integer REFERENCES annotation(annotation_id),
+principal_id integer REFERENCES principal(principal_id),
+permission_  text REFERENCES permission_(permission_mode),
+unique(annotation_id, principal_id)
+);
+
+CREATE TABLE notebooks_principals_permissions (
+notebook_id integer REFERENCES notebook(notebook_id),
+principal_id integer REFERENCES principal(principal_id),
+permission_  text REFERENCES permission_(permission_mode),
+unique(notebook_id, principal_id)
+);
+
+
+---------------------------------------------------------------------------------------------
+-- ALTER TABLE ONLY annotation
+    -- ADD CONSTRAINT annotation_primary_key PRIMARY KEY (annotation_id);
+
+-- ALTER TABLE ONLY notebooks_annotations
+   -- ADD CONSTRAINT pk_notebooks_annotations PRIMARY KEY (notebook_id, annotation_id);
+
+
+-- ALTER TABLE ONLY annotation
+ -- ADD CONSTRAINT fk_annotation_owner_principal_id FOREIGN KEY (owner_id) REFERENCES principal(principal_id);
+
+-- ALTER TABLE ONLY notebook
+   -- ADD CONSTRAINT fk_notebook_owner_id_principal_id FOREIGN KEY (owner_id) REFERENCES principal(principal_id);
+
+ --ALTER TABLE ONLY notebooks_annotations
+ --   ADD CONSTRAINT fk_notebooks_annotations_annotation_id FOREIGN KEY (annotation_id) REFERENCES annotation(annotation_id);
+
+-- ALTER TABLE ONLY notebooks_annotations
+--     ADD CONSTRAINT fk_notebooks_annotations_notebook_id FOREIGN KEY (notebook_id) REFERENCES notebook(notebook_id);
+
+
+-- Completed on 2013-06-14 14:36:28 CEST
+
+--
+-- PostgreSQL database dump complete
+--
Index: /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/webapp/META-INF/context.xml
===================================================================
--- /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/webapp/META-INF/context.xml	(revision 4603)
+++ /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/webapp/META-INF/context.xml	(revision 4603)
@@ -0,0 +1,32 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+
+    Copyright (C) 2013 DASISH
+
+    This program is free software; you can redistribute it and/or
+    modify it under the terms of the GNU General Public License
+    as published by the Free Software Foundation; either version 2
+    of the License, or (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License
+    along with this program; if not, write to the Free Software
+    Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+-->
+<Context antiJARLocking="true" path="/annotator-backend">
+  <Resource auth="Container" 
+            driverClassName="org.postgresql.Driver" 
+            logAbandoned="true" maxActive="10" maxIdle="5" maxWait="4000" 
+            name="jdbc/DASISHAnnotator" 
+            password="dasish" 
+            removeAbandoned="false" 
+            removeAbandonedTimeout="10" 
+            type="javax.sql.DataSource" 
+            url="jdbc:postgresql:annotator" 
+            username="dasish"/>
+</Context>
Index: /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/webapp/WEB-INF/shhaa.xml
===================================================================
--- /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/webapp/WEB-INF/shhaa.xml	(revision 4603)
+++ /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/webapp/WEB-INF/shhaa.xml	(revision 4603)
@@ -0,0 +1,61 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+
+    Copyright (C) 2013 DASISH
+
+    This program is free software; you can redistribute it and/or
+    modify it under the terms of the GNU General Public License
+    as published by the Free Software Foundation; either version 2
+    of the License, or (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License
+    along with this program; if not, write to the Free Software
+    Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+-->
+<ROOT>
+    <shhaa>
+
+        <authentication>
+            <shibheader>
+                <username>oid:eduPersonPrincipalName</username>
+                <username>mace:eduPersonPrincipalName</username>
+                <username>eduPersonPrincipalName</username>
+		
+                <username>oid:eduPersonTargetedID</username>
+                <username>mace:eduPersonTargetedID</username>
+                <username>eduPersonTargetedID</username>
+
+                <session>Shib-Session-ID</session>
+                <idp>Shib-Identity-Provider</idp>
+                <timestamp>Shib-Authentication-Instant</timestamp>
+            </shibheader>
+            <fallback>
+                <username>anonymous</username>
+            </fallback>
+            <sso action="lI">http://lux16.mpi.nl/Shibboleth.sso/Login</sso> 
+	    <slo action="lO">http://lux16.mpi.nl/Shibboleth.sso/Logout</slo> 
+        </authentication>
+	
+	
+        <!-- <composition action="rF">
+       	    <shibheader>
+              		<attribute>displayName</attribute>
+              		<attribute>commonName</attribute>
+       	    </shibheader>
+       	</composition> -->
+
+	
+        <authorization>
+            <location  target="/api/authenticate/login/*" />
+        </authorization>
+	
+	
+	
+    </shhaa>
+</ROOT>
Index: /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/webapp/WEB-INF/web-shib.xml
===================================================================
--- /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/webapp/WEB-INF/web-shib.xml	(revision 4603)
+++ /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/webapp/WEB-INF/web-shib.xml	(revision 4603)
@@ -0,0 +1,87 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+
+    Copyright (C) 2013 DASISH
+
+    This program is free software; you can redistribute it and/or
+    modify it under the terms of the GNU General Public License
+    as published by the Free Software Foundation; either version 2
+    of the License, or (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License
+    along with this program; if not, write to the Free Software
+    Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+-->
+<!-- This web.xml file is not required when using Servlet 3.0 container, 
+see implementation details http://jersey.java.net/nonav/documentation/latest/jax-rs.html#d4e194 -->
+<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
+    
+    <context-param>
+        <param-name>ShhaaConfigLocation</param-name>
+        <param-value>/WEB-INF/shhaa.xml</param-value>
+    </context-param>
+    
+    <context-param>
+        <param-name>contextConfigLocation</param-name>
+        <param-value>classpath*:spring-config/**/*.xml</param-value>
+    </context-param>
+    <context-param>
+        <param-name>eu.dasish.annotation.backend.schemaLocation</param-name>
+        <param-value>http://www.dasish.eu/ns/addit https://svn.clarin.eu/DASISH/t5.6/schema/trunk/annotator-schema/src/main/resources/DASISH-schema.xsd</param-value>
+    </context-param>
+     <context-param>
+        <param-name>eu.dasish.annotation.backend.logDatabaseLocation</param-name>
+        <param-value>${catalina.base}/logs/dasishDatabase.log</param-value>
+    </context-param>
+    <context-param>
+        <param-name>eu.dasish.annotation.backend.logServerLocation</param-name>
+        <param-value>${catalina.base}/logs/dasishServer.log</param-value>
+    </context-param>
+    
+    
+    <listener>
+        <listener-class>
+            org.springframework.web.context.ContextLoaderListener
+        </listener-class>
+    </listener>
+    <servlet>
+        <servlet-name>annotator-backend</servlet-name>
+        <servlet-class>
+            com.sun.jersey.spi.spring.container.servlet.SpringServlet
+        </servlet-class>
+        <init-param>
+            <param-name>com.sun.jersey.config.property.packages</param-name>
+            <param-value>eu.dasish.annotation.backend</param-value>
+        </init-param>
+        <load-on-startup>1</load-on-startup>
+    </servlet>
+    <servlet>
+        <servlet-name>ServletAdaptor</servlet-name>
+        <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
+        <load-on-startup>1</load-on-startup>
+    </servlet>
+    <servlet-mapping>
+        <servlet-name>annotator-backend</servlet-name>
+        <url-pattern>/api/*</url-pattern>
+    </servlet-mapping>
+    
+    <servlet-mapping>
+        <servlet-name>ServletAdaptor</servlet-name>
+        <url-pattern>/webresources/*</url-pattern>
+    </servlet-mapping>
+    
+   <filter>
+        <filter-name>AAIFilter</filter-name>
+        <filter-class>de.mpg.aai.shhaa.AuthFilter</filter-class>
+    </filter>
+    <filter-mapping>
+        <filter-name>AAIFilter</filter-name>
+        <url-pattern>/*</url-pattern>
+    </filter-mapping> 
+</web-app>
Index: /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/webapp/WEB-INF/web.xml
===================================================================
--- /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/webapp/WEB-INF/web.xml	(revision 4603)
+++ /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/webapp/WEB-INF/web.xml	(revision 4603)
@@ -0,0 +1,112 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+
+    Copyright (C) 2013 DASISH
+
+    This program is free software; you can redistribute it and/or
+    modify it under the terms of the GNU General Public License
+    as published by the Free Software Foundation; either version 2
+    of the License, or (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License
+    along with this program; if not, write to the Free Software
+    Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+-->
+<!-- This web.xml file is not required when using Servlet 3.0 container, 
+see implementation details http://jersey.java.net/nonav/documentation/latest/jax-rs.html#d4e194 -->
+<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
+    <context-param>
+        <param-name>ShhaaConfigLocation</param-name>
+        <param-value>/WEB-INF/shhaa.xml</param-value>
+    </context-param>
+    
+    
+    <context-param>
+        <param-name>contextConfigLocation</param-name>
+        <param-value>classpath*:spring-config/**/*.xml</param-value>
+    </context-param>
+    <context-param>
+        <param-name>eu.dasish.annotation.backend.schemaLocation</param-name>
+        <param-value>http://www.dasish.eu/ns/addit https://svn.clarin.eu/DASISH/t5.6/schema/trunk/annotator-schema/src/main/resources/DASISH-schema.xsd</param-value>
+    </context-param>
+    <context-param>
+        <param-name>eu.dasish.annotation.backend.logDatabaseLocation</param-name>
+        <param-value>${catalina.base}/logs/dasishDatabase.log</param-value>
+    </context-param>
+    <context-param>
+        <param-name>eu.dasish.annotation.backend.logServerLocation</param-name>
+        <param-value>${catalina.base}/logs/dasishServer.log</param-value>
+    </context-param>
+    
+    <listener>
+        <listener-class>
+            org.springframework.web.context.ContextLoaderListener
+        </listener-class>
+    </listener>
+    <servlet>
+        <servlet-name>annotator-backend</servlet-name>
+        <servlet-class>
+            com.sun.jersey.spi.spring.container.servlet.SpringServlet
+        </servlet-class>
+        <init-param>
+            <param-name>com.sun.jersey.config.property.packages</param-name>
+            <param-value>eu.dasish.annotation.backend</param-value>
+        </init-param>
+        <load-on-startup>1</load-on-startup>
+    </servlet>
+    <servlet>
+        <servlet-name>ServletAdaptor</servlet-name>
+        <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
+        <load-on-startup>1</load-on-startup>
+    </servlet>
+    <servlet-mapping>
+        <servlet-name>annotator-backend</servlet-name>
+        <url-pattern>/api/*</url-pattern>
+    </servlet-mapping>
+    
+    <servlet-mapping>
+        <servlet-name>ServletAdaptor</servlet-name>
+        <url-pattern>/webresources/*</url-pattern>
+    </servlet-mapping>
+    
+    <security-constraint>
+        <display-name>Protected backend localhost</display-name>
+        <web-resource-collection>
+            <web-resource-name> Protected backend rest service</web-resource-name>
+            <description />
+            <url-pattern>/api/authentication/login</url-pattern> 
+            <http-method>GET</http-method>
+            <http-method>DELETE</http-method>
+            <http-method>PUT</http-method>
+            <http-method>POST</http-method>
+        </web-resource-collection>
+        <auth-constraint>
+            <role-name>tomcat</role-name>
+        </auth-constraint>
+    </security-constraint>
+    <login-config>
+        <auth-method>BASIC</auth-method>
+    </login-config>
+    <security-role>
+        <description> The role that is required to log in to the Application
+        </description>
+        <role-name>tomcat</role-name>
+    </security-role> 
+    
+<!--    <filter>
+        <filter-name>AAIFilter</filter-name>
+        <filter-class>de.mpg.aai.shhaa.AuthFilter</filter-class>
+    </filter>
+    <filter-mapping>
+        <filter-name>AAIFilter</filter-name>
+        <url-pattern>/api/annotations/login</url-pattern>
+    </filter-mapping> 
+    -->
+   
+</web-app>
Index: /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/webapp/index.jsp
===================================================================
--- /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/webapp/index.jsp	(revision 4603)
+++ /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/webapp/index.jsp	(revision 4603)
@@ -0,0 +1,55 @@
+<%--
+
+    Copyright (C) 2013 DASISH
+
+    This program is free software; you can redistribute it and/or
+    modify it under the terms of the GNU General Public License
+    as published by the Free Software Foundation; either version 2
+    of the License, or (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License
+    along with this program; if not, write to the Free Software
+    Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+--%>
+<html>
+    <body>
+        <h2>DASISH REST API</h2>
+        <p><a href="api/myresource">Jersey resource</a>
+        <p><a href="https://trac.clarin.eu/wiki/DASISH/SpecificationDocument#RESTAPI">https://trac.clarin.eu/wiki/DASISH/SpecificationDocument#RESTAPI</a></p>
+      
+        <br> 
+         <a href="api/authentication/login"> Login/check</a> <br> 
+         <br> 
+         <a href="api/authentication/logout"> Logout</a> <br> 
+        <br> 
+        <b>Test URI-s</b><br>
+        <b>All output xml-s are valid w.r.t. the schema</b><br>
+        GET <a href="api/users/00000000-0000-0000-0000-0000000000112">api/users/00000000-0000-0000-0000-0000000000112</a> <br> 
+        GET <a href="api/users/00000000-0000-0000-0000-0000000000112/current">api/users/00000000-0000-0000-0000-0000000000112/current</a>  !Problem: how to ask the servlet if the given user is logged in, may be by some other running somewhere client<br> 
+        GET <a href="api/users/info?email=Twan.Goosen@mpi.nl">api/users/info?email=Twan.Goosen@mpi.nl</a>  <br>
+        GET <a href="api/annotations?link=Sagrada">api/annotations/info?link=Sagrada</a>  <br>
+        GET <a href="api/annotations?link=Gaud">api/annotations/info?link=Gaud</a>  <br>
+        GET <a href="api/annotations?after=2014-02-04 15:57:58.046908&before=2014-02-06 10:08:16.213186">api/annotations?after=2014-02-04 15:57:58.046908&before=2014-02-06 10:08:16.213186</a> <br>
+        !Comment: What is "namespace" query parameter? Must be implemented and tested <br>
+        GET <a href="api/annotations/00000000-0000-0000-0000-000000000021">api/annotations/00000000-0000-0000-0000-000000000021</a>  </br>
+        GET <a href="api/annotations/00000000-0000-0000-0000-000000000021/targets">api/annotations/00000000-0000-0000-0000-000000000021/targets</a>  </br>
+        GET <a href="api/annotations/00000000-0000-0000-0000-000000000021/permissions">api/annotations/00000000-0000-0000-0000-000000000021/permissions</a><br>
+        GET <a href="api/targets/00000000-0000-0000-0000-000000000032">api/targets/00000000-0000-0000-0000-000000000032</a>  <br>
+        GET <a href="api/targets/00000000-0000-0000-0000-000000000032/versions">api/targets/00000000-0000-0000-0000-000000000032/versions</a>   <br>
+        GET <a href="api/cached/00000000-0000-0000-0000-000000000051/metadata">api/cached/00000000-0000-0000-0000-000000000051/metadata</a><br>
+        GET <a href="api/cached/00000000-0000-0000-0000-000000000051/content">api/cached/00000000-0000-0000-0000-000000000051/content</a> !Problem: works only on image.jpeg, end maps png-blobs to jpegs.
+        <br> 
+        <br>
+        <b>Debugging URI's (only for developers)</b><br>
+        GET <a href="api/debug/remoteID">api/debug/remoteID</a> <br>
+        GET <a href="api/debug/annotations">api/debug/annotations</a> <br>
+        GET <a href="api/debug/logDatabase/32">api/debug/logDatabase/32</a> <br>
+        GET <a href="api/debug/logServer/32">api/debug/logServer/32</a> <br>
+    </body>
+</html>
Index: /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/test/java/eu/dasish/annotation/backend/MockObjectsFactoryDao.java
===================================================================
--- /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/test/java/eu/dasish/annotation/backend/MockObjectsFactoryDao.java	(revision 4603)
+++ /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/test/java/eu/dasish/annotation/backend/MockObjectsFactoryDao.java	(revision 4603)
@@ -0,0 +1,62 @@
+/*
+ * Copyright (C) 2013 DASISH
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
+ */
+package eu.dasish.annotation.backend;
+
+import eu.dasish.annotation.backend.dao.AnnotationDao;
+import eu.dasish.annotation.backend.dao.CachedRepresentationDao;
+import eu.dasish.annotation.backend.dao.NotebookDao;
+import eu.dasish.annotation.backend.dao.TargetDao;
+import eu.dasish.annotation.backend.dao.UserDao;
+import org.jmock.Mockery;
+
+/**
+ * Created on : Jun 12, 2013, 2:05:25 PM
+ *
+ * @author Peter Withers <peter.withers@mpi.nl>
+ */
+public class MockObjectsFactoryDao {
+
+    private final Mockery context;
+
+    public MockObjectsFactoryDao(Mockery context) {
+        this.context = context;
+    }
+
+    public NotebookDao newNotebookDao() {
+        return context.mock(NotebookDao.class);
+    }
+
+    public AnnotationDao newAnnotationDao() {
+        return context.mock(AnnotationDao.class);
+    }
+    
+    public UserDao newUserDao() {
+        return context.mock(UserDao.class);
+    }
+    
+   
+    public TargetDao newTargetDao() {
+        return context.mock(TargetDao.class);
+    }
+    
+    public CachedRepresentationDao newCachedRepresentationDao() {
+        return context.mock(CachedRepresentationDao.class);
+    }
+ 
+  
+}
Index: /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/test/java/eu/dasish/annotation/backend/MockObjectsFactoryRest.java
===================================================================
--- /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/test/java/eu/dasish/annotation/backend/MockObjectsFactoryRest.java	(revision 4603)
+++ /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/test/java/eu/dasish/annotation/backend/MockObjectsFactoryRest.java	(revision 4603)
@@ -0,0 +1,62 @@
+/*
+ * Copyright (C) 2013 DASISH
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
+ */
+package eu.dasish.annotation.backend;
+
+import eu.dasish.annotation.backend.dao.DBIntegrityService;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import javax.ws.rs.core.UriInfo;
+import javax.ws.rs.ext.Providers;
+import org.jmock.Mockery;
+
+/**
+ * Created on : Jun 12, 2013, 2:05:25 PM
+ *
+ * @author Peter Withers <peter.withers@mpi.nl>
+ */
+public class MockObjectsFactoryRest {
+
+    private final Mockery context;
+
+    public MockObjectsFactoryRest(Mockery context) {
+        this.context = context;
+    }
+
+    
+    public DBIntegrityService newDBIntegrityService() {
+        return context.mock(DBIntegrityService.class);
+    }
+    
+    public UriInfo newUriInfo() {
+        return context.mock(UriInfo.class);
+    }
+   
+    
+     public Providers newProviders() {
+        return context.mock(Providers.class);
+    }
+   
+    public HttpServletRequest newHttpServletRequest() {
+        return context.mock(HttpServletRequest.class);
+    }
+    
+    public HttpServletResponse newHttpServletResponce() {
+        return context.mock(HttpServletResponse.class);
+    }
+   
+}
Index: /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/test/java/eu/dasish/annotation/backend/MyResourceTest.java
===================================================================
--- /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/test/java/eu/dasish/annotation/backend/MyResourceTest.java	(revision 4603)
+++ /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/test/java/eu/dasish/annotation/backend/MyResourceTest.java	(revision 4603)
@@ -0,0 +1,58 @@
+/**
+ * Copyright (C) 2013 DASISH
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ */
+/*
+ * To change this template, choose Tools | Templates
+ * and open the template in the editor.
+ */
+package eu.dasish.annotation.backend;
+
+import com.sun.jersey.api.client.ClientResponse;
+import com.sun.jersey.test.framework.JerseyTest;
+import com.sun.jersey.test.framework.WebAppDescriptor;
+import com.sun.jersey.test.framework.spi.container.TestContainerException;
+
+import org.junit.Test;
+import static org.junit.Assert.*;
+
+/**
+ *
+ * @author Peter Withers <peter.withers@mpi.nl>
+ */
+public class MyResourceTest extends JerseyTest {
+
+    public MyResourceTest() throws TestContainerException {
+        super(new WebAppDescriptor.Builder(MyResource.class.getPackage().getName())
+                // .servletClass(SpringServlet.class)
+                // .contextParam("contextConfigLocation", "classpath:testApplicationContext.xml")
+                // .contextListenerClass(ContextLoaderListener.class)
+                .build());
+    }
+
+    /**
+     * Test of getIt method, of class MyReTarget.
+     */
+    @Test
+    public void testGetIt() {
+        System.out.println("getIt");
+        ClientResponse response = resource().path("myresource").get(ClientResponse.class);
+        assertEquals(200, response.getStatus());
+        assertEquals("Hi there!", response.getEntity(String.class));
+//        final String hello = target("hello").request().get(String.class);
+//        assertEquals("Hello World!", hello);
+    }
+}
Index: /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/test/java/eu/dasish/annotation/backend/TestBackendConstants.java
===================================================================
--- /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/test/java/eu/dasish/annotation/backend/TestBackendConstants.java	(revision 4603)
+++ /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/test/java/eu/dasish/annotation/backend/TestBackendConstants.java	(revision 4603)
@@ -0,0 +1,34 @@
+/**
+ * Copyright (C) 2013 DASISH
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ */
+/*
+ * To change this template, choose Tools | Templates
+ * and open the template in the editor.
+ */
+
+package eu.dasish.annotation.backend;
+
+public class TestBackendConstants {
+    
+    public static final String _TEST_SERVLET_URI = "http://localhost:8080/annotator-backend/api/";
+    public static final String _TEST_SERVLET_URI_annotations = "http://localhost:8080/annotator-backend/api/annotations/";
+    public static final String _TEST_SERVLET_URI_Targets = "http://localhost:8080/annotator-backend/api/Targets/";
+    public static final String _TEST_SERVLET_URI_cached = "http://localhost:8080/annotator-backend/api/cached/";
+    public static final String _TEST_SERVLET_URI_users = "http://localhost:8080/annotator-backend/api/users/";
+    public static final String _TEST_SERVLET_URI_notebooks = "http://localhost:8080/annotator-backend/api/notebooks/";
+}
+
Index: /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/test/java/eu/dasish/annotation/backend/TestInstances.java
===================================================================
--- /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/test/java/eu/dasish/annotation/backend/TestInstances.java	(revision 4603)
+++ /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/test/java/eu/dasish/annotation/backend/TestInstances.java	(revision 4603)
@@ -0,0 +1,133 @@
+/**
+ * Copyright (C) 2013 DASISH
+ *
+ * This program is free software; you can redistribute it and/or modify it under
+ * the terms of the GNU General Public License as published by the Free Software
+ * Foundation; either version 2 of the License, or (at your option) any later
+ * version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+ * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
+ * details.
+ *
+ * You should have received a copy of the GNU General Public License along with
+ * this program; if not, write to the Free Software Foundation, Inc., 59 Temple
+ * Place - Suite 330, Boston, MA 02111-1307, USA.
+ */
+package eu.dasish.annotation.backend;
+
+import eu.dasish.annotation.schema.Annotation;
+import eu.dasish.annotation.schema.AnnotationBody;
+import eu.dasish.annotation.schema.AnnotationBody.TextBody;
+import eu.dasish.annotation.schema.Permission;
+import eu.dasish.annotation.schema.TargetInfo;
+import eu.dasish.annotation.schema.TargetInfoList;
+import eu.dasish.annotation.schema.UserWithPermission;
+import eu.dasish.annotation.schema.UserWithPermissionList;
+import javax.xml.datatype.DatatypeConfigurationException;
+import javax.xml.datatype.DatatypeFactory;
+
+/**
+ *
+ * @author olhsha
+ */
+public class TestInstances {
+
+    final private Annotation _annotationOne;
+    final private Annotation _annotationToAdd;
+
+    public TestInstances(String baseURI) {
+        _annotationOne = makeAnnotationOne(baseURI);
+        _annotationToAdd = makeAnnotationToAdd(baseURI);
+    }
+
+    private Annotation makeAnnotationOne(String baseURI) {
+        Annotation result = makeAnnotation(baseURI, "<html><body>some html 1</body></html>", "text/html", "Sagrada Famiglia", "00000000-0000-0000-0000-000000000111");
+
+        try {
+            result.setLastModified(DatatypeFactory.newInstance().newXMLGregorianCalendar("2013-08-12T09:25:00.383000Z"));
+        } catch (DatatypeConfigurationException dce) {
+            System.out.println("wrongly-formatted test timestamp " + "2013-08-12T09:25:00.383000Z");
+            result.setLastModified(null);
+        }
+        UserWithPermissionList upL = new UserWithPermissionList();
+        TargetInfoList targets = new TargetInfoList();
+        result.setPermissions(upL);
+        result.setTargets(targets);
+
+        UserWithPermission up1 = new UserWithPermission();
+        up1.setRef(baseURI + "users/00000000-0000-0000-0000-000000000112");
+        up1.setPermission(Permission.WRITER);
+
+        UserWithPermission up2 = new UserWithPermission();
+        up2.setRef(baseURI + "users/00000000-0000-0000-0000-000000000113");
+        up2.setPermission(Permission.READER);
+
+        upL.getUserWithPermission().add(up1);
+        upL.getUserWithPermission().add(up2);
+
+        TargetInfo target1 = new TargetInfo();
+        target1.setLink("http://nl.wikipedia.org/wiki/Sagrada_Fam%C3%ADlia");
+        target1.setRef(baseURI + "targets/00000000-0000-0000-0000-000000000031");
+        target1.setVersion("version 1.0");
+
+        TargetInfo target2 = new TargetInfo();
+        target2.setLink("http://nl.wikipedia.org/wiki/Antoni_Gaud%C3%AD");
+        target2.setRef(baseURI + "targets/00000000-0000-0000-0000-000000000032");
+        target2.setVersion("version 1.1");
+
+        targets.getTargetInfo().add(target1);
+        targets.getTargetInfo().add(target2);
+
+        return result;
+    }
+
+    private Annotation makeAnnotationToAdd(String baseURI) {
+        Annotation result = makeAnnotation(baseURI, "<html><body>some html 3</body></html>", "text/plain", "Annotation to add to test DAO", "00000000-0000-0000-0000-000000000113");
+
+        TargetInfo TargetInfo = new TargetInfo();
+        TargetInfo.setLink("http://nl.wikipedia.org/wiki/Sagrada_Fam%C3%ADlia");
+        TargetInfo.setRef(TestBackendConstants._TEST_SERVLET_URI_Targets + "00000000-0000-0000-0000-000000000031");
+        TargetInfo.setVersion("version 1.0");
+
+        TargetInfoList targetInfos = new TargetInfoList();
+        targetInfos.getTargetInfo().add(TargetInfo);
+        result.setTargets(targetInfos);
+
+        return result;
+    }
+
+    private Annotation makeAnnotation(String baseURI, String bodyTxt, String bodyMimeType, String headline, String ownerID) {
+        Annotation result = new Annotation();
+        AnnotationBody body = new AnnotationBody();
+        result.setBody(body);
+        TextBody textBody = new TextBody();
+        body.setTextBody(textBody);
+        textBody.setMimeType(bodyMimeType);
+        textBody.setBody(bodyTxt);
+
+        result.setHeadline(headline);
+
+        if (baseURI != null) {
+            result.setOwnerRef(baseURI + "users/" + ownerID);
+        } else {
+            result.setOwnerRef("users/" + ownerID);
+        }
+
+        result.setLastModified(null);
+        result.setURI(null);
+        result.setTargets(null);
+        result.setURI(null);
+
+        return result;
+    }
+
+    public Annotation getAnnotationOne() {
+        return _annotationOne;
+    }
+
+    public Annotation getAnnotationToAdd() {
+        return _annotationToAdd;
+    }
+}
Index: /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/test/java/eu/dasish/annotation/backend/dao/impl/DBIntegrityServiceTest.java
===================================================================
--- /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/test/java/eu/dasish/annotation/backend/dao/impl/DBIntegrityServiceTest.java	(revision 4603)
+++ /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/test/java/eu/dasish/annotation/backend/dao/impl/DBIntegrityServiceTest.java	(revision 4603)
@@ -0,0 +1,1349 @@
+/*
+ * Copyright (C) 2013 DASISH
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
+ */
+package eu.dasish.annotation.backend.dao.impl;
+
+import eu.dasish.annotation.backend.Resource;
+import eu.dasish.annotation.backend.TestBackendConstants;
+import eu.dasish.annotation.backend.TestInstances;
+import eu.dasish.annotation.backend.dao.AnnotationDao;
+import eu.dasish.annotation.backend.dao.CachedRepresentationDao;
+import eu.dasish.annotation.backend.dao.NotebookDao;
+import eu.dasish.annotation.backend.dao.TargetDao;
+import eu.dasish.annotation.backend.dao.UserDao;
+import eu.dasish.annotation.schema.Annotation;
+import eu.dasish.annotation.schema.AnnotationBody;
+import eu.dasish.annotation.schema.AnnotationBody.TextBody;
+import eu.dasish.annotation.schema.AnnotationInfo;
+import eu.dasish.annotation.schema.AnnotationInfoList;
+import eu.dasish.annotation.schema.CachedRepresentationInfo;
+import eu.dasish.annotation.schema.Notebook;
+import eu.dasish.annotation.schema.NotebookInfo;
+import eu.dasish.annotation.schema.NotebookInfoList;
+import eu.dasish.annotation.schema.Permission;
+import eu.dasish.annotation.schema.ReferenceList;
+import eu.dasish.annotation.schema.Target;
+import eu.dasish.annotation.schema.TargetInfo;
+import eu.dasish.annotation.schema.User;
+import eu.dasish.annotation.schema.UserWithPermission;
+import eu.dasish.annotation.schema.UserWithPermissionList;
+import java.io.ByteArrayInputStream;
+import java.sql.SQLException;
+import java.sql.Timestamp;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import javax.sql.rowset.serial.SerialException;
+import javax.xml.datatype.DatatypeConfigurationException;
+import javax.xml.datatype.DatatypeFactory;
+import javax.xml.datatype.XMLGregorianCalendar;
+import org.jmock.Expectations;
+import org.jmock.Mockery;
+import org.junit.Test;
+import static org.junit.Assert.*;
+import org.junit.runner.RunWith;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+
+/**
+ *
+ * @author olhsha
+ */
+@RunWith(SpringJUnit4ClassRunner.class)
+@ContextConfiguration({"/spring-test-config/dataSource.xml", "/spring-test-config/mockeryDao.xml", "/spring-test-config/mockAnnotationDao.xml",
+    "/spring-test-config/mockUserDao.xml", "/spring-test-config/mockTargetDao.xml", "/spring-test-config/mockCachedRepresentationDao.xml",
+    "/spring-test-config/mockNotebookDao.xml",
+    "/spring-config/dbIntegrityService.xml"})
+public class DBIntegrityServiceTest {
+
+    @Autowired
+    private DBIntegrityServiceImlp dbIntegrityService;
+    @Autowired
+    private Mockery mockeryDao;
+    @Autowired
+    private UserDao userDao;
+    @Autowired
+    private CachedRepresentationDao cachedRepresentationDao;
+    @Autowired
+    private TargetDao targetDao;
+    @Autowired
+    private AnnotationDao annotationDao;
+    @Autowired
+    private NotebookDao notebookDao;
+    TestInstances testInstances = new TestInstances(TestBackendConstants._TEST_SERVLET_URI);
+
+    public DBIntegrityServiceTest() {
+    }
+
+    ///////// GETTERS /////////////
+    /**
+     * Test of getAnnotationInternalIdentifier method, of class
+     * DBIntegrityServiceImlp.
+     */
+    @Test
+    public void testGetAnnotationInternalIdentifier() {
+        System.out.println("getAnnotationInternalIdentifier");
+        final UUID externalID = UUID.fromString("00000000-0000-0000-0000-000000000021");       
+        //dbIntegrityService.setResourceList();
+        mockeryDao.checking(new Expectations() {
+            {
+                oneOf(annotationDao).getInternalID(externalID);
+                will(returnValue(1));
+            }
+        });
+        assertEquals(1, dbIntegrityService.getResourceInternalIdentifier(externalID, Resource.ANNOTATION));
+    }
+
+    /**
+     * Test of getAnnotationExternalIdentifier method, of class
+     * DBIntegrityServiceImlp.
+     */
+    @Test
+    public void testGetAnnotationExternalIdentifier() {
+        System.out.println("getAnnotationExternalIdentifier");
+        final UUID externalID = UUID.fromString("00000000-0000-0000-0000-000000000021");
+
+        mockeryDao.checking(new Expectations() {
+            {
+                oneOf(annotationDao).getExternalID(1);
+                will(returnValue(externalID));
+            }
+        });
+        assertEquals("00000000-0000-0000-0000-000000000021", dbIntegrityService.getResourceExternalIdentifier(1, Resource.ANNOTATION).toString());
+    }
+
+    /**
+     * Test of getUserInternalIdentifier method, of class
+     * DBIntegrityServiceImlp.
+     */
+    @Test
+    public void testGetUserInternalIdentifier() {
+        System.out.println("getUserInternalIdentifier");
+
+        final UUID externalID = UUID.fromString("00000000-0000-0000-0000-000000000111");
+
+        mockeryDao.checking(new Expectations() {
+            {
+                oneOf(userDao).getInternalID(externalID);
+                will(returnValue(1));
+            }
+        });
+        assertEquals(1, dbIntegrityService.getResourceInternalIdentifier(externalID, Resource.PRINCIPAL));
+    }
+
+    /**
+     * Test of getUserExternalIdentifier method, of class
+     * DBIntegrityServiceImlp.
+     */
+    @Test
+    public void testGetUserExternalIdentifier() {
+        System.out.println("getUserExternalIdentifier");
+        final UUID externalID = UUID.fromString("00000000-0000-0000-0000-000000000111");
+
+        mockeryDao.checking(new Expectations() {
+            {
+                oneOf(userDao).getExternalID(1);
+                will(returnValue(externalID));
+            }
+        });
+        assertEquals("00000000-0000-0000-0000-000000000111", dbIntegrityService.getResourceExternalIdentifier(1, Resource.PRINCIPAL).toString());
+    }
+
+    /**
+     * Test of getAnnotation method, of class DBIntegrityServiceImlp.
+     */
+    @Test
+    public void testGetAnnotation() throws Exception {
+        System.out.println("test getAnnotation");
+
+        final Annotation mockAnnotation = new Annotation();// corresponds to the annotation # 1
+        mockAnnotation.setURI(TestBackendConstants._TEST_SERVLET_URI_annotations + "00000000-0000-0000-0000-000000000021");
+        mockAnnotation.setHeadline("Sagrada Famiglia");
+        XMLGregorianCalendar mockTimeStamp = DatatypeFactory.newInstance().newXMLGregorianCalendar("2013-08-12T09:25:00.383000Z");
+        mockAnnotation.setLastModified(mockTimeStamp);
+        mockAnnotation.setOwnerRef(TestBackendConstants._TEST_SERVLET_URI_annotations + "00000000-0000-0000-0000-000000000111");
+
+        AnnotationBody mockBody = new AnnotationBody();
+        TextBody textBody = new AnnotationBody.TextBody();
+        mockBody.setTextBody(textBody);
+        textBody.setMimeType("text/plain");
+        textBody.setBody("<html><body>some html 1</body></html>");
+        mockAnnotation.setBody(mockBody);
+        mockAnnotation.setTargets(null);
+
+
+        final List<Number> mockTargetIDs = new ArrayList<Number>();
+        mockTargetIDs.add(1);
+        mockTargetIDs.add(2);
+
+        final Target mockTargetOne = new Target();
+        mockTargetOne.setLink("http://nl.wikipedia.org/wiki/Sagrada_Fam%C3%ADlia");
+        mockTargetOne.setURI(TestBackendConstants._TEST_SERVLET_URI_Targets + "00000000-0000-0000-0000-000000000031");
+        mockTargetOne.setVersion("version 1.0");
+
+        final Target mockTargetTwo = new Target();
+        mockTargetTwo.setLink("http://nl.wikipedia.org/wiki/Antoni_Gaud%C3%AD");
+        mockTargetTwo.setURI(TestBackendConstants._TEST_SERVLET_URI_Targets + "00000000-0000-0000-0000-000000000032");
+        mockTargetTwo.setVersion("version 1.1");
+
+        final List<Map<Number, String>> listMap = new ArrayList<Map<Number, String>>();
+        Map<Number, String> map2 = new HashMap<Number, String>();
+        map2.put(2, "writer");
+        listMap.add(map2);
+        Map<Number, String> map3 = new HashMap<Number, String>();
+        map3.put(3, "reader");
+        listMap.add(map3);
+
+        final String uri1 = TestBackendConstants._TEST_SERVLET_URI_users + "00000000-0000-0000-0000-000000000111";
+        final String uri2 = TestBackendConstants._TEST_SERVLET_URI_users + "00000000-0000-0000-0000-000000000112";
+        final String uri3 = TestBackendConstants._TEST_SERVLET_URI_users + "00000000-0000-0000-0000-000000000113";
+
+
+        mockeryDao.checking(new Expectations() {
+            {
+                oneOf(annotationDao).getAnnotationWithoutTargetsAndPermissions(1);
+                will(returnValue(mockAnnotation));
+
+                oneOf(annotationDao).getOwner(1);
+                will(returnValue(1));
+
+                oneOf(userDao).getURIFromInternalID(1);
+                will(returnValue(uri1));
+
+                oneOf(targetDao).retrieveTargetIDs(1);
+                will(returnValue(mockTargetIDs));
+
+                oneOf(targetDao).getTarget(1);
+                will(returnValue(mockTargetOne));
+
+                oneOf(targetDao).getTarget(2);
+                will(returnValue(mockTargetTwo));
+
+                /// getPermissionsForAnnotation
+
+                oneOf(annotationDao).getPermissions(1);
+                will(returnValue(listMap));
+
+                oneOf(userDao).getURIFromInternalID(2);
+                will(returnValue(uri2));
+
+                oneOf(userDao).getURIFromInternalID(3);
+                will(returnValue(uri3));
+            }
+        });
+
+        Annotation result = dbIntegrityService.getAnnotation(1);
+        assertEquals(TestBackendConstants._TEST_SERVLET_URI_annotations + "00000000-0000-0000-0000-000000000021", result.getURI());
+        assertEquals("text/plain", result.getBody().getTextBody().getMimeType());
+        assertEquals("<html><body>some html 1</body></html>", result.getBody().getTextBody().getBody());
+        assertEquals("Sagrada Famiglia", result.getHeadline());
+        assertEquals("2013-08-12T09:25:00.383000Z", result.getLastModified().toString());
+        assertEquals(TestBackendConstants._TEST_SERVLET_URI_users + "00000000-0000-0000-0000-000000000111", result.getOwnerRef());
+
+        assertEquals(mockTargetOne.getLink(), result.getTargets().getTargetInfo().get(0).getLink());
+        assertEquals(mockTargetOne.getURI(), result.getTargets().getTargetInfo().get(0).getRef());
+        assertEquals(mockTargetOne.getVersion(), result.getTargets().getTargetInfo().get(0).getVersion());
+        assertEquals(mockTargetTwo.getLink(), result.getTargets().getTargetInfo().get(1).getLink());
+        assertEquals(mockTargetTwo.getURI(), result.getTargets().getTargetInfo().get(1).getRef());
+        assertEquals(mockTargetTwo.getVersion(), result.getTargets().getTargetInfo().get(1).getVersion());
+
+        assertEquals(Permission.WRITER, result.getPermissions().getUserWithPermission().get(0).getPermission());
+        assertEquals(uri2, result.getPermissions().getUserWithPermission().get(0).getRef());
+
+        assertEquals(Permission.READER, result.getPermissions().getUserWithPermission().get(1).getPermission());
+        assertEquals(uri3, result.getPermissions().getUserWithPermission().get(1).getRef());
+    }
+
+    /**
+     * Test of getFilteredAnnotationIDs method, of class DBIntegrityServiceImlp.
+     */
+    @Test
+    public void testGetFilteredAnnotationIDs() {
+        System.out.println("test getFilteredAnnotationIDs");
+
+        final List<Number> mockTargetIDs = new ArrayList<Number>();
+        mockTargetIDs.add(1);
+        mockTargetIDs.add(2);
+
+        final List<Number> mockAnnotationIDs1 = new ArrayList<Number>();
+        mockAnnotationIDs1.add(1);
+
+        final List<Number> mockAnnotationIDs2 = new ArrayList<Number>();
+        mockAnnotationIDs2.add(1);
+        mockAnnotationIDs2.add(2);
+
+        final String after = (new Timestamp(0)).toString();
+        final String before = (new Timestamp(System.currentTimeMillis())).toString();
+
+        final List<Number> mockRetval = new ArrayList<Number>();
+        mockRetval.add(1);
+
+
+        mockeryDao.checking(new Expectations() {
+            {
+                oneOf(targetDao).getTargetsReferringTo("nl.wikipedia.org");
+                will(returnValue(mockTargetIDs));
+
+                oneOf(annotationDao).getAnnotationIDsForTargets(mockTargetIDs);
+                will(returnValue(mockAnnotationIDs2));
+
+                oneOf(annotationDao).getFilteredAnnotationIDs(null, "some html 1", null, after, before);
+                will(returnValue(mockAnnotationIDs1));
+
+                oneOf(annotationDao).getAnnotationIDsForUserWithPermission(3, "reader");
+                will(returnValue(mockAnnotationIDs1));
+
+
+
+            }
+        });
+
+
+        List result = dbIntegrityService.getFilteredAnnotationIDs(null, "nl.wikipedia.org", "some html 1", 3, "reader", null, after, before);
+        assertEquals(1, result.size());
+        assertEquals(1, result.get(0));
+    }
+
+    @Test
+    public void testGetAnnotationTargets() throws SQLException {
+        System.out.println("test getAnnotationTargets");
+        final List<Number> TargetIDs = new ArrayList<Number>();
+        TargetIDs.add(1);
+        TargetIDs.add(2);
+        mockeryDao.checking(new Expectations() {
+            {
+                oneOf(targetDao).retrieveTargetIDs(1);
+                will(returnValue(TargetIDs));
+
+                oneOf(targetDao).getURIFromInternalID(1);
+                will(returnValue(TestBackendConstants._TEST_SERVLET_URI_Targets + "00000000-0000-0000-0000-000000000031"));
+
+                oneOf(targetDao).getURIFromInternalID(2);
+                will(returnValue(TestBackendConstants._TEST_SERVLET_URI_Targets + "00000000-0000-0000-0000-000000000032"));
+
+            }
+        });
+
+        ReferenceList result = dbIntegrityService.getAnnotationTargets(1);
+        assertEquals(2, result.getRef().size());
+        assertEquals(TestBackendConstants._TEST_SERVLET_URI_Targets + "00000000-0000-0000-0000-000000000031", result.getRef().get(0));
+        assertEquals(TestBackendConstants._TEST_SERVLET_URI_Targets + "00000000-0000-0000-0000-000000000032", result.getRef().get(1));
+
+    }
+
+//     @Override
+//    public AnnotationInfoList getFilteredAnnotationInfos(String link, String text, String access, String namespace, UUID
+//            owner, Timestamp after, Timestamp before){
+//        List<Number> annotationIDs = getFilteredAnnotationIDs(link, text, access, namespace, owner, after, before);
+//        List<AnnotationInfo> listAnnotationInfo = annotationDao.getAnnotationInfos(annotationIDs);
+    //       AnnotationInfoList result = new AnnotationInfoList();
+    //       result.getAnnotation().addAll(listAnnotationInfo);
+    //       return result;
+//    }
+    @Test
+    public void testGetFilteredAnnotationInfos() throws SQLException {
+        System.out.println("test getetFilteredAnnotationInfos");
+
+        final List<Number> mockTargetIDs = new ArrayList<Number>();
+        mockTargetIDs.add(1);
+        mockTargetIDs.add(2);
+
+        final List<Number> mockAnnotationIDs1 = new ArrayList<Number>();
+        mockAnnotationIDs1.add(1);
+
+        final List<Number> mockAnnotationIDs2 = new ArrayList<Number>();
+        mockAnnotationIDs2.add(1);
+        mockAnnotationIDs2.add(2);
+
+        final UUID ownerUUID = UUID.fromString("00000000-0000-0000-0000-000000000111");
+        final String after = (new Timestamp(0)).toString();
+        final String before = (new Timestamp(System.currentTimeMillis())).toString();
+
+        final List<Number> mockAnnotIDs = new ArrayList<Number>();
+        mockAnnotIDs.add(1);
+
+        final AnnotationInfo mockAnnotInfo = new AnnotationInfo();
+
+        mockAnnotInfo.setHeadline("Sagrada Famiglia");
+        mockAnnotInfo.setRef(TestBackendConstants._TEST_SERVLET_URI_annotations + "00000000-0000-0000-0000-000000000021");
+        mockAnnotInfo.setOwnerRef(TestBackendConstants._TEST_SERVLET_URI_users + "00000000-0000-0000-0000-000000000111");
+
+        final List<Number> targetIDs = new ArrayList<Number>();
+        targetIDs.add(1);
+        targetIDs.add(2);
+
+
+
+        mockeryDao.checking(new Expectations() {
+            {
+                oneOf(userDao).getInternalID(ownerUUID);
+                will(returnValue(1));
+
+                oneOf(targetDao).getTargetsReferringTo("nl.wikipedia.org");
+                will(returnValue(mockTargetIDs));
+
+                oneOf(annotationDao).getAnnotationIDsForTargets(mockTargetIDs);
+                will(returnValue(mockAnnotationIDs2));
+
+                oneOf(annotationDao).getFilteredAnnotationIDs(1, "some html 1", null, after, before);
+                will(returnValue(mockAnnotationIDs1));
+
+                oneOf(annotationDao).getAnnotationIDsForUserWithPermission(3, "reader");
+                will(returnValue(mockAnnotationIDs1));
+
+
+//                ///////////////////////////////////
+//                
+                oneOf(annotationDao).getAnnotationInfoWithoutTargets(1);
+                will(returnValue(mockAnnotInfo));
+
+                oneOf(annotationDao).getOwner(1);
+                will(returnValue(1));
+
+                oneOf(userDao).getURIFromInternalID(1);
+                will(returnValue(TestBackendConstants._TEST_SERVLET_URI_users + "00000000-0000-0000-0000-000000000111"));
+
+                ////
+                oneOf(targetDao).retrieveTargetIDs(1);
+                will(returnValue(targetIDs));
+
+                oneOf(targetDao).getURIFromInternalID(1);
+                will(returnValue(TestBackendConstants._TEST_SERVLET_URI_Targets + "00000000-0000-0000-0000-000000000031"));
+
+
+                oneOf(targetDao).getURIFromInternalID(2);
+                will(returnValue(TestBackendConstants._TEST_SERVLET_URI_Targets + "00000000-0000-0000-0000-000000000032"));
+
+
+            }
+        });
+
+
+        AnnotationInfoList result = dbIntegrityService.getFilteredAnnotationInfos(ownerUUID, "nl.wikipedia.org", "some html 1", 3, "reader", null, after, before);
+        assertEquals(1, result.getAnnotationInfo().size());
+        AnnotationInfo resultAnnotInfo = result.getAnnotationInfo().get(0);
+        assertEquals(mockAnnotInfo.getHeadline(), resultAnnotInfo.getHeadline());
+        assertEquals(mockAnnotInfo.getRef(), resultAnnotInfo.getRef());
+        assertEquals(mockAnnotInfo.getOwnerRef(), resultAnnotInfo.getOwnerRef());
+        assertEquals(mockAnnotInfo.getRef(), result.getAnnotationInfo().get(0).getRef());
+        assertEquals(TestBackendConstants._TEST_SERVLET_URI_Targets + "00000000-0000-0000-0000-000000000031", resultAnnotInfo.getTargets().getRef().get(0));
+        assertEquals(TestBackendConstants._TEST_SERVLET_URI_Targets + "00000000-0000-0000-0000-000000000032", resultAnnotInfo.getTargets().getRef().get(1));
+
+    }
+
+    @Test
+    public void testGetTargetsWithNoCachedRepresentation() {
+        System.out.println("test getTargetsWithNoCachedRepresentation");
+        final List<Number> targetIDs = new ArrayList<Number>();
+        targetIDs.add(5);
+        targetIDs.add(7);
+
+        final List<Number> cachedIDs5 = new ArrayList<Number>();
+        cachedIDs5.add(7);
+        final List<Number> cachedIDs7 = new ArrayList<Number>();
+
+
+
+        mockeryDao.checking(new Expectations() {
+            {
+                oneOf(targetDao).retrieveTargetIDs(3);
+                will(returnValue(targetIDs));
+
+                oneOf(cachedRepresentationDao).getCachedRepresentationsForTarget(5);
+                will(returnValue(cachedIDs5));
+
+                oneOf(cachedRepresentationDao).getCachedRepresentationsForTarget(7);
+                will(returnValue(cachedIDs7));
+
+                oneOf(targetDao).getURIFromInternalID(7);
+                will(returnValue("00000000-0000-0000-0000-000000000037"));
+
+            }
+        });
+
+        List<String> result = dbIntegrityService.getTargetsWithNoCachedRepresentation(3);
+        assertEquals(1, result.size());
+        assertEquals("00000000-0000-0000-0000-000000000037", result.get(0)); // Target number 7 has no cached
+    }
+
+    ////////////// ADDERS /////////////////////////
+    /**
+     * Test of addCachedForVersion method, of class DBIntegrityServiceImlp.
+     */
+    @Test
+    public void testAddCached() throws SerialException, SQLException {
+        System.out.println("addCached");
+        String mime = "text/html";
+        String type = "text";
+        String tool = "latex";
+        String externalID = UUID.randomUUID().toString();
+        final CachedRepresentationInfo newCachedInfo = new CachedRepresentationInfo();
+        newCachedInfo.setMimeType(mime);
+        newCachedInfo.setType(type);
+        newCachedInfo.setTool(tool);
+        newCachedInfo.setURI(TestBackendConstants._TEST_SERVLET_URI_cached + externalID);
+
+        String blobString = "aaa";
+        byte[] blobBytes = blobString.getBytes();
+        final ByteArrayInputStream newCachedBlob = new ByteArrayInputStream(blobBytes);
+
+        mockeryDao.checking(new Expectations() {
+            {
+
+                oneOf(cachedRepresentationDao).getInternalIDFromURI(newCachedInfo.getURI());
+                will(returnValue(null));
+
+                oneOf(cachedRepresentationDao).addCachedRepresentation(newCachedInfo, newCachedBlob);
+                will(returnValue(8));
+
+                one(targetDao).addTargetCachedRepresentation(1, 8, "#(1,2)");
+                will(returnValue(1));
+
+            }
+        });
+
+
+        Number[] result = dbIntegrityService.addCachedForTarget(1, "#(1,2)", newCachedInfo, newCachedBlob);
+        assertEquals(2, result.length);
+        assertEquals(1, result[0]);
+        assertEquals(8, result[1]);
+    }
+
+    /**
+     * Test of updateSiblingTargetClassForTarget method, of class
+     * DBIntegrityServiceImlp.
+     *
+     *
+     */
+    /**
+     * Test of addTargetsForAnnotation method, of class DBIntegrityServiceImlp.
+     */
+    @Test
+    public void testAddTargetsForAnnotation() throws Exception {
+        System.out.println("test addTargetsForAnnotation");
+
+        // test 1: adding an existing target
+        TargetInfo testTargetOne = new TargetInfo();
+        testTargetOne.setLink("http://nl.wikipedia.org/wiki/Sagrada_Fam%C3%ADlia");
+        testTargetOne.setRef(TestBackendConstants._TEST_SERVLET_URI_Targets + "00000000-0000-0000-0000-000000000031");
+        testTargetOne.setVersion("version 1.0");
+        final List<TargetInfo> mockTargetListOne = new ArrayList<TargetInfo>();
+        mockTargetListOne.add(testTargetOne);
+
+        mockeryDao.checking(new Expectations() {
+            {
+                oneOf(targetDao).getInternalIDFromURI(mockTargetListOne.get(0).getRef());
+                will(returnValue(1));
+
+                oneOf(annotationDao).addAnnotationTarget(4, 1);
+                will(returnValue(1));
+            }
+        });
+
+        Map<String, String> result = dbIntegrityService.addTargetsForAnnotation(4, mockTargetListOne);
+        assertEquals(0, result.size());
+
+        // test 2: adding a new Target
+        TargetInfo testTargetTwo = new TargetInfo();
+        final String tempTargetID = UUID.randomUUID().toString();
+        testTargetTwo.setRef(TestBackendConstants._TEST_SERVLET_URI_Targets + tempTargetID);
+        testTargetTwo.setLink("http://www.sagradafamilia.cat/docs_instit/historia.php");
+        testTargetTwo.setVersion("version 1.0");
+        final List<TargetInfo> mockTargetListTwo = new ArrayList<TargetInfo>();
+        mockTargetListTwo.add(testTargetTwo);
+
+        final UUID mockNewTargetUUID = UUID.randomUUID();
+
+        mockeryDao.checking(new Expectations() {
+            {
+                oneOf(targetDao).getInternalIDFromURI(mockTargetListTwo.get(0).getRef());
+                will(returnValue(null));
+
+                oneOf(targetDao).addTarget(with(aNonNull(Target.class)));
+                will(returnValue(8)); //# the next new number is 8, we have already 7 Targets
+
+                oneOf(targetDao).stringURItoExternalID(mockTargetListTwo.get(0).getRef());
+                will(returnValue(tempTargetID));
+
+                oneOf(targetDao).getExternalID(8);
+                will(returnValue(mockNewTargetUUID));
+
+                oneOf(annotationDao).addAnnotationTarget(1, 8);
+                will(returnValue(1));
+
+            }
+        });
+
+        Map<String, String> resultTwo = dbIntegrityService.addTargetsForAnnotation(1, mockTargetListTwo);
+        assertEquals(1, resultTwo.size());
+        assertEquals(mockNewTargetUUID.toString(), resultTwo.get(tempTargetID));
+
+    }
+
+    /**
+     * Test of addUsersAnnotation method, of class DBIntegrityServiceImlp.
+     */
+    @Test
+    public void testAddUsersAnnotation() throws Exception {
+        System.out.println("test addUsersAnnotation");
+
+        // expectations for addUsersannotation itself
+        final Annotation testAnnotation = testInstances.getAnnotationToAdd();
+
+        mockeryDao.checking(new Expectations() {
+            {
+                oneOf(annotationDao).addAnnotation(testAnnotation, 3);
+                will(returnValue(5)); // the next free number is 5
+
+                //  expectations for addTargetsForannotation
+                oneOf(targetDao).getInternalIDFromURI(TestBackendConstants._TEST_SERVLET_URI_Targets + "00000000-0000-0000-0000-000000000031");
+                will(returnValue(1));
+
+                oneOf(annotationDao).addAnnotationTarget(5, 1);
+                will(returnValue(1));
+
+                ///////////
+
+                oneOf(annotationDao).updateAnnotationBody(5, testAnnotation.getBody().getTextBody().getBody(), testAnnotation.getBody().getTextBody().getMimeType(), false);
+                will(returnValue(1)); // the DB update will be called at perform anyway, even if the body is not changed (can be optimized)
+
+
+            }
+        });
+
+        Number result = dbIntegrityService.addUsersAnnotation(3, testAnnotation);
+        assertEquals(5, result);
+    }
+
+    @Test
+    public void testAddUser() {
+        System.out.println("test addUser");
+        final User freshUser = new User();
+        freshUser.setDisplayName("Guilherme");
+        freshUser.setEMail("Guilherme.Silva@mpi.nl");
+        mockeryDao.checking(new Expectations() {
+            {
+                oneOf(userDao).userExists(freshUser);
+                will(returnValue(false));
+
+                oneOf(userDao).addUser(freshUser, "guisil@mpi.nl");
+                will(returnValue(11));
+            }
+        });
+
+
+        assertEquals(11, dbIntegrityService.addUser(freshUser, "guisil@mpi.nl").intValue());
+
+        /// user already exists
+        final User user = new User();
+        freshUser.setDisplayName("Olha");
+        freshUser.setEMail("Olha.Shakaravska@mpi.nl");
+        mockeryDao.checking(new Expectations() {
+            {
+                oneOf(userDao).userExists(user);
+                will(returnValue(true));
+
+            }
+        });
+
+        assertTrue(null == dbIntegrityService.addUser(user, "olhsha@mpi.nl"));
+    }
+
+    //////////////////// DELETERS ////////////////
+    @Test
+    public void testDeleteUser() {
+        System.out.println("test deleteUser");
+
+        mockeryDao.checking(new Expectations() {
+            {
+                oneOf(userDao).deleteUser(1);
+                will(returnValue(0));
+
+                oneOf(userDao).deleteUser(3);
+                will(returnValue(0));
+
+                oneOf(userDao).deleteUser(10);
+                will(returnValue(1));
+
+            }
+        });
+
+        assertEquals(0, dbIntegrityService.deleteUser(1));
+        assertEquals(0, dbIntegrityService.deleteUser(3));
+        assertEquals(1, dbIntegrityService.deleteUser(10));
+    }
+
+    /**
+     * Test of deleteCachedForVersion method, of class DBIntegrityServiceImlp.
+     */
+    @Test
+    public void testDeleteCachedRepresentationForTarget() throws SQLException {
+        System.out.println("test deleteCachedRepresentationForTarget");
+        mockeryDao.checking(new Expectations() {
+            {
+                oneOf(targetDao).deleteTargetCachedRepresentation(5, 7);
+                will(returnValue(1));
+
+                oneOf(cachedRepresentationDao).deleteCachedRepresentation(7);
+                will(returnValue(1)); // cached is used by another version
+
+            }
+        });
+
+        int[] result = dbIntegrityService.deleteCachedRepresentationOfTarget(5, 7);
+        assertEquals(2, result.length);
+        assertEquals(1, result[0]);
+        assertEquals(1, result[1]);
+    }
+
+    /////////////////////////////////////////////
+    @Test
+    public void testDeleteAllCachedRepresentationsOfTarget() throws SQLException {
+        System.out.println("test deleteAllCachedRepresentationsOfTarget");
+        final List<Number> cachedList = new ArrayList<Number>();
+        cachedList.add(1);
+        cachedList.add(2);
+
+        mockeryDao.checking(new Expectations() {
+            {
+                oneOf(cachedRepresentationDao).getCachedRepresentationsForTarget(1);
+                will(returnValue(cachedList));
+
+                oneOf(targetDao).deleteTargetCachedRepresentation(1, 1);
+                will(returnValue(1));
+
+                oneOf(cachedRepresentationDao).deleteCachedRepresentation(1);
+                will(returnValue(1));
+
+                oneOf(targetDao).deleteTargetCachedRepresentation(1, 2);
+                will(returnValue(1));
+
+                oneOf(cachedRepresentationDao).deleteCachedRepresentation(2);
+                will(returnValue(1));
+
+            }
+        });
+
+        int[] result = dbIntegrityService.deleteAllCachedRepresentationsOfTarget(1);
+        assertEquals(2, result[0]); // # affected rows in Targets_cacheds
+        assertEquals(2, result[1]); // # affected rows in cacheds 
+    }
+
+    /**
+     * Test of deleteAnnotationWithTargets method, of class
+     * DBIntegrityServiceImlp.
+     */
+    @Test
+    public void testDeleteAnnotation() throws Exception {
+        System.out.println("deleteAnnotation ");
+
+        // deleting annotation 3, which has its target Target 2  (used by annotation # 1)
+        final List<Number> mockTargetIDs = new ArrayList<Number>();
+        mockTargetIDs.add(2);
+
+        final List<Number> mockCachedIDs = new ArrayList<Number>();
+        mockCachedIDs.add(3);
+
+        mockeryDao.checking(new Expectations() {
+            {
+                oneOf(annotationDao).deleteAnnotationPrincipalPermissions(2);
+                will(returnValue(2));
+
+                oneOf(targetDao).retrieveTargetIDs(2);
+                will(returnValue(mockTargetIDs));
+
+                oneOf(annotationDao).deleteAllAnnotationTarget(2);
+                will(returnValue(1));
+
+                oneOf(annotationDao).deleteAnnotation(2);
+                will(returnValue(1));
+
+                oneOf(cachedRepresentationDao).getCachedRepresentationsForTarget(2);
+                will(returnValue(mockCachedIDs));
+
+                oneOf(targetDao).deleteTargetCachedRepresentation(2, 3);
+                will(returnValue(1));
+
+                oneOf(cachedRepresentationDao).deleteCachedRepresentation(3);
+                will(returnValue(1));
+                
+                oneOf(annotationDao).targetIsInUse(2);
+                will(returnValue(true));
+
+                oneOf(targetDao).deleteTarget(2);
+                will(returnValue(0));
+
+                oneOf(annotationDao).deleteAnnotationFromAllNotebooks(2);
+                will(returnValue(1));
+                
+                
+            }
+        });
+        int[] result = dbIntegrityService.deleteAnnotation(2);// the Target will be deleted because it is not referred by any annotation
+        assertEquals(5, result.length);
+        assertEquals(1, result[0]); // annotation 3 is deleted
+        assertEquals(2, result[1]); // 2 rows in "annotation principal permissions are deleted"
+        assertEquals(1, result[2]);  // row (3,2) in "annotations_Targets" is deleted
+        assertEquals(0, result[3]); //  target 2 is not deleted deleted since it is used by annotation 1
+        assertEquals(1, result[4]); // deleted from 1 notebook
+    }
+
+
+    /**
+     * NOTEBOOKS
+     */
+    /**
+     * Getters
+     */
+   
+//     public Number getNotebookInternalIdentifier(UUID externalIdentifier){
+//        return notebookDao.getInternalID(externalIdentifier);
+//    }
+    
+    @Test
+    public void testGetNotebookInternalIdentifier() {
+        
+        final UUID mockUUID = UUID.fromString("00000000-0000-0000-0000-000000000021");
+        
+        mockeryDao.checking(new Expectations() {
+            {
+                oneOf(notebookDao).getInternalID(mockUUID);
+                will(returnValue(1));
+            }
+        });
+
+       assertEquals(1, dbIntegrityService.getResourceInternalIdentifier(mockUUID, Resource.NOTEBOOK));
+    
+    }  
+       
+    
+    
+//    public NotebookInfoList getNotebooks(Number principalID, String permission) {
+//        NotebookInfoList result = new NotebookInfoList();
+//        if (permission.equalsIgnoreCase("reader") || permission.equalsIgnoreCase("writer")) {
+//            List<Number> notebookIDs = notebookDao.getNotebookIDs(principalID, Permission.fromValue(permission));
+//            for (Number notebookID : notebookIDs) {
+//                NotebookInfo notebookInfo = notebookDao.getNotebookInfoWithoutOwner(notebookID);
+//                Number ownerID = notebookDao.getOwner(notebookID);
+//                notebookInfo.setOwnerRef(userDao.getURIFromInternalID(ownerID));
+//                result.getNotebookInfo().add(notebookInfo);
+//            }
+//        } else {
+//            if (permission.equalsIgnoreCase("owner")) {
+//                List<Number> notebookIDs = notebookDao.getNotebookIDsOwnedBy(principalID);
+//                String ownerRef = userDao.getURIFromInternalID(principalID);
+//                for (Number notebookID : notebookIDs) {
+//                    NotebookInfo notebookInfo = notebookDao.getNotebookInfoWithoutOwner(notebookID);
+//                    notebookInfo.setOwnerRef(ownerRef);
+//                    result.getNotebookInfo().add(notebookInfo);
+//                }
+//            } else {
+//                return null;
+//            }
+//        }
+//        return result;
+//    }
+    @Test
+    public void testGetNotebooksReaderBranch() {
+
+        final List<Number> mockNotebookIDs = new ArrayList<Number>();
+        mockNotebookIDs.add(1);
+
+        final NotebookInfo mockNotebookInfo = new NotebookInfo();
+        mockNotebookInfo.setRef("00000000-0000-0000-0000-000000000011");
+        mockNotebookInfo.setTitle("Notebook 1");
+
+        mockeryDao.checking(new Expectations() {
+            {
+                oneOf(notebookDao).getNotebookIDs(3, Permission.READER);
+                will(returnValue(mockNotebookIDs));
+
+                oneOf(notebookDao).getNotebookInfoWithoutOwner(1);
+                will(returnValue(mockNotebookInfo));
+
+                oneOf(notebookDao).getOwner(1);
+                will(returnValue(1));
+
+                oneOf(userDao).getURIFromInternalID(1);
+                will(returnValue("00000000-0000-0000-0000-000000000111"));
+
+            }
+        });
+
+        NotebookInfoList result = dbIntegrityService.getNotebooks(3, "reader");
+        assertEquals("00000000-0000-0000-0000-000000000011", result.getNotebookInfo().get(0).getRef());
+        assertEquals("00000000-0000-0000-0000-000000000111", result.getNotebookInfo().get(0).getOwnerRef());
+        assertEquals("Notebook 1", result.getNotebookInfo().get(0).getTitle());
+
+    }
+
+    @Test
+    public void testGetNotebooksOwnerBranch() {
+
+        final List<Number> mockNotebookIDs = new ArrayList<Number>();
+        mockNotebookIDs.add(3);
+        mockNotebookIDs.add(4);
+
+        final NotebookInfo mockNotebookInfo1 = new NotebookInfo();
+        mockNotebookInfo1.setRef("00000000-0000-0000-0000-000000000013");
+        mockNotebookInfo1.setTitle("Notebook 3");
+
+        final NotebookInfo mockNotebookInfo2 = new NotebookInfo();
+        mockNotebookInfo2.setRef("00000000-0000-0000-0000-000000000014");
+        mockNotebookInfo2.setTitle("Notebook 4");
+
+        mockeryDao.checking(new Expectations() {
+            {
+                oneOf(notebookDao).getNotebookIDsOwnedBy(3);
+                will(returnValue(mockNotebookIDs));
+
+                oneOf(userDao).getURIFromInternalID(3);
+                will(returnValue("00000000-0000-0000-0000-000000000113"));
+
+                oneOf(notebookDao).getNotebookInfoWithoutOwner(3);
+                will(returnValue(mockNotebookInfo1));
+
+                oneOf(notebookDao).getNotebookInfoWithoutOwner(4);
+                will(returnValue(mockNotebookInfo2));
+
+            }
+        });
+
+        NotebookInfoList result = dbIntegrityService.getNotebooks(3, "owner");
+        assertEquals("00000000-0000-0000-0000-000000000013", result.getNotebookInfo().get(0).getRef());
+        assertEquals("00000000-0000-0000-0000-000000000113", result.getNotebookInfo().get(0).getOwnerRef());
+        assertEquals("Notebook 3", result.getNotebookInfo().get(0).getTitle());
+        assertEquals("00000000-0000-0000-0000-000000000014", result.getNotebookInfo().get(1).getRef());
+        assertEquals("00000000-0000-0000-0000-000000000113", result.getNotebookInfo().get(1).getOwnerRef());
+        assertEquals("Notebook 4", result.getNotebookInfo().get(1).getTitle());
+
+    }
+
+//    public ReferenceList getNotebooksOwnedBy(Number principalID) {
+//        ReferenceList result = new ReferenceList();
+//        List<Number> notebookIDs = notebookDao.getNotebookIDsOwnedBy(principalID);
+//        for (Number notebookID : notebookIDs) {
+//            String reference = notebookDao.getURIFromInternalID(notebookID);
+//            result.getRef().add(reference);
+//        }
+//        return result;
+//    }
+    @Test
+    public void testGetNotebooksOwnedBy() {
+
+        final List<Number> mockNotebookIDs = new ArrayList<Number>();
+        mockNotebookIDs.add(3);
+        mockNotebookIDs.add(4);
+
+        mockeryDao.checking(new Expectations() {
+            {
+                oneOf(notebookDao).getNotebookIDsOwnedBy(3);
+                will(returnValue(mockNotebookIDs));
+
+                oneOf(notebookDao).getURIFromInternalID(3);
+                will(returnValue(TestBackendConstants._TEST_SERVLET_URI_notebooks + "00000000-0000-0000-0000-000000000013"));
+
+                oneOf(notebookDao).getURIFromInternalID(4);
+                will(returnValue(TestBackendConstants._TEST_SERVLET_URI_notebooks + "00000000-0000-0000-0000-000000000014"));
+
+            }
+        });
+
+        ReferenceList result = dbIntegrityService.getNotebooksOwnedBy(3);
+        assertEquals(2, result.getRef().size());
+        assertEquals(TestBackendConstants._TEST_SERVLET_URI_notebooks + "00000000-0000-0000-0000-000000000013", result.getRef().get(0));
+        assertEquals(TestBackendConstants._TEST_SERVLET_URI_notebooks + "00000000-0000-0000-0000-000000000014", result.getRef().get(1));
+    }
+    
+ /*      public boolean hasAccess(Number notebookID, Number principalID, Permission permission){
+        List<Number> notebookIDs = notebookDao.getNotebookIDs(principalID, permission);
+        if (notebookIDs == null) {
+            return false;
+        } 
+        return notebookIDs.contains(notebookID);
+    } */
+    
+    @Test
+    public void testHasAccess() {
+
+        
+        final Permission writer = Permission.fromValue("writer"); 
+        final List<Number> mockNotebookIDwriter = new ArrayList<Number>();
+        mockNotebookIDwriter.add(1);
+        mockNotebookIDwriter.add(4);
+
+        mockeryDao.checking(new Expectations() {
+            {
+                oneOf(notebookDao).getNotebookIDs(2, writer);
+                will(returnValue(mockNotebookIDwriter));
+                
+                oneOf(notebookDao).getNotebookIDs(2, writer);
+                will(returnValue(mockNotebookIDwriter));
+
+            }
+        });
+
+        assertTrue(dbIntegrityService.hasAccess(4, 2, writer));
+        assertFalse(dbIntegrityService.hasAccess(5, 2, writer));
+    }
+    
+    /*
+     public ReferenceList getPrincipals(Number notebookID, String permission) {
+        ReferenceList result = new ReferenceList();
+        List<Number> principalIDs = notebookDao.getPrincipalIDsWithPermission(notebookID, Permission.fromValue(permission));
+        for (Number principalID : principalIDs) {
+            String reference = userDao.getURIFromInternalID(principalID);
+            result.getRef().add(reference);
+        }
+        return result;
+    }
+     }*/
+    @Test
+    public void testGetPrincipals() {
+        final List<Number> mockPrincipalIDs = new ArrayList<Number>();
+        mockPrincipalIDs.add(2);
+        mockPrincipalIDs.add(4);
+        
+        mockeryDao.checking(new Expectations() {
+            {
+                oneOf(userDao).getPrincipalIDsWithPermissionForNotebook(1, Permission.WRITER);
+                will(returnValue(mockPrincipalIDs));
+
+                oneOf(userDao).getURIFromInternalID(2);
+                will(returnValue("serviceURI/users/00000000-0000-0000-0000-000000000112"));
+
+                oneOf(userDao).getURIFromInternalID(4);
+                will(returnValue("serviceURI/users/00000000-0000-0000-0000-000000000114"));
+
+
+            }
+        });
+
+        ReferenceList result = dbIntegrityService.getPrincipals(1, "writer");
+        assertEquals("serviceURI/users/00000000-0000-0000-0000-000000000112", result.getRef().get(0).toString());
+        assertEquals("serviceURI/users/00000000-0000-0000-0000-000000000114", result.getRef().get(1).toString());
+
+    }
+
+//   @Override
+//    public Notebook getNotebook(Number notebookID) {
+//        Notebook result = notebookDao.getNotebookWithoutAnnotationsAndPermissionsAndOwner(notebookID);
+//
+//        result.setOwnerRef(userDao.getURIFromInternalID(notebookDao.getOwner(notebookID)));
+//
+//        ReferenceList annotations = new ReferenceList();
+//        List<Number> annotationIDs = notebookDao.getAnnotations(notebookID);
+//        for (Number annotationID : annotationIDs) {
+//            annotations.getRef().add(annotationDao.getURIFromInternalID(annotationID));
+//        }
+//        result.setAnnotations(annotations);
+//
+//        UserWithPermissionList ups = new UserWithPermissionList();
+//        List<Permission> permissions = new ArrayList<Permission>();
+//        permissions.add(Permission.READER);
+//        permissions.add(Permission.WRITER);
+//        for (Permission permission : permissions) {
+//            List<Number> users = notebookDao.getPrincipalIDsWithPermission(notebookID, permission);
+//            if (users != null) {
+//                for (Number user : users) {
+//                    UserWithPermission up = new UserWithPermission();
+//                    up.setRef(userDao.getURIFromInternalID(user));
+//                    up.setPermission(permission);
+//                    ups.getUserWithPermission().add(up);
+//                }
+//            }
+//        }
+//
+//        result.setPermissions(ups);
+//        return result;
+//    }
+
+
+    @Test
+    public void testGetNotebook() throws DatatypeConfigurationException{
+
+        final Notebook mockNotebook = new Notebook();
+        mockNotebook.setURI("serviceURI/notebooks/00000000-0000-0000-0000-000000000012");
+        mockNotebook.setTitle("Notebook 2");
+        mockNotebook.setLastModified(DatatypeFactory.newInstance().newXMLGregorianCalendar("2014-02-12T09:25:00.383000Z"));
+        
+        final List<Number> mockAnnotations = new ArrayList<Number>();
+        mockAnnotations.add(3);
+        
+        final List<Number> mockReaders = new ArrayList<Number>();
+        mockReaders.add(1);
+        
+        final List<Number> mockWriters = new ArrayList<Number>();
+        mockWriters.add(3);
+        
+        mockeryDao.checking(new Expectations() {
+            {
+                oneOf(notebookDao).getNotebookWithoutAnnotationsAndPermissionsAndOwner(2);
+                will(returnValue(mockNotebook));
+
+                oneOf(notebookDao).getOwner(2);
+                will(returnValue(2));
+
+                oneOf(userDao).getURIFromInternalID(2);
+                will(returnValue("serviceURI/users/00000000-0000-0000-0000-000000000112"));
+
+                oneOf(annotationDao).getAnnotations(2);
+                will(returnValue(mockAnnotations));
+                
+                oneOf(annotationDao).getURIFromInternalID(3);
+                will(returnValue("serviceURI/annotations/00000000-0000-0000-0000-000000000023"));
+                
+                oneOf(userDao).getPrincipalIDsWithPermissionForNotebook(2, Permission.READER);
+                will(returnValue(mockReaders));
+                
+                oneOf(userDao).getURIFromInternalID(1);
+                will(returnValue("serviceURI/users/00000000-0000-0000-0000-000000000111"));
+                
+                oneOf(userDao).getPrincipalIDsWithPermissionForNotebook(2, Permission.WRITER);
+                will(returnValue(mockWriters));
+                
+                oneOf(userDao).getURIFromInternalID(3);
+                will(returnValue("serviceURI/users/00000000-0000-0000-0000-000000000113"));
+
+                
+
+            }
+        });
+
+        Notebook result = dbIntegrityService.getNotebook(2);
+        assertEquals("serviceURI/notebooks/00000000-0000-0000-0000-000000000012", result.getURI());
+        assertEquals("serviceURI/users/00000000-0000-0000-0000-000000000112", result.getOwnerRef());
+        assertEquals("2014-02-12T09:25:00.383000Z", result.getLastModified().toString());
+        assertEquals("Notebook 2", result.getTitle());
+        assertEquals(1, result.getAnnotations().getRef().size());
+        assertEquals("serviceURI/annotations/00000000-0000-0000-0000-000000000023", result.getAnnotations().getRef().get(0));
+        assertEquals(2, result.getPermissions().getUserWithPermission().size());
+        assertEquals("serviceURI/users/00000000-0000-0000-0000-000000000111", result.getPermissions().getUserWithPermission().get(0).getRef());
+        assertEquals("reader", result.getPermissions().getUserWithPermission().get(0).getPermission().value());
+        assertEquals("serviceURI/users/00000000-0000-0000-0000-000000000113", result.getPermissions().getUserWithPermission().get(1).getRef());
+        assertEquals("writer", result.getPermissions().getUserWithPermission().get(1).getPermission().value());
+        
+    }
+
+    @Test
+    public void testAnnotationsForNotebook() {
+        final List<Number> mockAnnotationIDs = new ArrayList<Number>();
+        mockAnnotationIDs.add(1);
+        mockAnnotationIDs.add(2);
+
+        mockeryDao.checking(new Expectations() {
+            {
+                oneOf(annotationDao).getAnnotations(1);
+                will(returnValue(mockAnnotationIDs));
+
+                oneOf(annotationDao).sublistOrderedAnnotationIDs(mockAnnotationIDs, 0, 3, "last_modified", "DESC");
+                will(returnValue(mockAnnotationIDs));
+
+                oneOf(annotationDao).getURIFromInternalID(1);
+                will(returnValue("serviceURI/annotations/00000000-0000-0000-0000-000000000021"));
+
+                oneOf(annotationDao).getURIFromInternalID(2);
+                will(returnValue("serviceURI/annotations/00000000-0000-0000-0000-000000000022"));
+
+
+
+            }
+        });
+
+        ReferenceList result = dbIntegrityService.getAnnotationsForNotebook(1, -1, 3, "last_modified", true);
+        assertEquals(2, result.getRef().size());
+        assertEquals("serviceURI/annotations/00000000-0000-0000-0000-000000000021", result.getRef().get(0).toString());
+        assertEquals("serviceURI/annotations/00000000-0000-0000-0000-000000000022", result.getRef().get(1).toString());
+
+    }
+
+    /**
+     * Updaters
+     */
+//    public boolean updateNotebookMetadata(Number notebookID, NotebookInfo upToDateNotebookInfo) {
+//        Number ownerID = userDao.getInternalIDFromURI(upToDateNotebookInfo.getOwnerRef());
+//        return notebookDao.updateNotebookMetadata(notebookID, upToDateNotebookInfo.getTitle(), ownerID);
+//    }
+    @Test
+    public void testUpdateNotebookMetadata() {
+
+        final NotebookInfo mockNotebookInfo = new NotebookInfo();
+        mockNotebookInfo.setOwnerRef(TestBackendConstants._TEST_SERVLET_URI_users + "00000000-0000-0000-0000-000000000113");
+        mockNotebookInfo.setTitle("New Title");
+
+        mockeryDao.checking(new Expectations() {
+            {
+                oneOf(userDao).getInternalIDFromURI(TestBackendConstants._TEST_SERVLET_URI_users + "00000000-0000-0000-0000-000000000113");
+                will(returnValue(3));
+
+                oneOf(notebookDao).updateNotebookMetadata(1, "New Title", 3);
+                will(returnValue(true));
+            }
+        });
+
+        boolean result = dbIntegrityService.updateNotebookMetadata(1, mockNotebookInfo);
+        assertTrue(result);
+    }
+
+// 
+//    public boolean addAnnotationToNotebook(Number notebookID, Number annotationID) {
+//        return notebookDao.addAnnotationToNotebook(notebookID, annotationID);
+//    }
+    @Test
+    public void testAddAnnotationToNotebook() {
+
+        mockeryDao.checking(new Expectations() {
+            {
+
+                oneOf(notebookDao).addAnnotationToNotebook(1, 3);
+                will(returnValue(true));
+            }
+        });
+
+        assertTrue(dbIntegrityService.addAnnotationToNotebook(1, 3));
+    }
+
+    /**
+     * Adders
+     */
+//    public Number createNotebook(Notebook notebook, Number ownerID) {
+//        Number notebookID = notebookDao.createNotebookWithoutPermissionsAndAnnotations(notebook, ownerID);
+//        boolean updateOwner = notebookDao.setOwner(notebookID, ownerID);
+//        List<UserWithPermission> permissions = notebook.getPermissions().getUserWithPermission();
+//        for (UserWithPermission principalPermission : permissions) {
+//            Number principalID = userDao.getInternalIDFromURI(principalPermission.getRef());
+//            Permission permission = principalPermission.getPermission();
+//            boolean updatePermissions = notebookDao.addPermissionToNotebook(notebookID, principalID, permission);
+//        }
+//        return notebookID;
+//    }
+    @Test
+    public void testCreateNotebook() {
+
+        final Notebook notebook = new Notebook();
+        notebook.setOwnerRef("tmpXXX");
+        notebook.setTitle("(Almost) Copy of Notebook 1");
+        notebook.setURI("tmpYYY");
+
+        UserWithPermissionList permissions = new UserWithPermissionList();
+        UserWithPermission p1 = new UserWithPermission();
+        p1.setPermission(Permission.WRITER);
+        p1.setRef(TestBackendConstants._TEST_SERVLET_URI_users + "00000000-0000-0000-0000-000000000112");
+        permissions.getUserWithPermission().add(p1);
+        UserWithPermission p2 = new UserWithPermission();
+        p2.setPermission(Permission.READER);
+        p2.setRef(TestBackendConstants._TEST_SERVLET_URI_users + "00000000-0000-0000-0000-000000000113");
+        permissions.getUserWithPermission().add(p2);
+        notebook.setPermissions(permissions);
+
+        mockeryDao.checking(new Expectations() {
+            {
+                oneOf(notebookDao).createNotebookWithoutPermissionsAndAnnotations(notebook, 1);
+                will(returnValue(5));
+
+                oneOf(notebookDao).setOwner(5, 1);
+                will(returnValue(true));
+
+                oneOf(userDao).getInternalIDFromURI(TestBackendConstants._TEST_SERVLET_URI_users + "00000000-0000-0000-0000-000000000112");
+                will(returnValue(2));
+
+                oneOf(userDao).getInternalIDFromURI(TestBackendConstants._TEST_SERVLET_URI_users + "00000000-0000-0000-0000-000000000113");
+                will(returnValue(3));
+
+                oneOf(notebookDao).addPermissionToNotebook(5, 2, Permission.WRITER);
+                will(returnValue(true));
+
+                oneOf(notebookDao).addPermissionToNotebook(5, 3, Permission.READER);
+                will(returnValue(true));
+
+            }
+        });
+
+        Number result = dbIntegrityService.createNotebook(notebook, 1);
+        assertEquals(5, result);
+
+    }
+
+//    public boolean createAnnotationInNotebook(Number notebookID, Annotation annotation, Number ownerID) {
+//        Number newAnnotationID = this.addUsersAnnotation(ownerID, annotation);
+//        return notebookDao.addAnnotationToNotebook(notebookID, newAnnotationID);
+//    }
+    @Test
+    public void testCreateAnnotationInNotebook() {
+
+        final Annotation testAnnotation = testInstances.getAnnotationToAdd();
+
+        mockeryDao.checking(new Expectations() {
+            {
+                oneOf(annotationDao).addAnnotation(testAnnotation, 3);
+                will(returnValue(5)); // the next free number is 5
+
+                //  expectations for addTargetsForannotation
+                oneOf(targetDao).getInternalIDFromURI(TestBackendConstants._TEST_SERVLET_URI_Targets + "00000000-0000-0000-0000-000000000031");
+                will(returnValue(1));
+
+                oneOf(annotationDao).addAnnotationTarget(5, 1);
+                will(returnValue(1));
+
+                oneOf(annotationDao).updateAnnotationBody(5, testAnnotation.getBody().getTextBody().getBody(), testAnnotation.getBody().getTextBody().getMimeType(), false);
+                will(returnValue(1)); // the DB update will be called at perform anyway, even if the body is not changed (can be optimized)
+
+                /////////////////////////
+
+                oneOf(notebookDao).addAnnotationToNotebook(1, 5);
+                will(returnValue(true));
+            }
+        });
+
+        assertTrue(dbIntegrityService.createAnnotationInNotebook(1, testAnnotation, 3));
+
+    }
+
+    /**
+     * Deleters
+     */
+//      public boolean deleteNotebook(Number notebookID) {
+//        if (notebookDao.deleteAllPermissionsForNotebook(notebookID) || notebookDao.deleteAllAnnotationsFromNotebook(notebookID)) {
+//            return notebookDao.deleteNotebook(notebookID);
+//        } else {
+//            return false;
+//        }
+//   
+//   }
+    @Test
+    public void testDeleteNotebook() {
+
+        mockeryDao.checking(new Expectations() {
+            {
+
+                oneOf(notebookDao).deleteAllPermissionsForNotebook(1);
+                will(returnValue(true));
+
+                oneOf(notebookDao).deleteAllAnnotationsFromNotebook(1);
+                will(returnValue(true));
+
+                oneOf(notebookDao).deleteNotebook(1);
+                will(returnValue(true));
+            }
+        });
+
+        assertTrue(dbIntegrityService.deleteNotebook(1));
+    }
+}
Index: /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/test/java/eu/dasish/annotation/backend/dao/impl/JdbcAnnotationDaoTest.java
===================================================================
--- /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/test/java/eu/dasish/annotation/backend/dao/impl/JdbcAnnotationDaoTest.java	(revision 4603)
+++ /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/test/java/eu/dasish/annotation/backend/dao/impl/JdbcAnnotationDaoTest.java	(revision 4603)
@@ -0,0 +1,372 @@
+/*
+ * Copyright (C) 2013 DASISH
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
+ */
+package eu.dasish.annotation.backend.dao.impl;
+
+import eu.dasish.annotation.backend.TestBackendConstants;
+import eu.dasish.annotation.backend.TestInstances;
+import eu.dasish.annotation.schema.Annotation;
+import eu.dasish.annotation.schema.Permission;
+import java.sql.SQLException;
+import java.sql.Timestamp;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import javax.xml.datatype.DatatypeConfigurationException;
+import javax.xml.datatype.DatatypeFactory;
+import static org.junit.Assert.*;
+import org.junit.Ignore;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+
+/**
+ *
+ * @author olhsha
+ */
+@RunWith(SpringJUnit4ClassRunner.class)
+@ContextConfiguration({"/spring-test-config/dataSource.xml", "/spring-config/annotationDao.xml"})
+public class JdbcAnnotationDaoTest extends JdbcResourceDaoTest {
+
+    @Autowired
+    JdbcAnnotationDao jdbcAnnotationDao;    
+    TestInstances testInstances = new TestInstances(TestBackendConstants._TEST_SERVLET_URI);
+    
+     /**
+     * Test of stringURItoExternalID method
+     * public String stringURItoExternalID(String uri);
+     */
+    @Test
+    public void testStringURItoExternalID() {
+        System.out.println("test stringURItoExternalID");
+        jdbcAnnotationDao.setServiceURI(TestBackendConstants._TEST_SERVLET_URI_annotations);
+        String randomUUID = UUID.randomUUID().toString();
+        String uri = TestBackendConstants._TEST_SERVLET_URI_annotations + randomUUID;
+        String externalID = jdbcAnnotationDao.stringURItoExternalID(uri);
+        assertEquals(randomUUID, externalID);
+    }
+    
+    /**
+     * Test of externalIDtoURI method
+     * public String externalIDtoURI(String externalID);
+     */
+    @Test
+    public void testExternalIDtoURI() {
+        System.out.println("test stringURItoExternalID");
+        jdbcAnnotationDao.setServiceURI(TestBackendConstants._TEST_SERVLET_URI_annotations);
+        String randomUUID = UUID.randomUUID().toString();
+        String uri = TestBackendConstants._TEST_SERVLET_URI_annotations+randomUUID;
+        String uriResult = jdbcAnnotationDao.externalIDtoURI(randomUUID);
+        assertEquals(uri, uriResult);
+    }
+
+     /**
+     * Test of retrieveTargetIDs method, of class JdbcAnnotationDao.
+     */
+ 
+    
+     /**
+     * Test of getAnnotations method, of class JdbcNotebookDao.
+     */
+    @Test
+    public void testGetAnnotations() {
+        System.out.println("test getAnnotations");
+        List<Number> expResult = new ArrayList<Number>();
+        expResult.add(1);
+        expResult.add(2);
+        List<Number> result = jdbcAnnotationDao.getAnnotations(1);
+        assertEquals(expResult, result);
+    }
+
+    
+    ///////////////////////////////////////////
+    @Test
+    public void testDeleteAllAnnotationTarget() throws SQLException{
+        System.out.println("test deleteAllAnnotationTargets");
+        assertEquals(2, jdbcAnnotationDao.deleteAllAnnotationTarget(1));
+        assertEquals(0, jdbcAnnotationDao.deleteAllAnnotationTarget(1));
+    }
+    
+    ///////////////////////////////////////////
+    @Test
+    public void testDeleteAnnotationPrinciplePermissions() throws SQLException{
+        System.out.println("test deleteAllAnnotationTargets");
+        int result = jdbcAnnotationDao.deleteAnnotationPrincipalPermissions(1);
+        assertEquals(2, result);
+        assertEquals(0, jdbcAnnotationDao.deleteAnnotationPrincipalPermissions(1));
+    }
+    
+    ///////////////////////////////////////////
+    @Test
+    public void testAddAnnotationPrinciplePermission() throws SQLException{
+        System.out.println("test addAnnotationTargets");
+        int result = jdbcAnnotationDao.addAnnotationPrincipalPermission(1, 1, Permission.READER);
+        assertEquals(1, result);
+    }
+    
+    ///////////////////////////////////////////
+    @Test
+    public void testAddAnnotationTarget() throws SQLException{
+        System.out.println("test addAnnotationTargetPair");
+        assertEquals(1, jdbcAnnotationDao.addAnnotationTarget(1,3));
+    }
+    
+    ////////////////////////////////
+    
+//    @Test
+//    public void testGetAnnotationInfos() {
+//        System.out.println("getAnnotationInfos");
+//        List<Number> annotIds = new ArrayList<Number>();
+//        annotIds.add(2);
+//        annotIds.add(3);
+//        annotIds.add(4);
+//
+//        jdbcAnnotationDao.setServiceURI(TestBackendConstants._TEST_SERVLET_URI_annotations);
+//        final List<AnnotationInfo> annotationInfos = jdbcAnnotationDao.getAnnotationInfos(annotIds);
+//        assertEquals(3, annotationInfos.size());
+//
+//        assertEquals("Sagrada Famiglia", annotationInfos.get(0).getHeadline());
+//        assertEquals(String.valueOf(TestBackendConstants._TEST_ANNOT_2_OWNER), annotationInfos.get(0).getOwnerRef());
+//        assertEquals(TestBackendConstants._TEST_SERVLET_URI_annotations +"00000000-0000-0000-0000-000000000021",
+//           annotationInfos.get(0).getRef());          
+//        //assertEquals(TestBackendConstants._TEST_ANNOT_1_TARGETS, annotationInfos.get(0).getTargetTargets());
+//
+//        assertEquals("Gaudi", annotationInfos.get(1).getHeadline());
+//        assertEquals(String.valueOf(TestBackendConstants._TEST_ANNOT_3_OWNER), annotationInfos.get(1).getOwnerRef());
+//        assertEquals(TestBackendConstants._TEST_SERVLET_URI_annotations + "00000000-0000-0000-0000-000000000022",
+//           annotationInfos.get(1).getRef()); 
+//        //assertEquals(TestBackendConstants._TEST_ANNOT_2_TARGETS, annotationInfos.get(1).getTargetTargets());
+//
+//        assertEquals(TestBackendConstants._TEST_ANNOT_4_HEADLINE, annotationInfos.get(2).getHeadline());
+//        assertEquals(String.valueOf(TestBackendConstants._TEST_ANNOT_4_OWNER), annotationInfos.get(2).getOwnerRef());
+//        assertEquals(TestBackendConstants._TEST_SERVLET_URI_annotations + "00000000-0000-0000-0000-000000000023",
+//           annotationInfos.get(2).getRef()); 
+//        //assertEquals(TestBackendConstants._TEST_ANNOT_3_TARGETS, annotationInfos.get(2).getTargetTargets());
+//
+//        final List<AnnotationInfo> annotationInfosNull = jdbcAnnotationDao.getAnnotationInfos(null);
+//        assertEquals(null, annotationInfosNull);
+//
+//        final List<AnnotationInfo> annotationInfosZeroSize = jdbcAnnotationDao.getAnnotationInfos(new ArrayList<Number>());
+//        assertEquals(0, annotationInfosZeroSize.size());
+//
+//
+//    }
+
+    /**
+     * Test of getAnnotationREFs method, of class JdbcAnnotationDao.
+     * List<ReTargetREF> getAnnotationREFs(List<Number> annotationIDs)
+     */
+    @Test
+    public void testGetAnnotationREFs() {
+        System.out.println("getAnnotationREFs");
+        List<Number> annotIds = new ArrayList<Number>();
+        annotIds.add(1);
+        annotIds.add(2);
+        annotIds.add(3);
+
+        jdbcAnnotationDao.setServiceURI(TestBackendConstants._TEST_SERVLET_URI_annotations);
+        final List<String> testList = jdbcAnnotationDao.getAnnotationREFs(annotIds);
+        assertEquals(3, testList.size());
+        assertEquals(TestBackendConstants._TEST_SERVLET_URI_annotations+"00000000-0000-0000-0000-000000000021", testList.get(0));
+        assertEquals(TestBackendConstants._TEST_SERVLET_URI_annotations+"00000000-0000-0000-0000-000000000022", testList.get(1));
+        assertEquals(TestBackendConstants._TEST_SERVLET_URI_annotations+"00000000-0000-0000-0000-000000000023", testList.get(2));
+
+        final List<String> testListTwo = jdbcAnnotationDao.getAnnotationREFs(new ArrayList<Number>());
+        assertEquals(0, testListTwo.size());
+
+        final List<String> testListThree = jdbcAnnotationDao.getAnnotationREFs(null);
+        assertEquals(null, testListThree);
+
+    }
+
+    /**
+     *
+     * Test of getAnnotationID method, of class JdbcAnnotationDao. Integer
+     * getAnnotationID(UUID externalID)
+     */
+    @Test
+    public void getInternalID() throws SQLException {
+        System.out.println("test getInternalID");
+
+        final Number annotaionId = jdbcAnnotationDao.getInternalID(UUID.fromString("00000000-0000-0000-0000-000000000021"));
+        assertEquals(1, annotaionId.intValue());
+
+        final Number annotaionIdNE = jdbcAnnotationDao.getInternalID(UUID.fromString("00000000-0000-0000-0000-0000000000cc"));
+        assertEquals(null, annotaionIdNE);
+
+       
+    }
+    
+      /**
+     * Test of getInternalIDFromURI method,
+     * public Number getInternalIDFromURI(UUID externalID);
+     */
+    @Test
+    public void testGetInternalIDFRomURI() {
+        System.out.println("test getInternalIDFromURI");
+        jdbcAnnotationDao.setServiceURI(TestBackendConstants._TEST_SERVLET_URI_annotations);
+        String uri = TestBackendConstants._TEST_SERVLET_URI_annotations+"00000000-0000-0000-0000-000000000021";
+        Number result = jdbcAnnotationDao.getInternalIDFromURI(uri);
+        assertEquals(1, result.intValue());
+    }
+
+    /**
+     *
+     * Test of getAnnotationWithoutTargetsAndPermissions method, of class JdbcAnnotationDao. Annotation
+     * getAnnotation(Number annotationlID)
+     */
+    @Test
+    public void getAnnotationWithoutTargetsAndPermissions() throws SQLException, DatatypeConfigurationException {
+        System.out.println("test getAnnotationWithoutTargets");
+        jdbcAnnotationDao.setServiceURI(TestBackendConstants._TEST_SERVLET_URI_annotations);
+        final Annotation result= jdbcAnnotationDao.getAnnotationWithoutTargetsAndPermissions(1);
+        
+        assertEquals("Sagrada Famiglia", result.getHeadline());
+        assertEquals("<html><body>some html 1</body></html>", result.getBody().getTextBody().getBody()); 
+        assertEquals("text/html", result.getBody().getTextBody().getMimeType()); 
+        assertEquals(TestBackendConstants._TEST_SERVLET_URI_annotations+
+                "00000000-0000-0000-0000-000000000021", result.getURI());
+        assertEquals(DatatypeFactory.newInstance().newXMLGregorianCalendar("2013-08-12T09:25:00.383000Z"), result.getLastModified());
+    }
+
+    /**
+     * Test of deletAnnotation method, of class JdbcAnnotationDao.
+     */
+     /**
+     * 
+     * @param annotationId
+     * @return removed annotation rows (should be 1)
+     */
+    @Test
+    public void testDeleteAnnotation() throws SQLException {
+        System.out.println("deleteAnnotation"); 
+        
+        // to provide integrity, first delete rows in the joint tables
+        jdbcAnnotationDao.deleteAllAnnotationTarget(4);
+        jdbcAnnotationDao.deleteAnnotationPrincipalPermissions(4);
+        
+        assertEquals(1, jdbcAnnotationDao.deleteAnnotation(4));
+        assertEquals(0, jdbcAnnotationDao.deleteAnnotation(4));
+    }
+
+    /**
+     * Test of addAnnotation method, of class JdbcAnnotationDao.
+     */
+    @Test  
+    public void testAddAnnotation() throws SQLException, Exception {
+        System.out.println("test_addAnnotation ");
+
+        final Annotation annotationToAdd = testInstances.getAnnotationToAdd();// existing Targets
+        assertEquals(null, annotationToAdd.getURI());
+        assertEquals(null, annotationToAdd.getLastModified());
+        
+        Number newAnnotationID = jdbcAnnotationDao.addAnnotation(annotationToAdd, 3);
+        assertEquals(5, newAnnotationID);
+        
+        // checking
+        Annotation addedAnnotation= jdbcAnnotationDao.getAnnotationWithoutTargetsAndPermissions(5);
+        assertFalse(null == addedAnnotation.getURI());
+        assertFalse(null == addedAnnotation.getLastModified());
+        assertEquals(annotationToAdd.getBody().getTextBody().getMimeType(), addedAnnotation.getBody().getTextBody().getMimeType());
+        assertEquals(annotationToAdd.getBody().getTextBody().getBody(), addedAnnotation.getBody().getTextBody().getBody()); 
+        assertEquals(annotationToAdd.getHeadline(), addedAnnotation.getHeadline());
+        System.out.println("creation time "+addedAnnotation.getLastModified());
+    }
+
+  
+
+    /**
+     * testing public List<Number> retrieveAnnotationList(List<Number> TargetIDs);
+    
+    **/
+    @Test    
+    public void testRetrieveAnnotationList() {
+        System.out.println("test retrieveAnnotationlist");
+        List<Number> targets = new ArrayList<Number>();
+        targets.add(1);
+        targets.add(2);
+        List<Number> result = jdbcAnnotationDao.getAnnotationIDsForTargets(targets);
+        assertEquals (2, result.size());
+        assertEquals(1, result.get(0));
+        assertEquals(2, result.get(1));
+    }
+    
+    //////////////////////////////////
+    
+    
+    @Test    
+    public void testGetExternalID() {
+        System.out.println("getExternalID");
+
+        final UUID externalId = jdbcAnnotationDao.getExternalID(1);
+        assertEquals(UUID.fromString("00000000-0000-0000-0000-000000000021"), externalId);
+        
+        final UUID externalIdThree = jdbcAnnotationDao.getExternalID(null);
+        assertEquals(null, externalIdThree);
+
+    }
+    
+    
+    /** test
+     * public List<Number> getFilteredAnnotationIDs(String link, String text, String access, String namespace, UUID owner, Timestamp after, Timestamp before) {
+  **/
+    
+    @Test    
+    public void testGetFilteredAnnotationIDs(){
+        System.out.println(" test getFilteredAnnotationIDs");
+       
+        List<Number> result_1 = jdbcAnnotationDao.getFilteredAnnotationIDs(null, "some html", null, null, null);        
+        assertEquals(3, result_1.size());
+        assertEquals(1, result_1.get(0));
+        assertEquals(2, result_1.get(1));
+        assertEquals(4, result_1.get(2));
+        
+             
+        final String after = (new Timestamp(0)).toString();
+        final String before = (new Timestamp(System.currentTimeMillis())).toString();
+ 
+        List<Number> result_2 = jdbcAnnotationDao.getFilteredAnnotationIDs(1, "some html", null, after, before);        
+        assertEquals(1, result_2.size());
+        assertEquals(1, result_2.get(0));
+        
+        final String after_1 = (new Timestamp(System.currentTimeMillis())).toString();// no annotations added after "now"       
+        List<Number> result_3 = jdbcAnnotationDao.getFilteredAnnotationIDs(4, "some html", null, after_1, null);        
+        assertEquals(0, result_3.size());
+        
+        
+    }
+    
+    //////////////////////////////////
+   
+  
+    
+    // public List<Map<Number, String>> retrievePermissions(Number annotationId)
+    
+    @Test
+    public void testRetrievePermissions (){
+        System.out.println("test Permissions");
+        List<Map<Number, String>> result = jdbcAnnotationDao.getPermissions(1);
+        assertEquals(2, result.size());
+        assertEquals("writer", result.get(0).get(2));
+        assertEquals("reader", result.get(1).get(3));
+        
+        
+    }
+}
Index: /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/test/java/eu/dasish/annotation/backend/dao/impl/JdbcCachedRepresentationDaoTest.java
===================================================================
--- /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/test/java/eu/dasish/annotation/backend/dao/impl/JdbcCachedRepresentationDaoTest.java	(revision 4603)
+++ /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/test/java/eu/dasish/annotation/backend/dao/impl/JdbcCachedRepresentationDaoTest.java	(revision 4603)
@@ -0,0 +1,201 @@
+/*
+ * Copyright (C) 2013 DASISH
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
+ */
+package eu.dasish.annotation.backend.dao.impl;
+
+import eu.dasish.annotation.backend.TestBackendConstants;
+import eu.dasish.annotation.schema.CachedRepresentationInfo;
+import java.io.UnsupportedEncodingException;
+import java.sql.Blob;
+import java.sql.SQLException;
+import java.util.List;
+import java.util.UUID;
+import javax.sql.rowset.serial.SerialBlob;
+import javax.sql.rowset.serial.SerialException;
+import org.junit.Test;
+import static org.junit.Assert.*;
+import org.junit.Ignore;
+import org.junit.runner.RunWith;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+
+/**
+ *
+ * @author olhsha
+ */
+@RunWith(SpringJUnit4ClassRunner.class)
+@ContextConfiguration({"/spring-test-config/dataSource.xml", "/spring-config/cachedRepresentationDao.xml"})
+public class JdbcCachedRepresentationDaoTest extends JdbcResourceDaoTest {
+
+    @Autowired
+    JdbcCachedRepresentationDao jdbcCachedRepresentationDao;
+
+     /**
+     * Test of stringURItoExternalID method
+     * public String stringURItoExternalID(String uri);
+     */
+    @Test
+    public void testStringURItoExternalID() {
+        System.out.println("test stringURItoExternalID");
+        jdbcCachedRepresentationDao.setServiceURI(TestBackendConstants._TEST_SERVLET_URI_cached);
+        String randomUUID = UUID.randomUUID().toString();
+        String uri = TestBackendConstants._TEST_SERVLET_URI_cached + randomUUID;
+        String externalID = jdbcCachedRepresentationDao.stringURItoExternalID(uri);
+        assertEquals(randomUUID, externalID);
+    }
+    
+    /**
+     * Test of externalIDtoURI method
+     * public String externalIDtoURI(String externalID);
+     */
+    @Test
+    public void testExternalIDtoURI() {
+        System.out.println("test stringURItoExternalID");
+        jdbcCachedRepresentationDao.setServiceURI(TestBackendConstants._TEST_SERVLET_URI_cached);
+        String randomUUID = UUID.randomUUID().toString();
+        String uri = TestBackendConstants._TEST_SERVLET_URI_cached+randomUUID;
+        String uriResult = jdbcCachedRepresentationDao.externalIDtoURI(randomUUID);
+        assertEquals(uri, uriResult);
+    }
+    
+    
+    public JdbcCachedRepresentationDaoTest() {
+    }
+
+    /**
+     * Test of getExternalId method, of class JdbcCachedRepresentationDao.
+     * public UUID getExternalId(Number internalID);
+     *
+     */
+    @Test
+    public void testGetExternalId() {
+        System.out.println("getExternalId");
+        Number internalID = 1;
+        UUID expResult = UUID.fromString("00000000-0000-0000-0000-000000000051");
+        UUID result = jdbcCachedRepresentationDao.getExternalID(internalID);
+        assertEquals(expResult, result);
+    }
+
+    /**
+     * Test of getInternalId method, of class JdbcCachedRepresentationDao.
+     * public Number getInternalId(UUID externalID);
+     */
+    @Test
+    public void testGetInternalId() {
+        System.out.println("test getInternalID");
+        UUID externalID = UUID.fromString("00000000-0000-0000-0000-000000000051");
+        Number result = jdbcCachedRepresentationDao.getInternalID(externalID);
+        assertEquals(1, result.intValue());
+    }
+    
+    
+    /**
+     * Test of getInternalIDFromURI method,
+     * public Number getInternalIDFromURI(UUID externalID);
+     */
+    @Test
+    public void testGetInternalIDFRomURI() {
+        System.out.println("test getInternalIDFromURI");
+        jdbcCachedRepresentationDao.setServiceURI(TestBackendConstants._TEST_SERVLET_URI_cached);
+        String uri = TestBackendConstants._TEST_SERVLET_URI_cached +"00000000-0000-0000-0000-000000000051";
+        Number result = jdbcCachedRepresentationDao.getInternalIDFromURI(uri);
+        assertEquals(1, result.intValue());
+    }
+   
+    /**
+     * Test of getCachedRepresentationInfo method, of class
+     * JdbcCachedRepresentationDao. public CachedRepresentationInfo
+     * getCachedRepresentationInfo(Number internalID);
+     */
+    @Test
+    public void testGetCachedRepresentationInfo() {
+        System.out.println("getCachedRepresentationInfo");
+
+        jdbcCachedRepresentationDao.setServiceURI(TestBackendConstants._TEST_SERVLET_URI_cached);
+        CachedRepresentationInfo result = jdbcCachedRepresentationDao.getCachedRepresentationInfo(1);
+        assertEquals(TestBackendConstants._TEST_SERVLET_URI_cached + "00000000-0000-0000-0000-000000000051", result.getURI());
+        assertEquals("text/html", result.getMimeType());
+        assertEquals("latex", result.getTool());
+        assertEquals("text", result.getType());
+        assertEquals(TestBackendConstants._TEST_SERVLET_URI_cached +"00000000-0000-0000-0000-000000000051", result.getURI());
+    }
+
+ 
+    
+    /* Test of getCachedRepresentationsForTarget method, of class JdbcTargetDao.
+     */
+    @Test
+    public void testGetCachedRepresentations() {
+        System.out.println("test getCachedRepresentationsForTarget");
+        Number TargetID = 1;
+        List<Number> result = jdbcCachedRepresentationDao.getCachedRepresentationsForTarget(TargetID);
+        assertEquals(1, result.get(0));
+        assertEquals(2, result.get(1));
+    }
+
+    /**
+     * Test of deleteCachedRepresentationInfo method, of class
+     * JdbcCachedRepresentationDao. public int
+     * deleteCachedRepresentationInfo(Number internalID);
+     */
+    @Test
+    public void testDeleteCachedRepresentation() {
+        System.out.println("deleteCachedRepresentationInfo");
+        Number internalID = 6; /// deleted because no version refers to it
+        int result = jdbcCachedRepresentationDao.deleteCachedRepresentation(internalID);
+        assertEquals(1, result);
+
+    }
+
+    /**
+     * Test of addCachedRepresentationInfo method, of class
+     * JdbcCachedRepresentationDao. public CachedRepresentationInfo
+     * addCachedRepresentationInfo(CachedRepresentationInfo cached);
+     */
+//    @Test
+//    public void testAddCachedRepresentation() throws SerialException, SQLException {
+//        System.out.println("addCachedRepresentation");
+//
+//        CachedRepresentationInfo cachedInfo = new CachedRepresentationInfo();
+//        cachedInfo.setMimeType("text/plain");
+//        cachedInfo.setTool("vi");
+//        cachedInfo.setType("text");
+//        cachedInfo.setURI(null);
+//
+//        String blobString = "111";
+//        byte[] blobBytes = blobString.getBytes();
+//        final Blob cachedBlob = new SerialBlob(blobBytes);
+//
+//        Number result = jdbcCachedRepresentationDao.addCachedRepresentation(cachedInfo, cachedBlob);
+//        // checking
+//        CachedRepresentationInfo addedCachedInfo = jdbcCachedRepresentationDao.getCachedRepresentationInfo(result);
+//        assertEquals(8, result.intValue());
+//        assertEquals("text/plain", addedCachedInfo.getMimeType());
+//        assertEquals("vi", addedCachedInfo.getTool());
+//        assertEquals("text", addedCachedInfo.getType());
+//        assertFalse(addedCachedInfo.getURI() == null); // new non-null external identifier should be assigned
+//
+//        Blob addedBlob = jdbcCachedRepresentationDao.getCachedRepresentationBlob(result);
+//        int lengthBlob = 3;
+//        String addedBlobString = new String(addedBlob.getBytes(1, lengthBlob));
+//        assertEquals(blobString, addedBlobString);
+//
+//    }
+//    
+   
+}
Index: /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/test/java/eu/dasish/annotation/backend/dao/impl/JdbcNotebookDaoTest.java
===================================================================
--- /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/test/java/eu/dasish/annotation/backend/dao/impl/JdbcNotebookDaoTest.java	(revision 4603)
+++ /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/test/java/eu/dasish/annotation/backend/dao/impl/JdbcNotebookDaoTest.java	(revision 4603)
@@ -0,0 +1,234 @@
+/*
+ * Copyright (C) 2013 DASISH
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
+ */
+package eu.dasish.annotation.backend.dao.impl;
+
+import eu.dasish.annotation.schema.Notebook;
+import eu.dasish.annotation.schema.NotebookInfo;
+import eu.dasish.annotation.schema.Permission;
+import java.util.ArrayList;
+import java.util.List;
+import javax.xml.datatype.DatatypeConfigurationException;
+import javax.xml.datatype.DatatypeFactory;
+import org.junit.Test;
+import static org.junit.Assert.*;
+import org.junit.Ignore;
+import org.junit.runner.RunWith;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+
+/**
+ *
+ * @author olhsha
+ */
+@RunWith(SpringJUnit4ClassRunner.class)
+@ContextConfiguration({"/spring-test-config/dataSource.xml", "/spring-config/notebookDao.xml"})
+public class JdbcNotebookDaoTest extends JdbcResourceDaoTest {
+
+    @Autowired
+    JdbcNotebookDao jdbcNotebookDao;
+
+    /**
+     * Test of getOwner method, of class JdbcNotebookDao.
+     */
+    @Test
+    public void testGetOwner() {
+        System.out.println("test getOwner");
+        assertEquals(3, jdbcNotebookDao.getOwner(4));
+    }
+
+    /**
+     * Test of getNotebookIDs method, of class JdbcNotebookDao.
+     */
+    @Test
+    public void testGetNotebookIDs() {
+        System.out.println("test getNotebookIDs for a principal with Permission");
+        List<Number> expResult = new ArrayList<Number>();
+        expResult.add(1);
+        expResult.add(4);
+        List<Number> result = jdbcNotebookDao.getNotebookIDs(2, Permission.WRITER);
+        assertEquals(expResult, result);
+    }
+
+    /**
+     * Test of getNotebookIDsOwnedBy method, of class JdbcNotebookDao.
+     */
+    @Test
+    public void testGetNotebookIDsOwnedBy() {
+        System.out.println("test getNotebookIDsOwnedBy");
+        List<Number> expResult = new ArrayList<Number>();
+        expResult.add(3);
+        expResult.add(4);
+        List<Number> result = jdbcNotebookDao.getNotebookIDsOwnedBy(3);
+        assertEquals(expResult, result);
+    }
+
+  
+    /**
+     * Test of getNotebookInfoWithoutOwner method, of class JdbcNotebookDao.
+     */
+    @Test
+    public void testGetNotebookInfoWithoutOwner() {
+        System.out.println("test getNotebookInfoWithoutOwner");
+        NotebookInfo result = jdbcNotebookDao.getNotebookInfoWithoutOwner(1);
+        assertEquals("00000000-0000-0000-0000-000000000011", result.getRef());
+        assertEquals("Notebook 1", result.getTitle());
+        assertEquals(null, result.getOwnerRef());
+    }
+
+    /**
+     * Test of getNotebookWithoutAnnotationsAndPermissionsAndOwner method, of
+     * class JdbcNotebookDao.
+     */
+    @Test
+    public void testGetNotebookWithoutAnnotationsAndPermissionsAndOwner() {
+        System.out.println("test getNotebookWithoutAnnotationsAndPermissionsAndOwner");
+        Notebook result = jdbcNotebookDao.getNotebookWithoutAnnotationsAndPermissionsAndOwner(1);
+        assertEquals("00000000-0000-0000-0000-000000000011", result.getURI());
+        assertEquals("Notebook 1", result.getTitle());
+        assertEquals("2013-08-12T09:25:00.383000Z", result.getLastModified().toString());
+    }
+
+   
+    /**
+     * Test of updateNotebookMetadata method, of class JdbcNotebookDao.
+     */
+    @Test
+    public void testUpdateNotebookMetadata() {
+        System.out.println("test updateNotebookMetadata");
+        boolean result = jdbcNotebookDao.updateNotebookMetadata(1, "Gaudi and his work", 3);
+        assertEquals(true, result);
+        assertEquals("Gaudi and his work", jdbcNotebookDao.getNotebookWithoutAnnotationsAndPermissionsAndOwner(1).getTitle());
+        assertEquals(3, jdbcNotebookDao.getOwner(1));
+    }
+
+    /**
+     * Test of setOwner method, of class JdbcNotebookDao.
+     */
+    @Test
+    public void testSetOwner() {
+        System.out.println("test setOwner");
+        boolean result = jdbcNotebookDao.setOwner(1, 2);
+        assertTrue(result);
+        assertEquals(2, jdbcNotebookDao.getOwner(2));
+    }
+
+    /**
+     * Test of updateUserPermissionForNotebook method, of class JdbcNotebookDao.
+     */
+    @Test
+    public void testUpdateUserPermissionForNotebook() {
+        System.out.println("test updateUserPermissionForNotebook");
+        boolean result = jdbcNotebookDao.updateUserPermissionForNotebook(1, 2, Permission.READER);
+        assertTrue(result);
+
+        // in the next test the update should fail
+        //assertFalse(jdbcNotebookDao.updateUserPermissionForNotebook(1, 2, Permission.OWNER));
+        //SQL throws an error, which is good
+    }
+
+    /**
+     * Test of createNotebookWithoutPermissionsAndAnnotations method, of class
+     * JdbcNotebookDao.
+     */
+    @Test
+    public void testCreateNotebookWithoutPermissionsAndAnnotations() throws DatatypeConfigurationException {
+        System.out.println("test createNotebookWithoutPermissionsAndAnnotations");
+        Notebook notebook = new Notebook();
+        notebook.setTitle("New test notebook");
+        notebook.setLastModified(DatatypeFactory.newInstance().newXMLGregorianCalendar("2014-02-12T09:25:00.383000Z"));
+        Number result = jdbcNotebookDao.createNotebookWithoutPermissionsAndAnnotations(notebook, 3);
+        assertEquals(5, result);
+        assertEquals(3, jdbcNotebookDao.getOwner(result));
+        assertNotNull(jdbcNotebookDao.getExternalID(result));
+        assertEquals("New test notebook", jdbcNotebookDao.getNotebookWithoutAnnotationsAndPermissionsAndOwner(result).getTitle());
+    }
+
+    /**
+     * Test of addAnnotationToNotebook method, of class JdbcNotebookDao.
+     */
+    @Test
+    public void testAddAnnotationToNotebook() {
+        System.out.println("test addAnnotationToNotebook");
+        boolean result = jdbcNotebookDao.addAnnotationToNotebook(2, 4);
+        assertTrue(result);
+    }
+
+    /**
+     * Test of addPermissionToNotebook method, of class JdbcNotebookDao.
+     */
+    @Test
+    public void testAddPermissionToNotebook() {
+        System.out.println("test addPermissionToNotebook");
+        boolean result = jdbcNotebookDao.addPermissionToNotebook(2, 4, Permission.WRITER);
+        assertTrue(result);
+    }
+
+    /**
+     * Test of deleteAnnotationFromNotebook method, of class JdbcNotebookDao.
+     */
+    @Test
+    public void testDeleteAnnotationFromNotebook() {
+        System.out.println("test deleteAnnotationFromNotebook");
+        boolean result = jdbcNotebookDao.deleteAnnotationFromNotebook(1, 2);
+        assertTrue(result);
+    }
+
+    /**
+     * Test of deleteNotebookPrincipalPermission method, of class
+     * JdbcNotebookDao.
+     */
+    @Test
+    public void testDeleteNotebookPrincipalPermission() {
+        System.out.println("deleteNotebookPrincipalPermission");
+        boolean result = jdbcNotebookDao.deleteNotebookPrincipalPermission(1, 2);
+        assertTrue(result);
+    }
+
+    /**
+     * Test of deleteAllAnnotationsFromNotebook method, of class
+     * JdbcNotebookDao.
+     */
+    @Test
+    public void testDeleteAllAnnotationsFromNotebook() {
+        System.out.println("test deleteAllAnnotationsFromNotebook");
+        boolean result = jdbcNotebookDao.deleteAllAnnotationsFromNotebook(1);
+        assertTrue(result);
+    }
+
+    /**
+     * Test of deleteAllPermissionsForNotebook method, of class JdbcNotebookDao.
+     */
+    @Test
+    public void testDeleteAllPermissionsForNotebook() {
+        System.out.println("test deleteAllPermissionsForNotebook");
+        boolean result = jdbcNotebookDao.deleteAllPermissionsForNotebook(1);
+        assertTrue(result);
+    }
+
+    /**
+     * Test of deleteNotebook method, of class JdbcNotebookDao.
+     */
+    @Test
+    public void testDeleteNotebook() {
+        System.out.println("test deleteNotebook");
+        boolean result = jdbcNotebookDao.deleteNotebook(3);
+        assertTrue(result);
+        assertNull(jdbcNotebookDao.getExternalID(3));
+    }
+}
Index: /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/test/java/eu/dasish/annotation/backend/dao/impl/JdbcResourceDaoTest.java
===================================================================
--- /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/test/java/eu/dasish/annotation/backend/dao/impl/JdbcResourceDaoTest.java	(revision 4603)
+++ /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/test/java/eu/dasish/annotation/backend/dao/impl/JdbcResourceDaoTest.java	(revision 4603)
@@ -0,0 +1,94 @@
+/*
+ * Copyright (C) 2013 DASISH
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
+ */
+package eu.dasish.annotation.backend.dao.impl;
+
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.net.URISyntaxException;
+import java.net.URL;
+import java.util.Scanner;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.dao.DataAccessException;
+import org.springframework.jdbc.core.JdbcTemplate;
+import org.junit.runner.RunWith;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+/**
+ *
+ * @author olhsha
+ */
+@RunWith(SpringJUnit4ClassRunner.class)
+@ContextConfiguration({"/spring-test-config/dataSource.xml"})
+public class JdbcResourceDaoTest {
+   
+   @Autowired
+   private JdbcTemplate jdbcTemplate; 
+   
+  public static  String getNormalisedSql() throws FileNotFoundException, URISyntaxException {
+        // remove the unsupported sql for the test
+        final URL sqlUrl = JdbcResourceDaoTest.class.getResource("/sql/DashishAnnotatorCreate.sql");
+        String sqlString = new Scanner(new File(sqlUrl.toURI()), "UTF8").useDelimiter("\\Z").next();
+        for (String unknownToken : new String[]{
+            "SET client_encoding",
+            "CREATE DATABASE",
+            "\\\\connect",
+            "SET default_with_oids",
+            //"ALTER SEQUENCE",
+            //ALTER TABLE ONLY",
+            //"ADD CONSTRAINT",
+            //"CREATE INDEX", 
+            // "ALTER TABLE ONLY [a-z]* ALTER COLUMN",
+            // "ALTER TABLE ONLY [^A]* ADD CONSTRAINT"
+        }) {
+            sqlString = sqlString.replaceAll(unknownToken, "-- " + unknownToken);
+        }
+        //sqlString = sqlString.replaceAll("CACHE 1;", "; -- CACHE 1;");
+        //sqlString = sqlString.replaceAll("UUID", "text");
+        sqlString = sqlString.replaceAll("bytea", "blob");
+        sqlString = sqlString.replaceAll("SERIAL NOT NULL", "INTEGER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY");
+        sqlString = sqlString.replaceAll("\\(current_timestamp AT TIME ZONE 'UTC'\\)", "current_timestamp AT TIME ZONE INTERVAL '00:00' HOUR TO MINUTE");
+        return sqlString;
+    }
+
+    public static String getTestDataInsertSql() throws FileNotFoundException, URISyntaxException {
+        final URL sqlUrl = JdbcResourceDaoTest.class.getResource("/test-data/InsertTestData.sql");
+        String sqlString = new Scanner(new File(sqlUrl.toURI()), "UTF8").useDelimiter("\\Z").next();
+        return sqlString;
+    }
+
+    @Before
+    public void setUp() throws DataAccessException, FileNotFoundException, URISyntaxException {
+        jdbcTemplate.execute("DROP SCHEMA PUBLIC CASCADE");
+        // consume the DashishAnnotatorCreate sql script to create the database
+        jdbcTemplate.execute(getNormalisedSql());
+        jdbcTemplate.execute(getTestDataInsertSql());
+    }
+
+    @After
+    public void tearDown() {
+    }
+    
+    @Test 
+    public void dummy(){
+        
+    }
+
+}
Index: /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/test/java/eu/dasish/annotation/backend/dao/impl/JdbcTargetDaoTest.java
===================================================================
--- /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/test/java/eu/dasish/annotation/backend/dao/impl/JdbcTargetDaoTest.java	(revision 4603)
+++ /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/test/java/eu/dasish/annotation/backend/dao/impl/JdbcTargetDaoTest.java	(revision 4603)
@@ -0,0 +1,218 @@
+/*
+ * Copyright (C) 2013 DASISH
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
+ */
+package eu.dasish.annotation.backend.dao.impl;
+
+import eu.dasish.annotation.backend.TestBackendConstants;
+import eu.dasish.annotation.schema.Target;
+import eu.dasish.annotation.schema.TargetInfo;
+import java.sql.SQLException;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import org.junit.Test;
+import static org.junit.Assert.*;
+import org.junit.Ignore;
+import org.junit.runner.RunWith;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+
+/**
+ *
+ * @author olhsha
+ */
+@RunWith(SpringJUnit4ClassRunner.class)
+@ContextConfiguration({"/spring-test-config/dataSource.xml", "/spring-config/TargetDao.xml"})
+public class JdbcTargetDaoTest extends JdbcResourceDaoTest {
+
+    @Autowired
+    JdbcTargetDao jdbcTargetDao;
+
+    /**
+     * Test of stringURItoExternalID method public String
+     * stringURItoExternalID(String uri);
+     */
+    @Test
+    public void testStringURItoExternalID() {
+        System.out.println("test stringURItoExternalID");
+        jdbcTargetDao.setServiceURI(TestBackendConstants._TEST_SERVLET_URI_Targets);
+        String randomUUID = UUID.randomUUID().toString();
+        String uri = TestBackendConstants._TEST_SERVLET_URI_Targets + randomUUID;
+        String externalID = jdbcTargetDao.stringURItoExternalID(uri);
+        assertEquals(randomUUID, externalID);
+    }
+
+    /**
+     * Test of externalIDtoURI method public String externalIDtoURI(String
+     * externalID);
+     */
+    @Test
+    public void testExternalIDtoURI() {
+        System.out.println("test stringURItoExternalID");
+        jdbcTargetDao.setServiceURI(TestBackendConstants._TEST_SERVLET_URI_Targets);
+        String randomUUID = UUID.randomUUID().toString();
+        String uri = TestBackendConstants._TEST_SERVLET_URI_Targets + randomUUID;
+        String uriResult = jdbcTargetDao.externalIDtoURI(randomUUID);
+        assertEquals(uri, uriResult);
+    }
+
+    /**
+     * Test of getExternalID method, of class JdbcTargetDao.
+     */
+    @Test
+    public void testGetExternalID() {
+        System.out.println("getExternalID");
+        Number internalID = 1;
+        UUID result = jdbcTargetDao.getExternalID(internalID);
+        assertEquals("00000000-0000-0000-0000-000000000031", result.toString());
+    }
+
+    /**
+     * Test of getInternalID method, of class JdbcTargetDao.
+     */
+    @Test
+    public void testGetInternalId() {
+        System.out.println("getInternalId");
+        UUID externalID = UUID.fromString("00000000-0000-0000-0000-000000000031");
+        Number expResult = 1;
+        Number result = jdbcTargetDao.getInternalID(externalID);
+        assertEquals(expResult, result);
+    }
+
+    /**
+     * Test of getInternalIDFromURI method, public Number
+     * getInternalIDFromURI(UUID externalID);
+     */
+    @Test
+    public void testGetInternalIDFRomURI() {
+        System.out.println("test getInternalIDFromURI");
+        jdbcTargetDao.setServiceURI(TestBackendConstants._TEST_SERVLET_URI_Targets);
+        String uri = TestBackendConstants._TEST_SERVLET_URI_Targets + "00000000-0000-0000-0000-000000000031";
+        Number result = jdbcTargetDao.getInternalIDFromURI(uri);
+        assertEquals(1, result.intValue());
+    }
+
+    /**
+     * Test of getTarget method, of class JdbcTargetDao.
+     */
+    @Test
+    public void testGetTarget() {
+        System.out.println("getTarget");
+        jdbcTargetDao.setServiceURI(TestBackendConstants._TEST_SERVLET_URI_Targets);
+        Target result = jdbcTargetDao.getTarget(1);
+        assertEquals(TestBackendConstants._TEST_SERVLET_URI_Targets + "00000000-0000-0000-0000-000000000031", result.getURI());
+        assertEquals("http://nl.wikipedia.org/wiki/Sagrada_Fam%C3%ADlia" + "#" + "de_Opdracht", result.getLink());
+        assertEquals("version 1.0", result.getVersion());
+        // TODO :add time stamp test
+
+    }
+
+    /**
+     * Test of deleteTarget method, of class JdbcTargetDao.
+     */
+    @Test
+    public void testDeleteTarget() {
+        System.out.println("deleteTarget");
+        // test 1
+        // remove the rows from the joint table to keep integrity
+        int result = jdbcTargetDao.deleteTarget(6); //the Target is in use, should not be deleted
+        assertEquals(1, result);
+    }
+
+    /**
+     * Test of addTargetCachedRepresentation method, of class JdbcTargetDao.
+     */
+    @Test
+    public void testAddTargetCachedRepresentation() throws SQLException {
+        System.out.println("test addTargetCachedRepresentation");
+        assertEquals(1, jdbcTargetDao.addTargetCachedRepresentation(6, 7, "#firstrow"));
+        // content test
+        Map<Number, String> pairs = jdbcTargetDao.getCachedRepresentationFragmentPairs(6);
+        assertEquals(1, pairs.size());
+        assertEquals("#firstrow", pairs.get(7));
+    }
+
+    /**
+     * Test of addTarget method, of class JdbcTargetDao.
+     */
+    @Test
+    public void testAddTarget() throws SQLException {
+        System.out.println("addTarget");
+
+        Target freshTarget = new Target();
+        freshTarget.setLink("http://nl.wikipedia.org/wiki/Sagrada_Fam%C3%ADlia" + "#Het_ontwerp");
+        freshTarget.setVersion("version 1.0");
+        freshTarget.setLastModified(null);
+
+        Number result = jdbcTargetDao.addTarget(freshTarget);
+        assertEquals(8, result);
+        // detailed checking
+        Target addedTarget = jdbcTargetDao.getTarget(result);
+        assertEquals("http://nl.wikipedia.org/wiki/Sagrada_Fam%C3%ADlia" + "#Het_ontwerp", addedTarget.getLink());
+        assertEquals("version 1.0", addedTarget.getVersion());
+        assertTrue(addedTarget.getURI().startsWith(TestBackendConstants._TEST_SERVLET_URI_Targets));
+    }
+
+    /**
+     * Test of getTargetInfos method, of class JdbcTargetDao.
+     */
+    @Test
+    public void testGetTargetInfos() {
+        System.out.println("getTargetInfos");
+        jdbcTargetDao.setServiceURI(TestBackendConstants._TEST_SERVLET_URI_Targets);
+        List<Number> test = new ArrayList<Number>();
+        test.add(1);
+        test.add(2);
+        List<TargetInfo> result = jdbcTargetDao.getTargetInfos(test);
+        assertEquals(2, result.size());
+        assertEquals(TestBackendConstants._TEST_SERVLET_URI_Targets + "00000000-0000-0000-0000-000000000031", result.get(0).getRef());
+        assertEquals(TestBackendConstants._TEST_SERVLET_URI_Targets + "00000000-0000-0000-0000-000000000032", result.get(1).getRef());
+        assertEquals("version 1.0", result.get(0).getVersion());
+        assertEquals("version 1.1", result.get(1).getVersion());
+        assertEquals("http://nl.wikipedia.org/wiki/Sagrada_Fam%C3%ADlia" + "#" + "de_Opdracht", result.get(0).getLink());
+        assertEquals("http://nl.wikipedia.org/wiki/Antoni_Gaud%C3%AD" + "#Vroege_werk", result.get(1).getLink());
+
+    }
+
+    /**
+     * test public List<Number> getTargetsForLink(String link)
+     *
+     *
+     */
+    @Test
+    public void tesGetTargetsReferringTo() {
+        System.out.println(" test getTargetsReferringTo");
+
+        String substring = "http://nl.wikipedia.org";
+        List<Number> result = jdbcTargetDao.getTargetsReferringTo(substring);
+        assertEquals(2, result.size());
+        assertEquals(1, result.get(0));
+        assertEquals(2, result.get(1));
+    }
+
+    @Test
+    public void testRetrieveTargetIDs() {
+        System.out.println("retrieveTargetIDs");
+        Number annotationID = 1;
+        List<Number> result = jdbcTargetDao.retrieveTargetIDs(annotationID);
+        assertEquals(2, result.size());
+        assertEquals(1, result.get(0));
+        assertEquals(2, result.get(1));
+    }
+}
Index: /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/test/java/eu/dasish/annotation/backend/dao/impl/JdbcUserDaoTest.java
===================================================================
--- /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/test/java/eu/dasish/annotation/backend/dao/impl/JdbcUserDaoTest.java	(revision 4603)
+++ /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/test/java/eu/dasish/annotation/backend/dao/impl/JdbcUserDaoTest.java	(revision 4603)
@@ -0,0 +1,177 @@
+/*
+ * Copyright (C) 2013 DASISH
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
+ */
+package eu.dasish.annotation.backend.dao.impl;
+
+import eu.dasish.annotation.backend.TestBackendConstants;
+import eu.dasish.annotation.backend.TestInstances;
+import eu.dasish.annotation.schema.Permission;
+import eu.dasish.annotation.schema.User;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.UUID;
+import org.junit.Test;
+import static org.junit.Assert.*;
+import org.junit.runner.RunWith;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+
+/**
+ *
+ * @author olhsha
+ */
+@RunWith(SpringJUnit4ClassRunner.class)
+@ContextConfiguration({"/spring-test-config/dataSource.xml", "/spring-config/userDao.xml"})
+public class JdbcUserDaoTest extends JdbcResourceDaoTest {
+
+    @Autowired
+    JdbcUserDao jdbcUserDao;
+    TestInstances testInstances = new TestInstances(TestBackendConstants._TEST_SERVLET_URI);
+    
+     /**
+     * Test of stringURItoExternalID method
+     * public String stringURItoExternalID(String uri);
+     */
+    @Test
+    public void testStringURItoExternalID() {
+        System.out.println("test stringURItoExternalID");
+        jdbcUserDao.setServiceURI(TestBackendConstants._TEST_SERVLET_URI_users);
+        String randomUUID = UUID.randomUUID().toString();
+        String uri = TestBackendConstants._TEST_SERVLET_URI_users + randomUUID;
+        String externalID = jdbcUserDao.stringURItoExternalID(uri);
+        assertEquals(randomUUID, externalID);
+    }
+    
+    /**
+     * Test of externalIDtoURI method
+     * public String externalIDtoURI(String externalID);
+     */
+    @Test
+    public void testExternalIDtoURI() {
+        System.out.println("test stringURItoExternalID");
+        jdbcUserDao.setServiceURI(TestBackendConstants._TEST_SERVLET_URI_users);
+        String randomUUID = UUID.randomUUID().toString();
+        String uri = TestBackendConstants._TEST_SERVLET_URI_users+randomUUID;
+        String uriResult = jdbcUserDao.externalIDtoURI(randomUUID);
+        assertEquals(uri, uriResult);
+    }
+
+    /**
+     * Test of getInternalID method, of class JdbcUserDao. Number
+     * getInternalID(UUID UUID);
+     */
+    @Test
+    public void testGetInternalID() {
+        Number testOne = jdbcUserDao.getInternalID(UUID.fromString("00000000-0000-0000-0000-000000000113"));
+        assertEquals(3, testOne.intValue());
+
+        Number testTwo = jdbcUserDao.getInternalID(UUID.fromString("00000000-0000-0000-0000-000000000ccc"));
+        assertEquals(null, testTwo);
+
+    }
+
+    /**
+     * public UUID getExternalID(Number internalId)
+     */
+    @Test
+    public void testGetExternalID() {
+        UUID testOne = jdbcUserDao.getExternalID(3);
+        assertEquals("00000000-0000-0000-0000-000000000113", testOne.toString());
+
+        UUID testTwo = jdbcUserDao.getExternalID(null);
+        assertEquals(null, testTwo);
+    }
+
+    @Test
+    public void testGetUser() {
+        System.out.println("test getUser");
+        jdbcUserDao.setServiceURI(TestBackendConstants._TEST_SERVLET_URI_users);
+        User result = jdbcUserDao.getUser(1);
+        assertEquals("Twan", result.getDisplayName());
+        assertEquals("Twan.Goosen@mpi.nl", result.getEMail());
+        assertEquals(TestBackendConstants._TEST_SERVLET_URI_users+"00000000-0000-0000-0000-000000000111", result.getURI());
+    }
+
+    @Test
+    public void testAddUser() {
+        System.out.println("test addUser");
+        jdbcUserDao.setServiceURI(TestBackendConstants._TEST_SERVLET_URI_users);
+        String freshUserName = "Guilherme";
+        String freshUserEmail = "guisil@mpi.nl";
+
+        User freshUser = new User();
+        freshUser.setDisplayName(freshUserName);
+        freshUser.setEMail(freshUserEmail);
+
+        Number result = jdbcUserDao.addUser(freshUser, "secret X");
+        assertEquals(11, result.intValue());
+        User addedUser = jdbcUserDao.getUser(result);
+        assertEquals(freshUserName, addedUser.getDisplayName());
+        assertEquals(freshUserEmail, addedUser.getEMail());
+        assertFalse(null == jdbcUserDao.stringURItoExternalID(addedUser.getURI()));
+    }
+
+    @Test
+    public void testDeleteUser() {
+        System.out.println("test deleteUser");
+        jdbcUserDao.setServiceURI(TestBackendConstants._TEST_SERVLET_URI_users);
+
+        int result = jdbcUserDao.deleteUser(10);
+        assertEquals(1, result);
+        User check = jdbcUserDao.getUser(10);
+        assertTrue(null==check);
+    }
+    
+    
+    @Test
+    public void testUserIsInUse(){
+        assertTrue(jdbcUserDao.userIsInUse(1));
+        assertTrue(jdbcUserDao.userIsInUse(3));
+        assertFalse(jdbcUserDao.userIsInUse(10));
+    }
+
+    @Test
+    public void tesUserExists() {
+        System.out.println("test userExists");
+        jdbcUserDao.setServiceURI(TestBackendConstants._TEST_SERVLET_URI_users);
+
+        User freshUser = new User();
+        freshUser.setDisplayName("Guilherme");
+        freshUser.setEMail("guisil@mpi.nl");
+        assertEquals(false,jdbcUserDao.userExists(freshUser));
+
+        User user = new User();
+        user.setDisplayName("Olha");
+        user.setEMail("Olha.Shakaravska@mpi.nl");
+        assertTrue(jdbcUserDao.userExists(user));
+    }
+    
+      /**
+     * Test of getPrincipalIDsWithPermission method, of class JdbcNotebookDao.
+     */
+    @Test
+    public void testGetPrincipalIDsWithPermission() {
+        System.out.println("gtest getPrincipalIDsWithPermission");
+        List<Number> expResult = new ArrayList<Number>();
+        expResult.add(2);
+        expResult.add(4);
+        List result = jdbcUserDao.getPrincipalIDsWithPermissionForNotebook(1, Permission.WRITER);
+        assertEquals(expResult, result);
+    }
+
+}
Index: /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/test/java/eu/dasish/annotation/backend/rest/AnnotationResourceTest.java
===================================================================
--- /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/test/java/eu/dasish/annotation/backend/rest/AnnotationResourceTest.java	(revision 4603)
+++ /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/test/java/eu/dasish/annotation/backend/rest/AnnotationResourceTest.java	(revision 4603)
@@ -0,0 +1,243 @@
+/*
+ * Copyright (C) 2013 DASISH
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
+ */
+package eu.dasish.annotation.backend.rest;
+
+import eu.dasish.annotation.backend.Resource;
+import eu.dasish.annotation.backend.dao.DBIntegrityService;
+import eu.dasish.annotation.backend.TestBackendConstants;
+import eu.dasish.annotation.backend.TestInstances;
+import eu.dasish.annotation.schema.Action;
+import eu.dasish.annotation.schema.ActionList;
+import eu.dasish.annotation.schema.AnnotationBody;
+import eu.dasish.annotation.schema.AnnotationBody.TextBody;
+import eu.dasish.annotation.schema.TargetInfo;
+import eu.dasish.annotation.schema.TargetInfoList;
+import eu.dasish.annotation.schema.Annotation;
+import eu.dasish.annotation.schema.ObjectFactory;
+import eu.dasish.annotation.schema.ResponseBody;
+import eu.dasish.annotation.schema.AnnotationActionName;
+import java.io.IOException;
+import java.sql.SQLException;
+import javax.xml.bind.JAXBElement;
+import org.jmock.Expectations;
+import org.jmock.Mockery;
+import org.junit.Test;
+import static org.junit.Assert.*;
+import org.junit.runner.RunWith;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+import java.lang.InstantiationException;
+import java.net.URI;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.UUID;
+import javax.servlet.ServletException;
+import javax.ws.rs.core.UriInfo;
+import javax.xml.bind.JAXBException;
+import javax.xml.datatype.DatatypeConfigurationException;
+import javax.xml.datatype.DatatypeFactory;
+import org.springframework.mock.web.MockHttpServletRequest;
+
+/**
+ *
+ * @author olhsha
+ */
+@RunWith(value = SpringJUnit4ClassRunner.class)
+@ContextConfiguration(locations = {"/spring-test-config/mockeryRest.xml", "/spring-test-config/mockDBIntegrityService.xml",
+    "/spring-test-config/mockUriInfo.xml",
+    "/spring-config/jaxbMarshallerFactory.xml"})
+public class AnnotationResourceTest {
+
+    @Autowired
+    private Mockery mockeryRest;
+    @Autowired
+    private DBIntegrityService mockDbIntegrityService;
+    @Autowired
+    UriInfo mockUriInfo;
+    @Autowired
+    private AnnotationResource annotationResource;
+    private MockHttpServletRequest mockRequest;
+
+    public AnnotationResourceTest() {
+        mockRequest = new MockHttpServletRequest();
+    }
+    
+   
+    @Test
+    public void testGetAnnotation() throws SQLException, JAXBException, Exception {
+        System.out.println("getAnnotation");
+        final String externalIDstring = "00000000-0000-0000-0000-000000000021";
+        final Annotation expectedAnnotation = (new TestInstances(null)).getAnnotationOne();
+        annotationResource.setHttpServletRequest(mockRequest);
+        annotationResource.setUriInfo(mockUriInfo);
+
+
+        mockeryRest.checking(new Expectations() {
+            {  
+                oneOf(mockDbIntegrityService).getRemoteUser();
+                will(returnValue("olhsha@mpi.nl"));
+                        
+                oneOf(mockDbIntegrityService).getUserInternalIDFromRemoteID("olhsha@mpi.nl");
+                will(returnValue(3));
+
+                oneOf(mockDbIntegrityService).getResourceInternalIdentifier(with(aNonNull(UUID.class)), with(aNonNull((Resource.class))));
+                will(returnValue(1));
+ 
+
+                oneOf(mockDbIntegrityService).canRead(3, 1);
+                will(returnValue(true));
+
+                oneOf(mockDbIntegrityService).getAnnotation(1);
+                will(returnValue(expectedAnnotation));
+            }
+        });
+
+
+        JAXBElement<Annotation> result = annotationResource.getAnnotation(externalIDstring);
+        assertTrue(expectedAnnotation.equals(result.getValue()));
+    }
+
+    /**
+     * Test of deleteAnnotation method, of class AnnotationResource.
+     */
+    @Test
+    public void testDeleteAnnotation() throws SQLException, IOException {
+        System.out.println("deleteAnnotation");
+
+        final int[] mockDelete = new int[4];
+        mockDelete[0] = 1; // # deleted annotations
+        mockDelete[3] = 1; // # deleted annotation_prinipal_permissions
+        mockDelete[2] = 2; // # deleted  annotations_target_Targets, (4,3), (4,4)
+        mockDelete[3] = 1; // # deletd Targets, 4
+
+        annotationResource.setHttpServletRequest(mockRequest);
+        annotationResource.setUriInfo(mockUriInfo);
+
+        mockeryRest.checking(new Expectations() {
+            {
+                oneOf(mockDbIntegrityService).getRemoteUser();
+                will(returnValue("olhsha@mpi.nl"));
+                
+                oneOf(mockDbIntegrityService).getUserInternalIDFromRemoteID("olhsha@mpi.nl");
+                will(returnValue(3));
+
+                oneOf(mockDbIntegrityService).getResourceInternalIdentifier(with(aNonNull(UUID.class)), with(aNonNull((Resource.class))));
+                will(returnValue(4));
+
+
+                oneOf(mockDbIntegrityService).getAnnotationOwnerID(4);
+                will(returnValue(3));
+
+                oneOf(mockDbIntegrityService).deleteAnnotation(4);
+                will(returnValue(mockDelete));
+            }
+        });
+
+
+        String result = annotationResource.deleteAnnotation("00000000-0000-0000-0000-000000000024");
+        assertEquals("1 annotation(s) deleted.", result);
+    }
+
+    /**
+     * Test of createAnnotation method, of class AnnotationResource.
+     */
+    @Test
+    public void testCreateAnnotation() throws SQLException, InstantiationException, IllegalAccessException, ServletException, DatatypeConfigurationException, Exception {
+        System.out.println("test createAnnotation");
+
+        final Annotation annotationToAdd = new Annotation();
+        final Number newAnnotationID = 6;
+
+        TargetInfoList TargetInfoList = new TargetInfoList();
+        annotationToAdd.setTargets(TargetInfoList);
+        annotationToAdd.setOwnerRef(null);
+        annotationToAdd.setLastModified(DatatypeFactory.newInstance().newXMLGregorianCalendar("2013-08-12T09:25:00.383000Z"));
+        annotationToAdd.setHeadline("headline");
+        annotationToAdd.setTargets(TargetInfoList);
+
+
+        AnnotationBody body = new AnnotationBody();
+        annotationToAdd.setBody(body);
+        TextBody textBody = new TextBody();
+        body.setTextBody(textBody);
+        textBody.setMimeType("text/plain");
+        textBody.setBody("blah");
+
+        TargetInfo TargetInfo = new TargetInfo();
+        TargetInfo.setLink("google.nl");
+        TargetInfo.setRef(UUID.randomUUID().toString());
+        TargetInfo.setVersion("vandaag");
+
+        final List<String> targets = new ArrayList<String>();
+        targets.add("http://localhost:8080/annotator-backend/api/targets/00000000-0000-0000-0000-000000000036");
+
+        final Annotation addedAnnotation = (new ObjectFactory()).createAnnotation(annotationToAdd).getValue();
+        addedAnnotation.setURI("http://localhost:8080/annotator-backend/api/annotations/" + UUID.randomUUID().toString());
+        addedAnnotation.setOwnerRef("http://localhost:8080/annotator-backend/api/users/" + "00000000-0000-0000-0000-000000000111");
+
+        final ResponseBody mockEnvelope = new ResponseBody();
+        final Action action = new Action();
+        final ActionList actionList = new ActionList();
+        mockEnvelope.setAnnotation(addedAnnotation);
+        mockEnvelope.setActionList(actionList);
+        actionList.getAction().add(action);
+        action.setMessage(AnnotationActionName.CREATE_CACHED_REPRESENTATION.value());
+        action.setObject("http://localhost:8080/annotator-backend/api/targets/00000000-0000-0000-0000-000000000036");
+
+        annotationResource.setHttpServletRequest(mockRequest);
+        annotationResource.setUriInfo(mockUriInfo);
+
+        mockeryRest.checking(new Expectations() {
+            {
+                oneOf(mockDbIntegrityService).getRemoteUser();
+                will(returnValue("olhsha@mpi.nl"));
+                
+             
+                oneOf(mockDbIntegrityService).getUserInternalIDFromRemoteID("olhsha@mpi.nl");
+                will(returnValue(3));
+
+                oneOf(mockDbIntegrityService).addUsersAnnotation(3, annotationToAdd);
+                will(returnValue(newAnnotationID));
+
+                oneOf(mockDbIntegrityService).getAnnotation(newAnnotationID);
+                will(returnValue(addedAnnotation));
+
+                oneOf(mockDbIntegrityService).getTargetsWithNoCachedRepresentation(newAnnotationID);
+                will(returnValue(targets));
+
+                oneOf(mockDbIntegrityService).makeAnnotationResponseEnvelope(newAnnotationID);
+                will(returnValue(mockEnvelope));
+
+            }
+        });
+
+
+
+        JAXBElement<ResponseBody> result = annotationResource.createAnnotation(annotationToAdd);
+        Annotation newAnnotation = result.getValue().getAnnotation();
+        String actionName = result.getValue().getActionList().getAction().get(0).getMessage();
+        assertEquals(addedAnnotation.getOwnerRef(), newAnnotation.getOwnerRef());
+        assertEquals(addedAnnotation.getURI(), newAnnotation.getURI());
+        assertEquals(addedAnnotation.getHeadline(), newAnnotation.getHeadline());
+        assertEquals(addedAnnotation.getTargets(), newAnnotation.getTargets());
+        assertEquals(addedAnnotation.getLastModified(), newAnnotation.getLastModified());
+        assertEquals(addedAnnotation.getBody(), newAnnotation.getBody());
+        assertEquals(AnnotationActionName.CREATE_CACHED_REPRESENTATION.value(), actionName);
+    }
+}
Index: /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/test/java/eu/dasish/annotation/backend/rest/AnnotationsTest.java
===================================================================
--- /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/test/java/eu/dasish/annotation/backend/rest/AnnotationsTest.java	(revision 4603)
+++ /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/test/java/eu/dasish/annotation/backend/rest/AnnotationsTest.java	(revision 4603)
@@ -0,0 +1,245 @@
+/*
+ * Copyright (C) 2013 DASISH
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
+ */
+package eu.dasish.annotation.backend.rest;
+
+import com.sun.jersey.api.client.ClientResponse;
+import com.sun.jersey.api.client.WebResource;
+import com.sun.jersey.api.client.WebResource.Builder;
+import com.sun.jersey.core.util.Base64;
+import com.sun.jersey.spi.spring.container.servlet.SpringServlet;
+import com.sun.jersey.test.framework.AppDescriptor;
+import com.sun.jersey.test.framework.JerseyTest;
+import com.sun.jersey.test.framework.WebAppDescriptor;
+import eu.dasish.annotation.backend.TestBackendConstants;
+import eu.dasish.annotation.backend.TestInstances;
+import eu.dasish.annotation.backend.dao.impl.JdbcResourceDaoTest;
+import eu.dasish.annotation.schema.Annotation;
+import eu.dasish.annotation.schema.AnnotationBody;
+import eu.dasish.annotation.schema.AnnotationBody.TextBody;
+import eu.dasish.annotation.schema.ObjectFactory;
+import eu.dasish.annotation.schema.ResponseBody;
+import eu.dasish.annotation.schema.TargetInfo;
+import eu.dasish.annotation.schema.TargetInfoList;
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.net.URISyntaxException;
+import java.net.URL;
+import java.sql.SQLException;
+import java.util.Scanner;
+import java.util.UUID;
+import javax.ws.rs.core.HttpHeaders;
+import javax.ws.rs.core.MediaType;
+import javax.xml.bind.JAXBElement;
+import javax.xml.datatype.DatatypeConfigurationException;
+import javax.xml.datatype.DatatypeFactory;
+import org.junit.Test;
+import static org.junit.Assert.*;
+import org.junit.Before;
+import org.junit.runner.RunWith;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.dao.DataAccessException;
+import org.springframework.jdbc.core.JdbcTemplate;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+import org.springframework.web.context.ContextLoaderListener;
+import org.springframework.web.context.request.RequestContextListener;
+
+/**
+ *
+ * @author olhsha
+ */
+@RunWith(value = SpringJUnit4ClassRunner.class)
+@ContextConfiguration({"/spring-test-config/dataSource.xml"})
+public class AnnotationsTest extends JerseyTest {    
+    
+    @Autowired
+    private JdbcTemplate jdbcTemplate;
+    
+    
+    
+    
+    @Override
+    protected AppDescriptor configure() {
+       return new WebAppDescriptor.Builder(AnnotationResource.class.getPackage().getName())
+                .servletClass(SpringServlet.class)
+                .contextParam("contextConfigLocation", getApplicationContextFile())
+                .addFilter(DummySecurityFilter.class, "DummySecurityFilter")
+                .requestListenerClass(RequestContextListener.class)
+                .contextListenerClass(ContextLoaderListener.class)
+                .build();
+        
+    }
+    
+    private String getApplicationContextFile() {
+	// sorry for the duplication, but JerseyTest is not aware of
+	// @ContextConfiguration
+	return "classpath:spring-config/componentscan.xml, classpath:spring-config/notebookDao.xml, classpath:spring-config/annotationDao.xml, classpath:spring-config/userDao.xml, classpath:spring-config/targetDao.xml, classpath:spring-config/cachedRepresentationDao.xml, classpath:spring-config/dbIntegrityService.xml, classpath:spring-config/jaxbMarshallerFactory.xml, classpath:spring-test-config/dataSource.xml";
+    }
+    
+    
+    
+    @Override
+    @Before
+    public void setUp() throws DataAccessException, FileNotFoundException, URISyntaxException, Exception {
+        super.setUp();
+        jdbcTemplate.execute("DROP SCHEMA PUBLIC CASCADE");
+        // consume the DashishAnnotatorCreate sql script to create the database
+        jdbcTemplate.execute(JdbcResourceDaoTest.getNormalisedSql());
+        jdbcTemplate.execute(JdbcResourceDaoTest.getTestDataInsertSql());
+    }
+
+    
+    @Override
+    public void tearDown() throws Exception {
+        super.tearDown();
+    }
+    /**
+     * Test of getAnnotation method, of class annotationResource. Get <aid>. GET
+     * api/annotations/<aid>
+     */
+    @Test
+    public void testGetAnnotation() throws SQLException, DatatypeConfigurationException {
+        
+        // Authentication  
+        Builder responseBuilderAu = getAuthenticatedResource(resource().path("authentication/login")).accept(MediaType.TEXT_XML);        
+        ClientResponse responseAu = responseBuilderAu.get(ClientResponse.class); 
+        assertEquals(200, responseAu.getStatus());
+        
+        // Getting annotation
+        System.out.println("testGetAnnotation");
+        final String externalIDstring = "00000000-0000-0000-0000-000000000021";
+        final Annotation testAnnotation = (new TestInstances(resource().getURI().toString())).getAnnotationOne();        
+        
+        final String requestUrl = "annotations/" + externalIDstring;
+        System.out.println("requestUrl: " + requestUrl);
+        
+        Builder responseBuilder = getAuthenticatedResource(resource().path(requestUrl)).accept(MediaType.TEXT_XML);        
+        ClientResponse response = responseBuilder.get(ClientResponse.class);        
+        
+        
+        assertEquals(200, response.getStatus());
+        Annotation entity = response.getEntity(Annotation.class);
+        assertEquals(testAnnotation.getBody().getTextBody().getBody(), entity.getBody().getTextBody().getBody());
+        assertEquals(testAnnotation.getHeadline(), entity.getHeadline());
+        assertEquals(testAnnotation.getOwnerRef(), entity.getOwnerRef());
+        assertEquals(2, entity.getPermissions().getUserWithPermission().size());
+        assertEquals("writer", entity.getPermissions().getUserWithPermission().get(0).getPermission().value());
+        assertEquals(resource().getURI()+"users/"+"00000000-0000-0000-0000-000000000112", entity.getPermissions().getUserWithPermission().get(0).getRef()); 
+        assertEquals("reader", entity.getPermissions().getUserWithPermission().get(1).getPermission().value()); 
+        assertEquals(resource().getURI()+"users/"+"00000000-0000-0000-0000-000000000113", entity.getPermissions().getUserWithPermission().get(1).getRef()); 
+        assertEquals(2, entity.getTargets().getTargetInfo().size());
+        assertEquals(resource().getURI().toString()+"targets/"+"00000000-0000-0000-0000-000000000031", entity.getTargets().getTargetInfo().get(0).getRef());
+        assertEquals(resource().getURI().toString()+"targets/"+"00000000-0000-0000-0000-000000000032", entity.getTargets().getTargetInfo().get(1).getRef());
+        assertEquals(testAnnotation.getLastModified(), entity.getLastModified());
+        assertEquals(resource().getURI()+requestUrl, entity.getURI());
+    }
+
+    /**
+     * Test of deleteAnnotation method, of class AnnotationResource. Delete
+     * <nid>. DELETE api/annotations/<aid>
+     */
+    @Test
+    public void testDeleteAnnotation() throws SQLException {
+        
+          
+        // Authentication  
+        Builder responseBuilderAu = getAuthenticatedResource(resource().path("authentication/login")).accept(MediaType.TEXT_XML);        
+        ClientResponse responseAu = responseBuilderAu.get(ClientResponse.class); 
+        assertEquals(200, responseAu.getStatus());
+        
+        // Deleting annotation 
+        System.out.println("testDeleteAnnotation");
+        String externalIDstring  =  "00000000-0000-0000-0000-000000000024";
+        final String requestUrl = "annotations/" + externalIDstring;
+        System.out.println("requestUrl: " + requestUrl);
+        
+        Builder responseBuilder = getAuthenticatedResource(resource().path(requestUrl)).accept(MediaType.TEXT_XML);        
+        ClientResponse response = responseBuilder.delete(ClientResponse.class);   
+        assertEquals(200, response.getStatus());
+        assertEquals("1 annotation(s) deleted.", response.getEntity(String.class));
+    }
+
+    /**
+     * Test of createAnnotation method, of class AnnotationResource. POST
+     * api/annotations/
+     */
+    @Test
+    public void testCreateAnnotation() throws SQLException, InstantiationException, IllegalAccessException, DatatypeConfigurationException, Exception {
+        
+          
+        // Authentication  
+        Builder responseBuilderAu = getAuthenticatedResource(resource().path("authentication/login")).accept(MediaType.TEXT_XML);        
+        ClientResponse responseAu = responseBuilderAu.get(ClientResponse.class); 
+        assertEquals(200, responseAu.getStatus());
+        
+        
+        // Adding annotation
+        System.out.println("test createAnnotation");
+        System.out.println("POST "+resource().getURI().toString()+"annotations/");
+        final String ownerString = resource().getURI().toString()+"users/"+"00000000-0000-0000-0000-000000000113";
+        final Annotation annotationToAdd = new Annotation();
+        final JAXBElement<Annotation> jaxbElement = (new ObjectFactory()).createAnnotation(annotationToAdd);
+        annotationToAdd.setPermissions(null);
+        annotationToAdd.setOwnerRef(ownerString);
+        annotationToAdd.setURI(resource().getURI().toString()+"annotations/"+ UUID.randomUUID().toString());        
+        annotationToAdd.setLastModified(DatatypeFactory.newInstance().newXMLGregorianCalendar("2013-08-12T09:25:00.383000Z"));        
+        
+        TargetInfoList targetInfoList = new TargetInfoList();
+        annotationToAdd.setTargets(targetInfoList);
+        TargetInfo targetInfo = new TargetInfo();
+        targetInfo.setLink("http://nl.wikipedia.org/wiki/Viktor_Janoekovytsj#Biografie");
+        targetInfo.setRef(resource().getURI().toString()+"targets/"+UUID.randomUUID().toString());
+        targetInfo.setVersion("5 apr 2013 om 18:42");
+        targetInfoList.getTargetInfo().add(targetInfo);       
+        
+        AnnotationBody annotationBody = new AnnotationBody();
+        annotationBody.setXmlBody(null);
+        TextBody textBody = new TextBody();
+        textBody.setMimeType("plain/text");
+        textBody.setBody("yanuk - zek");
+        annotationBody.setTextBody(textBody);
+        annotationToAdd.setBody(annotationBody);
+      
+        Builder responseBuilder = getAuthenticatedResource(resource().path("annotations/")).type(MediaType.APPLICATION_XML).accept(MediaType.APPLICATION_XML);        
+        ClientResponse response = responseBuilder.post(ClientResponse.class, jaxbElement);
+        assertEquals(200, response.getStatus());
+        
+        ResponseBody entity = response.getEntity(ResponseBody.class);        
+        Annotation entityA = entity.getAnnotation();
+        assertEquals(annotationToAdd.getBody().getTextBody().getBody(), entityA.getBody().getTextBody().getBody());
+        assertEquals(annotationToAdd.getBody().getTextBody().getMimeType(), entityA.getBody().getTextBody().getMimeType());
+        assertEquals(annotationToAdd.getHeadline(), entityA.getHeadline());
+        assertEquals(0, entityA.getPermissions().getUserWithPermission().size());
+        assertEquals(annotationToAdd.getOwnerRef(), entityA.getOwnerRef());
+        assertEquals(annotationToAdd.getTargets().getTargetInfo().get(0).getLink(), entityA.getTargets().getTargetInfo().get(0).getLink());
+        // new ref is generated
+        //assertEquals(annotationToAdd.getTargets().getTargetInfo().get(0).getRef(), entityA.getTargets().getTargetInfo().get(0).getRef());
+        assertEquals(annotationToAdd.getTargets().getTargetInfo().get(0).getVersion(), entityA.getTargets().getTargetInfo().get(0).getVersion());
+        //last modified is updated by the server
+        //assertEquals(annotationToAdd.getLastModified(), entityA.getLastModified());
+        assertEquals(annotationToAdd.getOwnerRef(), entityA.getOwnerRef());
+    }
+    
+    
+   
+    protected Builder getAuthenticatedResource(WebResource resource) {
+	return resource.header(HttpHeaders.AUTHORIZATION, "Basic "  + new String(Base64.encode(DummyPrincipal.DUMMY_PRINCIPAL.getName()+":olhapassword")));
+    }
+    
+    
+}
Index: /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/test/java/eu/dasish/annotation/backend/rest/DummyPrincipal.java
===================================================================
--- /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/test/java/eu/dasish/annotation/backend/rest/DummyPrincipal.java	(revision 4603)
+++ /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/test/java/eu/dasish/annotation/backend/rest/DummyPrincipal.java	(revision 4603)
@@ -0,0 +1,56 @@
+/*
+ * Copyright (C) 2013 DASISH
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
+ */
+package eu.dasish.annotation.backend.rest;
+
+/**
+ *
+ * @author olhsha
+ */
+
+import java.security.Principal;
+
+
+public final class DummyPrincipal implements Principal {
+
+    public static final DummyPrincipal DUMMY_ADMIN_PRINCIPAL = new DummyPrincipal("JUnit.Admin@test.com");
+    public static final DummyPrincipal DUMMY_PRINCIPAL = new DummyPrincipal("olhsha@mpi.nl");
+    public static final UserCredentials DUMMY_CREDENTIALS = new UserCredentials(DUMMY_PRINCIPAL) {
+
+	@Override
+	public String getDisplayName() {
+	    return "J.Unit";
+	}
+    };
+    
+    public static final UserCredentials DUMMY_ADMIN_CREDENTIALS = new UserCredentials(DUMMY_ADMIN_PRINCIPAL);
+    
+    private final String username;
+
+    public DummyPrincipal(String username) {
+	this.username = username;
+    }
+
+    @Override
+    public String getName() {
+	return username;
+    }
+
+    public UserCredentials getCredentials() {
+	return new UserCredentials(this);
+    }
+}
Index: /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/test/java/eu/dasish/annotation/backend/rest/DummySecurityFilter.java
===================================================================
--- /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/test/java/eu/dasish/annotation/backend/rest/DummySecurityFilter.java	(revision 4603)
+++ /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/test/java/eu/dasish/annotation/backend/rest/DummySecurityFilter.java	(revision 4603)
@@ -0,0 +1,123 @@
+/*
+ * Copyright (C) 2013 DASISH
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
+ */
+package eu.dasish.annotation.backend.rest;
+
+/**
+ *
+ * @author olhsha
+ */
+import java.io.IOException;
+import java.security.Principal;
+import java.util.Arrays;
+import java.util.List;
+
+import javax.naming.AuthenticationException;
+import javax.servlet.Filter;
+import javax.servlet.FilterChain;
+import javax.servlet.FilterConfig;
+import javax.servlet.ServletException;
+import javax.servlet.ServletRequest;
+import javax.servlet.ServletResponse;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletRequestWrapper;
+import javax.ws.rs.core.HttpHeaders;
+
+import com.sun.jersey.api.container.MappableContainerException;
+import com.sun.jersey.core.util.Base64;
+
+/**
+ * Dummy security filter, very handy for unit testing.
+ *
+ */
+public class DummySecurityFilter implements Filter {
+
+    private final List<String> ALLOWED_USERS = Arrays.asList(DummyPrincipal.DUMMY_PRINCIPAL.getName());
+
+    /**
+     * Dummy validation for unit tests
+     *
+     * @param username
+     * @param password
+     * @return
+     */
+    private boolean isValid(String username, String password) {
+        return ALLOWED_USERS.contains(username);
+    }
+
+    @Override
+    public void destroy() {
+    }
+
+    @Override
+    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
+        Principal principalResult = null;
+        HttpServletRequest req = (HttpServletRequest) request;
+        String authentication = req.getHeader(HttpHeaders.AUTHORIZATION);
+
+        if (authentication != null) { //if no authentication then do nothing
+            if (!authentication.startsWith("Basic ")) {
+                throw new MappableContainerException(new AuthenticationException("Only HTTP Basic authentication is supported"));
+            }
+            authentication = authentication.substring("Basic ".length());
+            String base64Decode = new String(Base64.decode(authentication.getBytes()));
+            String[] values = base64Decode.split(":");
+            if (values.length < 2) {
+                throw new MappableContainerException(new AuthenticationException("Invalid syntax for username and password"));
+            }
+            final String username = values[0];
+            String password = values[1];
+            if ((username == null) || (password == null)) {
+                throw new MappableContainerException(new AuthenticationException("Missing username or password"));
+            }
+            if (!isValid(username, password)) {
+                throw new MappableContainerException(new AuthenticationException("Invalid user/password"));
+            }
+            principalResult = new DummyPrincipal(username);
+        }
+        final Principal principal = principalResult;
+        HttpServletRequestWrapper wrapper = new HttpServletRequestWrapper(req) {
+            public boolean isUserInRole(String role) {
+                return true;
+            }
+
+            public boolean isSecure() {
+                return false;
+            }
+
+            public Principal getUserPrincipal() {
+                return principal;
+            }
+
+            @Override
+            public String getAuthType() {
+                return HttpServletRequest.BASIC_AUTH;
+            }
+
+            @Override
+            public String getRemoteUser() {
+                return principal.getName();
+            }
+        };
+
+        chain.doFilter(wrapper, response);
+    }
+
+    @Override
+    public void init(FilterConfig filterConfig) throws ServletException {
+    }
+}
Index: /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/test/java/eu/dasish/annotation/backend/rest/NotebookResourceTest.java
===================================================================
--- /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/test/java/eu/dasish/annotation/backend/rest/NotebookResourceTest.java	(revision 4603)
+++ /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/test/java/eu/dasish/annotation/backend/rest/NotebookResourceTest.java	(revision 4603)
@@ -0,0 +1,183 @@
+/*
+ * Copyright (C) 2013 DASISH
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
+ */
+package eu.dasish.annotation.backend.rest;
+
+import eu.dasish.annotation.backend.dao.DBIntegrityService;
+import org.jmock.Mockery;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+
+/**
+ *
+ * @author Peter Withers <peter.withers@mpi.nl>
+ */
+@RunWith(value = SpringJUnit4ClassRunner.class)
+@ContextConfiguration(locations = {"/spring-test-config/mockeryRest.xml", "/spring-test-config/mockDBIntegrityService.xml", "/spring-config/jaxbMarshallerFactory.xml",
+    "/spring-test-config/mockUriInfo.xml"})
+public class NotebookResourceTest {
+
+    @Autowired
+    private Mockery mockeryRest;
+    @Autowired
+    private DBIntegrityService daoDispatcher;
+    @Autowired
+    private NotebookResource notebookResource;
+
+    public NotebookResourceTest() {
+    }
+    
+    @Test
+    public void dummy(){
+        
+    }
+//
+//    /**
+//     * Test of getNotebookInfo method, of class NotebookResource.
+//     */
+//    @Test
+//    public void testGetNotebookInfo() {
+//        System.out.println("getNotebookInfo");
+//        final MockHttpServletRequest httpServletRequest = new MockHttpServletRequest();
+//        httpServletRequest.setRemoteUser(TestBackendConstants._TEST_UID_1_);  
+//        
+//        
+//        mockery.checking(new Expectations() {
+//            {
+//                oneOf(notebookDao).getNotebookInfos(UUID.fromString(httpServletRequest.getRemoteUser()));                
+//                will(returnValue(new ArrayList<NotebookInfo>()));
+//            }
+//        });
+//        JAXBElement<NotebookInfoList> result = notebookResource.getNotebookInfo(httpServletRequest);
+//        assertEquals(0, result.getValue().getNotebook().size()); // todo: shoudnt this return 3 infos?
+//    }
+//
+//    /**
+//     * Test of getUsersNotebooks method, of class NotebookResource.
+//     */
+//    @Test
+//    public void testGetUsersNotebooks() {
+//        System.out.println("getUsersNotebooks");
+//        mockery.checking(new Expectations() {
+//            {
+//                oneOf(notebookDao).getUsersNotebooks(UUID.fromString(TestBackendConstants._TEST_UID_2_));
+//                will(returnValue(new ArrayList<Notebook>()));
+//            }
+//        });
+//        final MockHttpServletRequest httpServletRequest = new MockHttpServletRequest();
+//        httpServletRequest.setRemoteUser(TestBackendConstants._TEST_UID_2_); 
+//        List result = notebookResource.getUsersNotebooks(httpServletRequest);
+//        assertEquals(0, result.size());
+//    }
+//
+//    /**
+//     * Test of createNotebook method, of class NotebookResource.
+//     */
+//    @Test
+//    public void testCreateNotebook() throws Exception {
+//        System.out.println("createNotebook");
+//        final MockHttpServletRequest httpServletRequest = new MockHttpServletRequest();
+//        httpServletRequest.setRemoteUser(TestBackendConstants._TEST_UID_2_);
+//        
+//        mockery.checking(new Expectations() {
+//            {
+//                oneOf(notebookDao).addNotebook(UUID.fromString(httpServletRequest.getRemoteUser()), null);
+//                will(returnValue(UUID.fromString(TestBackendConstants._TEST_NOTEBOOK_1_EXT_ID)));
+//            }
+//        });
+//        String expResult = "/api/notebooks/00000000-0000-0000-0000-000000000001";
+//        String result = notebookResource.createNotebook(httpServletRequest);  
+//        assertEquals(expResult, result.substring(result.length() - expResult.length()));
+//    }
+//
+//    /**
+//     * Test of deleteNotebook method, of class NotebookResource.
+//     */
+//    @Test
+//    public void testDeleteNotebook() {
+//        System.out.println("deleteNotebook");
+//        final UUID externalID = UUID.fromString(TestBackendConstants._TEST_NOTEBOOK_1_EXT_ID);
+//        mockery.checking(new Expectations() {
+//            {
+//                oneOf(notebookDao).deleteNotebook(externalID);
+//                will(returnValue(1));
+//            }
+//        });
+//        String expResult = "1";
+//        String result = notebookResource.deleteNotebook(externalID);
+//        assertEquals(expResult, result);
+//    }
+//    
+//    /**
+//     * Test of getMetadata method, of class NotebookResource. Get all metadata
+//     * about a specified notebook <nid>, including the information if it is
+//     * private or not. GET api/notebooks/<nid>/metadata
+//     */
+//    @Test
+//    public void testGetMetadata() {
+//        System.out.println("test GetMetadata");
+//        
+//        final String externalID= TestBackendConstants._TEST_NOTEBOOK_3_EXT;
+//        final int notebookID = 3;
+//        final NotebookInfo testInfo = new ObjectFactory().createNotebookInfo();
+//        
+//        mockery.checking(new Expectations() {
+//            {
+//                oneOf(notebookDao).getInternalID(UUID.fromString(externalID));                
+//                will(returnValue(notebookID));
+//                
+//                oneOf(notebookDao).getNotebookInfo(notebookID); 
+//               will(returnValue(testInfo)); 
+//            }
+//        });
+//        
+//        JAXBElement<NotebookInfo> result = notebookResource.getMetadata(externalID);
+//        NotebookInfo entity = result.getValue();
+//        assertEquals(testInfo.getRef(), entity.getRef());
+//        assertEquals(testInfo.getTitle(), entity.getTitle());
+//    }
+//
+//    
+//    @Test
+//    public void testGetAllAnnotations() {
+//        System.out.println("test getAllAnnotations");        
+//        final String externalID= TestBackendConstants._TEST_NOTEBOOK_3_EXT; 
+//        final UUID aIdOne= UUID.fromString("00000000-0000-0000-0000-000000000021");
+//        final UUID aIdTwo= UUID.fromString("00000000-0000-0000-0000-000000000022");
+//        final List<UUID> annotationIds = new ArrayList<UUID>();
+//        annotationIds.add(aIdOne);
+//        annotationIds.add(aIdTwo);
+//        
+//        mockery.checking(new Expectations() {
+//            {
+//                oneOf(notebookDao).getAnnotationExternalIDs(UUID.fromString(externalID));                
+//                will(returnValue(annotationIds));
+//                
+//            }
+//        });
+//        
+//        List<JAXBElement<UUID>> result= notebookResource.getAllAnnotations(externalID, 0, 0, null, 0);
+//        assertFalse(null==result);
+//        assertEquals(aIdOne, result.get(0).getValue());
+//        assertEquals(aIdTwo, result.get(1).getValue());
+//        
+//        
+//    }
+}
Index: /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/test/java/eu/dasish/annotation/backend/rest/UserCredentials.java
===================================================================
--- /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/test/java/eu/dasish/annotation/backend/rest/UserCredentials.java	(revision 4603)
+++ /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/test/java/eu/dasish/annotation/backend/rest/UserCredentials.java	(revision 4603)
@@ -0,0 +1,97 @@
+/*
+ * Copyright (C) 2013 DASISH
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
+ */
+package eu.dasish.annotation.backend.rest;
+
+/**
+ *
+ * @author olhsha
+ */
+
+import java.security.Principal;
+//import java.util.List;
+//
+//import org.apache.commons.codec.digest.DigestUtils;
+//
+//import de.mpg.aai.shhaa.model.AuthAttribute;
+//import de.mpg.aai.shhaa.model.AuthAttributes;
+//import de.mpg.aai.shhaa.model.AuthPrincipal;
+
+/**
+ * Wrapper class to hold the userPrincipal and a displayName
+ * 
+ */
+public class UserCredentials {
+
+    private final Principal userPrincipal;
+
+    public UserCredentials(Principal userPrincipal) {
+        this.userPrincipal = userPrincipal;
+    }
+
+    public Principal getPrincipal() {
+        return userPrincipal;
+    }
+
+    public String getPrincipalName() {
+        return userPrincipal.getName();
+    }
+
+//    public String getPrincipalNameMD5Hex() {
+//        return getPrincipalNameMD5Hex(userPrincipal.getName());
+//    }
+//
+//    public static String getPrincipalNameMD5Hex(String name){
+//	return DigestUtils.md5Hex(name);
+//    }
+
+    public String getDisplayName() {
+        String result = null;
+//        if (userPrincipal instanceof AuthPrincipal) {
+//            List<String> displayNamesAttributes = Configuration.getInstance().getDisplayNameShibbolethKeys();
+//            AuthPrincipal authPrincipal = (AuthPrincipal) userPrincipal;
+//            for (String key : displayNamesAttributes) {
+//                result = getValue(authPrincipal, key);
+//                if (result != null) {
+//                    break;
+//                }
+//            }
+//        }
+        if (result == null) {
+            result = getPrincipalName();
+        }
+        return result;
+    }
+
+//    private String getValue(AuthPrincipal authPrincipal, String key) {
+//        String result = null;
+//        AuthAttributes attributes = authPrincipal.getAttribues();
+//        if (attributes != null) {
+//            AuthAttribute<String> authAttribute = (AuthAttribute<String>) attributes.get(key);
+//            if (authAttribute != null) {
+//                result = authAttribute.getValue();
+//            }
+//        }
+//        return result;
+//    }
+
+    @Override
+    public String toString() {
+	return getPrincipal().toString();
+    }
+}
+
Index: /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/test/resources/spring-test-config/dataSource.xml
===================================================================
--- /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/test/resources/spring-test-config/dataSource.xml	(revision 4603)
+++ /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/test/resources/spring-test-config/dataSource.xml	(revision 4603)
@@ -0,0 +1,38 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+
+    Copyright (C) 2013 DASISH
+
+    This program is free software; you can redistribute it and/or
+    modify it under the terms of the GNU General Public License
+    as published by the Free Software Foundation; either version 2
+    of the License, or (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License
+    along with this program; if not, write to the Free Software
+    Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+-->
+<beans xmlns="http://www.springframework.org/schema/beans"
+       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+       xmlns:context="http://www.springframework.org/schema/context"
+
+       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
+          http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
+">
+    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
+        <property name="driverClassName" value="org.hsqldb.jdbcDriver"/>
+        <property name="url" value="jdbc:hsqldb:mem:dasish_annotator;sql.syntax_pgs=true"/>
+        <property name="username" value="sa"/>
+        <property name="password" value=""/>
+    </bean>	
+    
+    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
+        <property name="dataSource" ref="dataSource"/>
+    </bean>
+</beans>
Index: /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/test/resources/spring-test-config/mockAnnotationDao.xml
===================================================================
--- /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/test/resources/spring-test-config/mockAnnotationDao.xml	(revision 4603)
+++ /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/test/resources/spring-test-config/mockAnnotationDao.xml	(revision 4603)
@@ -0,0 +1,33 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+
+    Copyright (C) 2013 DASISH
+
+    This program is free software; you can redistribute it and/or
+    modify it under the terms of the GNU General Public License
+    as published by the Free Software Foundation; either version 2
+    of the License, or (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License
+    along with this program; if not, write to the Free Software
+    Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+-->
+<beans xmlns="http://www.springframework.org/schema/beans"
+       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+       xmlns:context="http://www.springframework.org/schema/context"
+
+       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
+          http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
+">
+    <!-- Context for testing the annotations service with mock implementations -->
+	   
+    <!-- Mocked annotations -->
+    <bean id="annotationDao" factory-bean="mockObjectsFactoryDao" factory-method="newAnnotationDao" />
+    
+</beans>
Index: /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/test/resources/spring-test-config/mockCachedRepresentationDao.xml
===================================================================
--- /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/test/resources/spring-test-config/mockCachedRepresentationDao.xml	(revision 4603)
+++ /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/test/resources/spring-test-config/mockCachedRepresentationDao.xml	(revision 4603)
@@ -0,0 +1,31 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+
+    Copyright (C) 2013 DASISH
+
+    This program is free software; you can redistribute it and/or
+    modify it under the terms of the GNU General Public License
+    as published by the Free Software Foundation; either version 2
+    of the License, or (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License
+    along with this program; if not, write to the Free Software
+    Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+-->
+<beans xmlns="http://www.springframework.org/schema/beans"
+       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+
+       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
+">
+    <!-- Context for testing the annotations service with mock implementations -->
+	   
+    <!-- Mocked cached repreenttaions -->
+    <bean id="cachedRepresentationDao" factory-bean="mockObjectsFactoryDao" factory-method="newCachedRepresentationDao" />
+    
+</beans>
Index: /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/test/resources/spring-test-config/mockDBIntegrityService.xml
===================================================================
--- /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/test/resources/spring-test-config/mockDBIntegrityService.xml	(revision 4603)
+++ /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/test/resources/spring-test-config/mockDBIntegrityService.xml	(revision 4603)
@@ -0,0 +1,33 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+
+    Copyright (C) 2013 DASISH
+
+    This program is free software; you can redistribute it and/or
+    modify it under the terms of the GNU General Public License
+    as published by the Free Software Foundation; either version 2
+    of the License, or (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License
+    along with this program; if not, write to the Free Software
+    Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+-->
+<beans xmlns="http://www.springframework.org/schema/beans"
+       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+       xmlns:context="http://www.springframework.org/schema/context"
+
+       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
+          http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
+">
+    <!-- Context for testing the dispatcher service with mock implementations -->
+	   
+    <!-- Mocked dispatcher -->
+    <bean id="dbIntegrityService" factory-bean="mockObjectsFactoryRest" factory-method="newDBIntegrityService" />
+    
+</beans>
Index: /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/test/resources/spring-test-config/mockNotebookDao.xml
===================================================================
--- /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/test/resources/spring-test-config/mockNotebookDao.xml	(revision 4603)
+++ /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/test/resources/spring-test-config/mockNotebookDao.xml	(revision 4603)
@@ -0,0 +1,35 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+
+    Copyright (C) 2013 DASISH
+
+    This program is free software; you can redistribute it and/or
+    modify it under the terms of the GNU General Public License
+    as published by the Free Software Foundation; either version 2
+    of the License, or (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License
+    along with this program; if not, write to the Free Software
+    Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+-->
+<beans xmlns="http://www.springframework.org/schema/beans"
+       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+       xmlns:context="http://www.springframework.org/schema/context"
+
+       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
+          http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
+">
+
+    
+    <!-- Context for testing the notebooks service with mock implementations -->
+	   
+    <!-- Mocked notebooks -->
+    <bean id="notebookDao" factory-bean="mockObjectsFactoryDao" factory-method="newNotebookDao" />
+    
+</beans>
Index: /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/test/resources/spring-test-config/mockProviders.xml
===================================================================
--- /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/test/resources/spring-test-config/mockProviders.xml	(revision 4603)
+++ /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/test/resources/spring-test-config/mockProviders.xml	(revision 4603)
@@ -0,0 +1,31 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+
+    Copyright (C) 2013 DASISH
+
+    This program is free software; you can redistribute it and/or
+    modify it under the terms of the GNU General Public License
+    as published by the Free Software Foundation; either version 2
+    of the License, or (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License
+    along with this program; if not, write to the Free Software
+    Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+-->
+<beans xmlns="http://www.springframework.org/schema/beans"
+       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+
+       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
+">
+   <!-- Context for testing the sources service with mock implementations -->
+	   
+    
+    <bean id="mockProviders" factory-bean="mockObjectsFactoryRest" factory-method="newProviders" />
+    
+</beans>
Index: /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/test/resources/spring-test-config/mockTargetDao.xml
===================================================================
--- /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/test/resources/spring-test-config/mockTargetDao.xml	(revision 4603)
+++ /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/test/resources/spring-test-config/mockTargetDao.xml	(revision 4603)
@@ -0,0 +1,31 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+
+    Copyright (C) 2013 DASISH
+
+    This program is free software; you can redistribute it and/or
+    modify it under the terms of the GNU General Public License
+    as published by the Free Software Foundation; either version 2
+    of the License, or (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License
+    along with this program; if not, write to the Free Software
+    Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+-->
+<beans xmlns="http://www.springframework.org/schema/beans"
+       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+
+       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
+">
+<!-- Context for testing the sources service with mock implementations -->
+	   
+    <!-- Mocked sources -->
+    <bean id="targetDao" factory-bean="mockObjectsFactoryDao" factory-method="newTargetDao" />
+    
+</beans>
Index: /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/test/resources/spring-test-config/mockUriInfo.xml
===================================================================
--- /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/test/resources/spring-test-config/mockUriInfo.xml	(revision 4603)
+++ /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/test/resources/spring-test-config/mockUriInfo.xml	(revision 4603)
@@ -0,0 +1,31 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+
+    Copyright (C) 2013 DASISH
+
+    This program is free software; you can redistribute it and/or
+    modify it under the terms of the GNU General Public License
+    as published by the Free Software Foundation; either version 2
+    of the License, or (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License
+    along with this program; if not, write to the Free Software
+    Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+-->
+<beans xmlns="http://www.springframework.org/schema/beans"
+       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+
+       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
+">
+   <!-- Context for testing the sources service with mock implementations -->
+	   
+    
+    <bean id="mockUriInfo" factory-bean="mockObjectsFactoryRest" factory-method="newUriInfo" />
+    
+</beans>
Index: /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/test/resources/spring-test-config/mockUserDao.xml
===================================================================
--- /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/test/resources/spring-test-config/mockUserDao.xml	(revision 4603)
+++ /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/test/resources/spring-test-config/mockUserDao.xml	(revision 4603)
@@ -0,0 +1,31 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+
+    Copyright (C) 2013 DASISH
+
+    This program is free software; you can redistribute it and/or
+    modify it under the terms of the GNU General Public License
+    as published by the Free Software Foundation; either version 2
+    of the License, or (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License
+    along with this program; if not, write to the Free Software
+    Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+-->
+<beans xmlns="http://www.springframework.org/schema/beans"
+       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+
+       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
+">
+   <!-- Context for testing the sources service with mock implementations -->
+	   
+    <!-- Mocked users -->
+    <bean id="userDao" factory-bean="mockObjectsFactoryDao" factory-method="newUserDao" />
+    
+</beans>
Index: /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/test/resources/spring-test-config/mockeryDao.xml
===================================================================
--- /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/test/resources/spring-test-config/mockeryDao.xml	(revision 4603)
+++ /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/test/resources/spring-test-config/mockeryDao.xml	(revision 4603)
@@ -0,0 +1,38 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+
+    Copyright (C) 2013 DASISH
+
+    This program is free software; you can redistribute it and/or
+    modify it under the terms of the GNU General Public License
+    as published by the Free Software Foundation; either version 2
+    of the License, or (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License
+    along with this program; if not, write to the Free Software
+    Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+-->
+<beans xmlns="http://www.springframework.org/schema/beans"
+       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+       xmlns:context="http://www.springframework.org/schema/context"
+
+       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
+          http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
+">
+	   
+    	 
+    <!-- Context for mocking -->
+    <bean id="mockeryDao" class="org.jmock.integration.junit4.JUnit4Mockery" />
+	   
+    <!-- Factory that creates mock objects in this mock context -->
+    <bean id="mockObjectsFactoryDao" class="eu.dasish.annotation.backend.MockObjectsFactoryDao">
+        <constructor-arg ref="mockeryDao" />
+    </bean>
+	   
+</beans>
Index: /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/test/resources/spring-test-config/mockeryRest.xml
===================================================================
--- /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/test/resources/spring-test-config/mockeryRest.xml	(revision 4603)
+++ /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/test/resources/spring-test-config/mockeryRest.xml	(revision 4603)
@@ -0,0 +1,42 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+
+    Copyright (C) 2013 DASISH
+
+    This program is free software; you can redistribute it and/or
+    modify it under the terms of the GNU General Public License
+    as published by the Free Software Foundation; either version 2
+    of the License, or (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License
+    along with this program; if not, write to the Free Software
+    Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+-->
+<beans xmlns="http://www.springframework.org/schema/beans"
+       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+       xmlns:context="http://www.springframework.org/schema/context"
+
+       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
+          http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
+">
+
+    
+   	   
+    <!-- This enables injection of the translator bean into the service object -->
+    <context:component-scan base-package="eu.dasish.annotation.backend.rest" />
+	 
+    <!-- Context for mocking -->
+    <bean id="mockeryRest" class="org.jmock.integration.junit4.JUnit4Mockery" />
+	   
+    <!-- Factory that creates mock objects in this mock context -->
+    <bean id="mockObjectsFactoryRest" class="eu.dasish.annotation.backend.MockObjectsFactoryRest">
+        <constructor-arg ref="mockeryRest" />
+    </bean>
+	   
+</beans>
Index: /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/test/resources/test-data/InsertTestData.sql
===================================================================
--- /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/test/resources/test-data/InsertTestData.sql	(revision 4603)
+++ /DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/test/resources/test-data/InsertTestData.sql	(revision 4603)
@@ -0,0 +1,131 @@
+--
+-- Copyright (C) 2013 DASISH
+--
+-- This program is free software; you can redistribute it and/or
+--
+-- Copyright (C) 2013 DASISH
+--
+-- This program is free software; you can redistribute it and/or
+-- modify it under the terms of the GNU General Public License
+-- as published by the Free Software Foundation; either version 2
+-- of the License, or (at your option) any later version.
+--
+-- This program is distributed in the hope that it will be useful,
+-- but WITHOUT ANY WARRANTY; without even the implied warranty of
+-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+-- GNU General Public License for more details.
+--
+-- You should have received a copy of the GNU General Public License
+-- along with this program; if not, write to the Free Software
+-- Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+--
+
+INSERT INTO principal (principal_name, external_id, remote_id, e_mail, account) VALUES ('Twan', '00000000-0000-0000-0000-000000000111', 'twagoo@mpi.nl', 'Twan.Goosen@mpi.nl', 'developer'); --1 
+INSERT INTO principal (principal_name, external_id, remote_id, e_mail, account) VALUES ('Peter', '00000000-0000-0000-0000-000000000112', 'petwit@mpi.nl', 'Peter.Withers@mpi.nl', 'developer'); -- 2
+INSERT INTO principal (principal_name, external_id, remote_id, e_mail, account) VALUES ('Olha', '00000000-0000-0000-0000-000000000113', 'olhsha@mpi.nl', 'Olha.Shakaravska@mpi.nl', 'admin'); -- 3
+INSERT INTO principal (principal_name, external_id, remote_id, e_mail, account) VALUES ('Eric', '00000000-0000-0000-0000-000000000114', 'ericauser@mpi.nl', 'Eric.Auer@mpi.nl', 'developer'); -- 4
+INSERT INTO principal (principal_name, external_id, remote_id, e_mail, account) VALUES ('Daan', '00000000-0000-0000-0000-000000000115', 'broeder@mpi.ml', 'Daan.Broeder@mpi.nl', 'developer'); --5 
+INSERT INTO principal (principal_name, external_id, remote_id, e_mail, account) VALUES ('Menzo', '00000000-0000-0000-0000-000000000116', 'menwin@mpi.nl', 'Menzo.Windhouwer@mpi.nl', 'developer'); -- 6
+INSERT INTO principal (principal_name, external_id, remote_id, e_mail, account) VALUES ('Przemek', '00000000-0000-0000-0000-000000000117', 'przlen@mpi,nl', 'Przemek.Lenkiewicz@mpi.nl', 'user'); -- 7
+INSERT INTO principal (principal_name, external_id, remote_id, e_mail, account) VALUES ('Stephanie', '00000000-0000-0000-0000-000000000118', 'gusrotst@gu.se', 'stephanie.roth@gu.se', 'developer'); -- 8
+INSERT INTO principal (principal_name, external_id, remote_id, e_mail, account) VALUES ('Olof', '00000000-0000-0000-0000-000000000119', 'gusolsol@gu.se', 'olof.olsson.2@gu.se', 'developer'); -- 9
+INSERT INTO principal (principal_name, external_id, remote_id, e_mail, account) VALUES ('Willem', '00000000-0000-0000-0000-000000000220', 'wilelb@mpi.nl', 'Willem.Elbers@mpi.nl', 'developer'); -- 10
+
+
+INSERT INTO notebook (title, owner_id, external_id, last_modified) VALUES ('Notebook 1', 1, '00000000-0000-0000-0000-000000000011', '2013-08-12 09:25:00.383'); -- 1
+INSERT INTO notebook (title, owner_id, external_id) VALUES ('Notebook 2', 2, '00000000-0000-0000-0000-000000000012'); --2
+INSERT INTO notebook (title, owner_id, external_id) VALUES ('Notebook 3', 3, '00000000-0000-0000-0000-000000000013'); --3
+INSERT INTO notebook (title, owner_id, external_id) VALUES ('Notebook 4', 3, '00000000-0000-0000-0000-000000000014'); --4
+
+INSERT INTO annotation (owner_id, headline,body_text, body_mimetype, external_id, last_modified, is_xml) VALUES (1, 'Sagrada Famiglia','<html><body>some html 1</body></html>', 'text/html' , '00000000-0000-0000-0000-000000000021', '2013-08-12 09:25:00.383', false); --1
+INSERT INTO annotation (owner_id, headline,body_text, body_mimetype, external_id, is_xml) VALUES (2, 'Gaudi','<html><body>some html 2</body></html>', 'text/html' , '00000000-0000-0000-0000-000000000022',false); --2
+INSERT INTO annotation (owner_id, headline,body_text, body_mimetype, external_id, is_xml) VALUES (3, 'Art Nuveau','some plain text', 'text/plain' , '00000000-0000-0000-0000-000000000023', false); --3
+INSERT INTO annotation (owner_id, headline,body_text, body_mimetype, external_id, is_xml) VALUES (3, 'Annotation to delete','<html><body>some html 4</body></html>', 'text/html' , '00000000-0000-0000-0000-000000000024',false); --4
+
+
+
+INSERT INTO notebooks_annotations (notebook_id,annotation_id) VALUES (1,1);
+INSERT INTO notebooks_annotations (notebook_id,annotation_id) VALUES (1,2);
+INSERT INTO notebooks_annotations (notebook_id,annotation_id) VALUES (2,3);
+INSERT INTO notebooks_annotations (notebook_id,annotation_id) VALUES (4,3);
+
+
+INSERT INTO target (external_id, link_uri, version, fragment_descriptor) VALUES ('00000000-0000-0000-0000-000000000031', 'http://nl.wikipedia.org/wiki/Sagrada_Fam%C3%ADlia', 'version 1.0', 'de_Opdracht'); -- 1
+INSERT INTO target (external_id, link_uri, version, fragment_descriptor) VALUES ('00000000-0000-0000-0000-000000000032', 'http://nl.wikipedia.org/wiki/Antoni_Gaud%C3%AD', 'version 1.1', 'Vroege_werk'); --2
+INSERT INTO target (external_id, link_uri, version, fragment_descriptor) VALUES ('00000000-0000-0000-0000-000000000033', 'http://en.wikipedia.org/wiki/Art_Nouveau', 'june 1013', 'Spain'); --3
+INSERT INTO target (external_id, link_uri, version, fragment_descriptor) VALUES ('00000000-0000-0000-0000-000000000034', '???', 'back up', '1111'); --4
+INSERT INTO target (external_id, link_uri, version, fragment_descriptor) VALUES ('00000000-0000-0000-0000-000000000035', '???', 'back up', '111111'); --5
+INSERT INTO target (external_id, link_uri, version, fragment_descriptor) VALUES ('00000000-0000-0000-0000-000000000036', '???', 'version 2.0', '1111111'); --6 not used by any annotation
+INSERT INTO target (external_id, link_uri, version, fragment_descriptor) VALUES ('00000000-0000-0000-0000-000000000037', '???', 'version 2.0', '11111111'); --7
+
+
+
+INSERT INTO annotations_targets (annotation_id, target_id) VALUES (1, 1); 
+INSERT INTO annotations_targets (annotation_id, target_id) VALUES (1, 2);
+INSERT INTO annotations_targets (annotation_id, target_id) VALUES (2, 2); 
+INSERT INTO annotations_targets (annotation_id, target_id) VALUES (3, 3); 
+INSERT INTO annotations_targets (annotation_id, target_id) VALUES (4, 3); -- Target 3 should not be deleted when annot 4 is deleted
+INSERT INTO annotations_targets (annotation_id, target_id) VALUES (4, 4); -- Target 4 to be deleted when annot 4 is deleted
+INSERT INTO annotations_targets (annotation_id, target_id) VALUES (3, 5); 
+INSERT INTO annotations_targets (annotation_id, target_id) VALUES (3, 7); 
+
+-- HSQL ---
+INSERT INTO cached_representation (external_id, mime_type, tool, type_, file_) VALUES ('00000000-0000-0000-0000-000000000051', 'text/html', 'latex', 'text', X'1001'); --1
+INSERT INTO cached_representation (external_id, mime_type, tool, type_, file_) VALUES ('00000000-0000-0000-0000-000000000052', 'text/html', 'vi', 'text', X'1002'); -- 2
+INSERT INTO cached_representation (external_id, mime_type, tool, type_, file_) VALUES ('00000000-0000-0000-0000-000000000053', 'image/png', 'screenshooter', 'image', X'1003'); -- 3
+INSERT INTO cached_representation (external_id, mime_type, tool, type_, file_) VALUES ('00000000-0000-0000-0000-000000000054', 'text/html', 'oxygen', 'text', X'1004'); --4 
+INSERT INTO cached_representation (external_id, mime_type, tool, type_, file_) VALUES ('00000000-0000-0000-0000-000000000055', 'image/jpg', 'photomaster', 'image', X'1005'); --5 
+INSERT INTO cached_representation (external_id, mime_type, tool, type_, file_) VALUES ('00000000-0000-0000-0000-000000000056', 'text/plain', 'some tool', 'text', X'1006'); --6  not used
+INSERT INTO cached_representation (external_id, mime_type, tool, type_, file_) VALUES ('00000000-0000-0000-0000-000000000057', 'text/html', 'some tool 2', 'text', X'1007'); --7 
+
+ -- PostgreSQL --
+-- INSERT INTO cached_representation (external_id, mime_type, tool, type_) VALUES ('00000000-0000-0000-0000-000000000051', 'image/png', 'some tool 1', 'image'); --1
+-- INSERT INTO cached_representation (external_id, mime_type, tool, type_) VALUES ('00000000-0000-0000-0000-000000000052', 'image/png', 'some tool 2', 'image'); -- 2
+-- INSERT INTO cached_representation (external_id, mime_type, tool, type_) VALUES ('00000000-0000-0000-0000-000000000053', 'image/png', 'some tool 3', 'image'); -- 3
+-- INSERT INTO cached_representation (external_id, mime_type, tool, type_) VALUES ('00000000-0000-0000-0000-000000000054', 'image/png', 'some tool 4', 'image'); --4 
+-- INSERT INTO cached_representation (external_id, mime_type, tool, type_) VALUES ('00000000-0000-0000-0000-000000000055', 'image/png', 'some tool 5', 'image'); --5 
+-- INSERT INTO cached_representation (external_id, mime_type, tool, type_) VALUES ('00000000-0000-0000-0000-000000000056', 'image/png', 'some tool 6', 'image'); --6  not used
+-- INSERT INTO cached_representation (external_id, mime_type, tool, type_) VALUES ('00000000-0000-0000-0000-000000000057', 'image/png', 'some tool 7', 'image'); --7 
+
+
+
+INSERT INTO targets_cached_representations (target_id,  cached_representation_id, fragment_descriptor_in_cached) VALUES (1, 1, 'De Opdracht');
+INSERT INTO targets_cached_representations (target_id,  cached_representation_id, fragment_descriptor_in_cached) VALUES (1, 2, '(0,0)');
+INSERT INTO targets_cached_representations (target_id,  cached_representation_id, fragment_descriptor_in_cached) VALUES (2, 3, 'Vroeger Werk');
+INSERT INTO targets_cached_representations (target_id,  cached_representation_id, fragment_descriptor_in_cached) VALUES (3, 4, 'Spain');
+INSERT INTO targets_cached_representations (target_id,  cached_representation_id, fragment_descriptor_in_cached) VALUES (4, 5, '(1,1)');
+INSERT INTO targets_cached_representations (target_id,  cached_representation_id, fragment_descriptor_in_cached) VALUES (5, 7, '(0,1)');
+
+
+---- PERMISSIONS --------------------------------------------------------------------------------------------
+
+
+INSERT INTO permission_(permission_mode) VALUES ('writer');
+INSERT INTO permission_(permission_mode) VALUES ('reader');
+
+INSERT INTO annotations_principals_permissions (annotation_id, principal_id, permission_) VALUES (1, 2, 'writer');
+INSERT INTO annotations_principals_permissions (annotation_id, principal_id, permission_) VALUES (1, 3, 'reader');
+
+INSERT INTO annotations_principals_permissions (annotation_id, principal_id, permission_) VALUES (2, 1, 'reader');
+INSERT INTO annotations_principals_permissions (annotation_id, principal_id, permission_) VALUES (2, 3, 'writer');
+
+INSERT INTO annotations_principals_permissions (annotation_id, principal_id, permission_) VALUES (3, 1, 'reader');
+INSERT INTO annotations_principals_permissions (annotation_id, principal_id, permission_) VALUES (3, 2, 'reader');
+
+INSERT INTO annotations_principals_permissions (annotation_id, principal_id, permission_) VALUES (4, 2, 'writer');
+INSERT INTO annotations_principals_permissions (annotation_id, principal_id, permission_) VALUES (4, 1, 'writer');
+-- checking integrity control:
+-- INSERT INTO annotations_principals_permissions (annotation_id, principal_id, permission_) VALUES (5, 5, 'reader');
+
+INSERT INTO notebooks_principals_permissions (notebook_id, principal_id, permission_) VALUES (1, 2, 'writer');
+INSERT INTO notebooks_principals_permissions (notebook_id, principal_id, permission_) VALUES (1, 3, 'reader');
+INSERT INTO notebooks_principals_permissions (notebook_id, principal_id, permission_) VALUES (1, 4, 'writer');
+INSERT INTO notebooks_principals_permissions (notebook_id, principal_id, permission_) VALUES (1, 5, 'reader');
+
+
+INSERT INTO notebooks_principals_permissions (notebook_id, principal_id, permission_) VALUES (2, 1, 'reader');
+INSERT INTO notebooks_principals_permissions (notebook_id, principal_id, permission_) VALUES (2, 3, 'writer');
+
+INSERT INTO notebooks_principals_permissions (notebook_id, principal_id, permission_) VALUES (4, 2, 'writer');
+INSERT INTO notebooks_principals_permissions (notebook_id, principal_id, permission_) VALUES (4, 1, 'writer');
+
