Index: modules/uoa-claims-api/tags/uoa-claims-api-2.1.0/pom.xml
===================================================================
--- modules/uoa-claims-api/tags/uoa-claims-api-2.1.0/pom.xml	(nonexistent)
+++ modules/uoa-claims-api/tags/uoa-claims-api-2.1.0/pom.xml	(revision 62533)
@@ -0,0 +1,162 @@
+<?xml version="1.0"?>
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+    <parent>
+        <groupId>eu.dnetlib</groupId>
+        <artifactId>uoa-global-parent</artifactId>
+        <version>1.0.1</version>
+    </parent>
+	<modelVersion>4.0.0</modelVersion>
+	<groupId>eu.dnetlib</groupId>
+	<artifactId>uoa-claims-api</artifactId>
+	<version>2.1.0</version>
+        <scm>
+                <developerConnection>scm:svn:https://svn.driver.research-infrastructures.eu/driver/dnet45/modules/uoa-claims-api/tags/uoa-claims-api-2.1.0</developerConnection>
+        </scm>
+	<pluginRepositories>
+		<pluginRepository>
+			<id>dtrotts</id>
+			<name>Repository for maven thrift plugin</name>
+			<url>http://maven.davidtrott.com/repository</url>
+			<layout>default</layout>
+		</pluginRepository>
+	</pluginRepositories>
+	<build>
+        <plugins>
+            <plugin>
+                <groupId>org.apache.maven.plugins</groupId>
+                <artifactId>maven-compiler-plugin</artifactId>
+                <configuration>
+                    <source>1.7</source>
+                    <target>1.7</target>
+                </configuration>
+            </plugin>
+        </plugins>
+    </build>
+    <dependencies>
+        <dependency>
+            <groupId>junit</groupId>
+            <artifactId>junit</artifactId>
+            <version>[0.0.0,)</version>
+            <scope>test</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.slf4j</groupId>
+            <artifactId>slf4j-api</artifactId>
+            <version>1.7.5</version>
+        </dependency>
+        <dependency>
+            <groupId>commons-dbcp</groupId>
+            <artifactId>commons-dbcp</artifactId>
+            <version>[1.2, 1.3)</version>
+        </dependency>
+        <dependency>
+            <groupId>eu.dnetlib</groupId>
+            <artifactId>uoa-claims</artifactId>
+            <version>2.1.0</version>
+        </dependency>
+        <dependency>
+            <groupId>javax.servlet</groupId>
+            <artifactId>servlet-api</artifactId>
+            <version>2.5</version>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.postgresql</groupId>
+            <artifactId>jdbc4driver</artifactId>
+            <version>9.1</version>
+        </dependency>
+        <dependency>
+            <groupId>org.springframework</groupId>
+            <artifactId>spring-tx</artifactId>
+            <version>4.2.5.RELEASE</version>
+        </dependency>
+        <dependency>
+            <groupId>org.springframework</groupId>
+            <artifactId>spring-jdbc</artifactId>
+            <version>4.2.5.RELEASE</version>
+        </dependency>
+        <dependency>
+            <groupId>oro</groupId>
+            <artifactId>oro</artifactId>
+            <version>2.0.8</version>
+        </dependency>
+
+
+        <!-- Jersey -->
+        <dependency>
+            <groupId>asm</groupId>
+            <artifactId>asm</artifactId>
+            <version>3.3.1</version>
+        </dependency>
+        <dependency>
+            <groupId>com.sun.jersey</groupId>
+            <artifactId>jersey-bundle</artifactId>
+            <version>1.19</version>
+        </dependency>
+        <dependency>
+            <groupId>org.json</groupId>
+            <artifactId>json</artifactId>
+            <version>20140107</version>
+        </dependency>
+        <dependency>
+            <groupId>com.sun.jersey</groupId>
+            <artifactId>jersey-server</artifactId>
+            <version>1.19</version>
+        </dependency>
+        <dependency>
+            <groupId>com.sun.jersey</groupId>
+            <artifactId>jersey-core</artifactId>
+            <version>1.19</version>
+        </dependency>
+        <dependency>
+            <groupId>commons-validator</groupId>
+            <artifactId>commons-validator</artifactId>
+            <version>1.3.1</version>
+        </dependency>
+        <dependency>
+            <groupId>com.sun.jersey.contribs</groupId>
+            <artifactId>jersey-spring</artifactId>
+            <version>1.8</version>
+            <exclusions>
+                <exclusion>
+                    <groupId>org.springframework</groupId>
+                    <artifactId>spring</artifactId>
+                </exclusion>
+                <exclusion>
+                    <groupId>org.springframework</groupId>
+                    <artifactId>spring-core</artifactId>
+                </exclusion>
+                <exclusion>
+                    <groupId>org.springframework</groupId>
+                    <artifactId>spring-web</artifactId>
+                </exclusion>
+                <exclusion>
+                    <groupId>org.springframework</groupId>
+                    <artifactId>spring-beans</artifactId>
+                </exclusion>
+                <exclusion>
+                    <groupId>org.springframework</groupId>
+                    <artifactId>spring-context</artifactId>
+                </exclusion>
+                <exclusion>
+                    <groupId>org.springframework</groupId>
+                    <artifactId>spring-utils</artifactId>
+                </exclusion>
+                <exclusion>
+                    <groupId>org.springframework</groupId>
+                    <artifactId>spring-aop</artifactId>
+                </exclusion>
+            </exclusions>
+        </dependency>
+        <dependency>
+            <groupId>io.jsonwebtoken</groupId>
+            <artifactId>jjwt</artifactId>
+            <version>0.7.0</version>
+        </dependency>
+        <dependency>
+            <groupId>eu.dnetlib</groupId>
+            <artifactId>uoa-claims</artifactId>
+            <version>2.1.0</version>
+        </dependency>
+    </dependencies>
+</project>
Index: modules/uoa-claims-api/tags/uoa-claims-api-2.1.0/src/main/java/eu/dnetlib/openaire/rest/Authorization.java
===================================================================
--- modules/uoa-claims-api/tags/uoa-claims-api-2.1.0/src/main/java/eu/dnetlib/openaire/rest/Authorization.java	(nonexistent)
+++ modules/uoa-claims-api/tags/uoa-claims-api-2.1.0/src/main/java/eu/dnetlib/openaire/rest/Authorization.java	(revision 62533)
@@ -0,0 +1,222 @@
+package eu.dnetlib.openaire.rest;
+
+import eu.dnetlib.openaire.rest.inputHandler.UserHandler;
+import org.apache.logging.log4j.LogManager;
+import org.apache.logging.log4j.Logger;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+/**
+ * Created by sofia on 20/4/2017.
+ */
+public class Authorization {
+
+    private static Logger logger = LogManager.getLogger(Authorization.class);
+    List<String> registeredRoles = new ArrayList<String>(Arrays.asList("Super Administrator", "Portal Administrator", "Expert - Community",
+            "Expert - Funder", "Curator - Claim", "Curator - Project", "Curator - Community", "Curator - Institution", "Cuthor", "Registered", "User Manager"));
+    List<String> claimCuratorRoles = new ArrayList<String>(Arrays.asList("Super Administrator", "Curator - Claim", "Portal Administrator"));
+    List<String> projectCuratorRoles = new ArrayList<String>(Arrays.asList("Curator - Project"));
+    List<String> communityCuratorRoles = new ArrayList<String>(Arrays.asList("Curator - Community"));
+    List<String> portalAdminRoles = new ArrayList<String>(Arrays.asList("Portal Administrator"));
+    UserHandler userHandler = null;
+    String originServer = null;
+
+    //    public static boolean isRegistered(String token) {
+//
+//        Claims claims = Jwts.parser()
+//                .setSigningKey(DatatypeConverter.parseBase64Binary("my-very-secret"))
+//                .parseClaimsJws(token).getBody();
+//
+//        if (claims.get("role").equals("1") || claims.get("role").equals("2")) {
+//            logger.debug("It's  registered with role " + claims.get("role"));
+//            return true;
+//        } else {
+//            logger.debug("It's *not*  registered with role " + claims.get("role"));
+//
+//            return false;
+//        }
+//    }
+//
+//    public static boolean isClaimCurator(String token) {
+//        Claims claims = Jwts.parser()
+//                .setSigningKey(DatatypeConverter.parseBase64Binary("my-very-secret"))
+//                .parseClaimsJws(token).getBody();
+//        if (claims.get("role").equals("2")) {
+//            logger.debug("It's  admin with role " + claims.get("role"));
+//            return true;
+//        } else {
+//            logger.debug("It's *not*  admin with role " + claims.get("role"));
+//            return false;
+//        }
+//    }
+    public boolean isRegistered(String token) {
+        UserInfo userInfo = userHandler.getUserInfo(token);
+        return isRegistered(userInfo);
+
+    }
+    public void logStatus(String token, String cookie) {
+
+        if(token == null || token.isEmpty()) {
+            logger.debug("No proper value: header \"X-XSRF-TOKEN\" has value " + token);
+        }else if(cookie == null || cookie.isEmpty() || !cookie.equals(token)) {
+            logger.debug("No proper value: cookie  \"AccessToken\" has value  " + cookie);
+        }else if( !cookie.equals(token)) {
+            logger.debug("No proper values:for cookie " + cookie + " and token "+token);
+        }
+    }
+
+    public boolean isRegistered(UserInfo userInfo) {
+        if (userInfo != null && userInfo.getEdu_person_entitlements() != null) {
+
+            return hasRole(userInfo.getEdu_person_entitlements(), registeredRoles);
+        } else {
+            return false;
+        }
+
+    }
+
+    public boolean isClaimCurator(String token) {
+        UserInfo userInfo = userHandler.getUserInfo(token);
+        return isClaimCurator(userInfo);
+
+    }
+
+    public boolean isClaimCurator(UserInfo userInfo) {
+        if (userInfo != null && userInfo.getEdu_person_entitlements() != null) {
+
+            return hasRole(userInfo.getEdu_person_entitlements(), claimCuratorRoles);
+        } else {
+            logger.debug(" User has no Valid UserInfo");
+            return false;
+        }
+
+    }
+
+    public boolean isCommunityCurator(String token) {
+        UserInfo userInfo = userHandler.getUserInfo(token);
+        return isCommunityCurator(userInfo);
+
+    }
+
+    public boolean isCommunityCurator(UserInfo userInfo) {
+        if (userInfo != null && userInfo.getEdu_person_entitlements() != null) {
+
+            return hasRole(userInfo.getEdu_person_entitlements(), communityCuratorRoles);
+        } else {
+            logger.debug(" User has no Valid UserInfo");
+            return false;
+        }
+
+    }
+    public boolean isProjectCurator(String token) {
+        UserInfo userInfo = userHandler.getUserInfo(token);
+        return isProjectCurator(userInfo);
+
+    }
+
+    public boolean isProjectCurator(UserInfo userInfo) {
+        if (userInfo != null && userInfo.getEdu_person_entitlements() != null) {
+
+            return hasRole(userInfo.getEdu_person_entitlements(), projectCuratorRoles);
+        } else {
+            return false;
+        }
+
+    }
+
+    public boolean isPortalAdministrator(String token) {
+        UserInfo userInfo = userHandler.getUserInfo(token);
+        return isPortalAdministrator(userInfo);
+
+    }
+
+    public boolean isPortalAdministrator(UserInfo userInfo) {
+        if (userInfo != null && userInfo.getEdu_person_entitlements() != null) {
+
+            return hasRole(userInfo.getEdu_person_entitlements(), portalAdminRoles);
+        } else {
+            logger.debug(" User has no Valid UserInfo");
+            return false;
+        }
+
+    }
+
+    public boolean hasRole(List<String> givenRoles, List<String> authorizedRoles) {
+
+        logger.debug("It's  registered with role " + givenRoles);
+        for (String gRole : givenRoles) {
+            if (authorizedRoles.indexOf(gRole) != -1) {
+                return true;
+            }
+        }
+        logger.debug("Not Authorized. Authorized roles are" + authorizedRoles);
+        return false;
+
+    }
+
+    public boolean hasValidOrigin(String origin) {
+        logger.debug("Origin is "+origin +" originServer: "+originServer);
+        if (origin != null && origin.indexOf(originServer)!=-1) {
+            return true;
+        }
+        logger.debug("Not valid origin. Origin server is \"" + origin + "\", but expected value is \"" + originServer + "\". If the expec cted value is not right, check properties file. ");
+        return false;
+    }
+
+    public boolean hasBasicAuthorization(String token, String origin, String  cookie){
+        if(token == null || token.isEmpty() || cookie == null || cookie.isEmpty() || !cookie.equals(token)|| !hasValidOrigin(origin)){
+            return false;
+        }
+        return true;
+    }
+
+    public List<String> getRegisteredRoles() {
+        return registeredRoles;
+    }
+
+    public void setRegisteredRoles(List<String> registeredRoles) {
+        this.registeredRoles = registeredRoles;
+    }
+
+    public List<String> getClaimCuratorRoles() {
+        return claimCuratorRoles;
+    }
+
+    public void setClaimCuratorRoles(List<String> claimCuratorRoles) {
+        this.claimCuratorRoles = claimCuratorRoles;
+    }
+
+    public List<String> getCommunityCuratorRoles() {
+        return communityCuratorRoles;
+    }
+
+    public void setCommunityCuratorRoles(List<String> communityCuratorRoles) {
+        this.communityCuratorRoles = communityCuratorRoles;
+    }
+
+    public List<String> getProjectCuratorRoles() {
+        return projectCuratorRoles;
+    }
+
+    public void setProjectCuratorRoles(List<String> projectCuratorRoles) {
+        this.projectCuratorRoles = projectCuratorRoles;
+    }
+
+    public UserHandler getUserHandler() {
+        return userHandler;
+    }
+
+    public void setUserHandler(UserHandler userHandler) {
+        this.userHandler = userHandler;
+    }
+
+    public String getOriginServer() {
+        return originServer;
+    }
+
+    public void setOriginServer(String originServer) {
+        this.originServer = originServer;
+    }
+}
Index: modules/uoa-claims-api/tags/uoa-claims-api-2.1.0/src/main/java/eu/dnetlib/openaire/rest/ClaimsService.java
===================================================================
--- modules/uoa-claims-api/tags/uoa-claims-api-2.1.0/src/main/java/eu/dnetlib/openaire/rest/ClaimsService.java	(nonexistent)
+++ modules/uoa-claims-api/tags/uoa-claims-api-2.1.0/src/main/java/eu/dnetlib/openaire/rest/ClaimsService.java	(revision 62533)
@@ -0,0 +1,1252 @@
+package eu.dnetlib.openaire.rest;
+
+import com.google.gson.*;
+import eu.dnetlib.data.claims.entity.Claim;
+import eu.dnetlib.data.claims.entity.Notification;
+import eu.dnetlib.data.claims.handler.*;
+import eu.dnetlib.data.claims.sql.SQLStoreException;
+import eu.dnetlib.data.claims.utils.ClaimValidationException;
+import eu.dnetlib.data.emailSender.EmailSender;
+import org.apache.commons.validator.EmailValidator;
+import org.apache.logging.log4j.LogManager;
+import org.apache.logging.log4j.Logger;
+import org.json.XML;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+import org.springframework.web.bind.annotation.CrossOrigin;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.*;
+import javax.ws.rs.core.Context;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+
+
+/**
+ * Created by kiatrop on 15/4/2016.
+ */
+@Component
+@CrossOrigin(origins = "*")
+@Path("/claimsService")
+public class ClaimsService {
+
+    private static final Logger logger = LogManager.getLogger(ClaimsService.class);
+
+    @Autowired
+    private FetchClaimHandler fetchClaimHandler = null;
+
+    @Autowired
+    private FetchProjectHandler fetchProjectHandler= null;
+
+    @Autowired
+    private FetchNotificationHandler fetchNotificationHandler = null;
+
+    @Autowired
+    private NotificationHandler notificationHandler = null;
+
+
+    @Autowired
+    private ClaimHandler claimHandler = null;
+
+    @Autowired
+    private DirectIndexHandler directIndexHandler = null;
+
+    @Autowired
+    public Authorization authorization = null;
+
+    @Autowired
+    private String defaultFrequencyInHours;
+
+    @Autowired
+    private EmailSender emailSender;
+
+    @GET
+    @Path("projects/{projectId}/claims")
+    @Produces(MediaType.APPLICATION_JSON)
+    public Response getProjectClaims(@PathParam("projectId") String projectId,
+                                     @DefaultValue("0") @QueryParam("offset") int offset,
+                                     @DefaultValue("20") @QueryParam("limit") int limit,
+                                     @DefaultValue("") @QueryParam("keyword") String keyword,
+                                     @DefaultValue("") @QueryParam("sortby") String orderby,
+                                     @DefaultValue("true") @QueryParam("descending") boolean descending,
+                                     @DefaultValue("") @QueryParam("types") List<String> types,
+                                     @HeaderParam("X-XSRF-TOKEN") String token,
+                                     @CookieParam("AccessToken") String  cookie,
+                                     @Context HttpServletRequest request) {
+
+        if(token == null || token.isEmpty() || cookie == null || cookie.isEmpty() || !cookie.equals(token)){
+            authorization.logStatus(token,cookie);
+            return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. Maybe you are not registered."))
+                    .type(MediaType.APPLICATION_JSON)
+                    .build();
+        }
+
+        if(authorization.isClaimCurator(token)) {
+
+            int total = -1;
+
+            if (projectId == null || projectId.isEmpty()) {
+                return Response.status(Response.Status.BAD_REQUEST).entity(compose400Message("Project id cannot be empty."))
+                        .type(MediaType.APPLICATION_JSON).build();
+            }
+
+            List<Claim> claims = null;
+            try {
+                claims = fetchClaimHandler.fetchClaimsByProject(projectId, limit, offset, keyword, orderby, descending, types,false);
+                total = fetchClaimHandler.countClaimsByProject(projectId, keyword, types);
+
+            } catch (SQLStoreException|Exception e) {  //TODO check this with exception
+                logger.error("Could not fetch claims for project with id " + projectId, e);
+                return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500Message("Fail to fetch claims" +
+                        " for projects with id " + projectId + ".", e)).type(MediaType.APPLICATION_JSON).build();
+
+            }
+
+            return Response.status(200).entity(composeDataResponse(request, claims, total, offset, limit)).build();
+        }
+
+        return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access"))
+                .type(MediaType.APPLICATION_JSON)
+                .build();
+    }
+
+    @GET
+    @Path("projects/{projectId}/all_claims")
+    @Produces(MediaType.APPLICATION_JSON)
+    public Response getAllProjectClaims(@PathParam("projectId") String projectId,
+                                        @DefaultValue("-1") @QueryParam("offset") int offset,
+                                        @DefaultValue("-1") @QueryParam("limit") int limit,
+                                        @DefaultValue("") @QueryParam("keyword") String keyword,
+                                        @DefaultValue("") @QueryParam("sortby") String orderby,
+                                        @DefaultValue("true") @QueryParam("descending") boolean descending,
+                                        @DefaultValue("") @QueryParam("types") List<String> types,
+                                        @HeaderParam("X-XSRF-TOKEN") String token,
+                                        @CookieParam("AccessToken") String  cookie,
+                                        @Context HttpServletRequest request) {
+
+        if(token == null || token.isEmpty() || cookie == null || cookie.isEmpty() || !cookie.equals(token)){
+            authorization.logStatus(token,cookie);
+            return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. Maybe you are not registered."))
+                    .type(MediaType.APPLICATION_JSON)
+                    .build();
+        }
+
+        UserInfo userInfo = authorization.getUserHandler().getUserInfo(token);
+//        if(authorization.isProjectCurator(userInfo)) {
+        String userMail = userInfo.getEmail();
+
+        int total = -1;
+
+        if (projectId == null || projectId.isEmpty()) {
+            return Response.status(Response.Status.BAD_REQUEST).entity(compose400Message("Project id cannot be empty."))
+                    .type(MediaType.APPLICATION_JSON).build();
+        }
+
+        List<Claim> claims = null;
+        try {
+            boolean forbidden = true;
+            if(authorization.isProjectCurator(userInfo)) {
+                forbidden = false;
+            } else {
+                List<String> contact_emails = fetchProjectHandler.fetchContactEmailsByProjectId(projectId);
+                logger.debug(contact_emails);
+                if(contact_emails != null && contact_emails.contains(userMail)) {
+                    forbidden = false;
+                }
+            }
+
+            if(forbidden){
+                return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access"))
+                        .type(MediaType.APPLICATION_JSON)
+                        .build();
+            }else{
+                if(offset == -1 && limit == -1) {
+                    // when offset and limit are -1 fetch claims with null values, to ignore paging and limit clause
+                    claims = fetchClaimHandler.fetchClaimsByProject(projectId, null, null, keyword, orderby, descending, types, true);
+                } else {
+                    claims = fetchClaimHandler.fetchClaimsByProject(projectId, limit, offset, keyword, orderby, descending, types, true);
+                }
+                total = fetchClaimHandler.countClaimsByProject(projectId, keyword, types);
+
+                return Response.status(200).entity(composeDataResponse(request, claims, total, offset, limit)).build();
+            }
+
+        } catch (SQLStoreException|Exception e) {
+            logger.error("Could not fetch claims for project with id " + projectId, e);
+            return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500Message("Fail to fetch claims" +
+                    " for projects with id " + projectId + ".", e)).type(MediaType.APPLICATION_JSON).build();
+        }
+    }
+/*
+    @GET
+    @Path("project/claims")
+    @Produces(MediaType.APPLICATION_JSON)
+    public Response getProjectClaimsByToken(@QueryParam("projectToken") String projectToken,
+                                     @DefaultValue("-1") @QueryParam("offset") int offset,
+                                     @DefaultValue("-1") @QueryParam("limit") int limit,
+                                     @DefaultValue("") @QueryParam("keyword") String keyword,
+                                     @DefaultValue("") @QueryParam("sortby") String orderby,
+                                     @DefaultValue("true") @QueryParam("descending") boolean descending,
+                                     @DefaultValue("") @QueryParam("types") List<String> types,
+                                     @HeaderParam("X-XSRF-TOKEN") String token,
+                                     @CookieParam("AccessToken") String  cookie,
+                                     @Context HttpServletRequest request) {
+
+
+        if(token == null || token.isEmpty() || cookie == null || cookie.isEmpty() || !cookie.equals(token)){
+            authorization.logStatus(token,cookie);
+            return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. Maybe you are not registered."))
+                    .type(MediaType.APPLICATION_JSON)
+                    .build();
+        }
+
+        UserInfo userInfo = authorization.getUserHandler().getUserInfo(token);
+//        if(authorization.isProjectCurator(userInfo)) {
+            String userMail = userInfo.getEmail();
+
+            int total = -1;
+
+            if (projectToken == null || projectToken.isEmpty()) {
+                return Response.status(Response.Status.BAD_REQUEST).entity(compose400Message("Project token cannot be empty."))
+                        .type(MediaType.APPLICATION_JSON).build();
+            }
+
+            List<Claim> claims = null;
+            try {
+                String projectId = null;
+                if(authorization.isProjectCurator(userInfo)) {
+                    projectId = fetchProjectHandler.fetchProjectIdByToken(projectToken);
+                } else {
+                    projectId = fetchProjectHandler.fetchProjectIdByTokenAndEmail(projectToken, userMail);
+                }
+                //String projectId = fetchProjectHandler.fetchProjectIdByToken(projectToken,userMail);
+                if(projectId == null){
+                    return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access"))
+                            .type(MediaType.APPLICATION_JSON)
+                            .build();
+                }else{
+                    if(offset == -1 && limit == -1) {
+                        // when offset and limit are -1 fetch claims with null values, to ignore paging and limit clause
+                        claims = fetchClaimHandler.fetchClaimsByProject(projectId, null, null, keyword, orderby, descending, types, true);
+                    } else {
+                        claims = fetchClaimHandler.fetchClaimsByProject(projectId, limit, offset, keyword, orderby, descending, types, true);
+                    }
+                    total = fetchClaimHandler.countClaimsByProject(projectId, keyword, types);
+
+                    return Response.status(200).entity(composeDataResponse(request, claims, total, offset, limit)).build();
+                }
+
+            } catch (SQLStoreException|Exception e) {
+                logger.error("Could not fetch claims for project token " + projectToken, e);
+                return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500Message("Fail to fetch claims" +
+                        " for projects with token " + projectToken + ".", e)).type(MediaType.APPLICATION_JSON).build();
+            }
+//        }
+
+//        return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access"))
+//                .type(MediaType.APPLICATION_JSON)
+//                .build();
+    }
+*/
+
+    @GET
+    @Path("/contexts/{contextId}/claims")
+    @Produces(MediaType.APPLICATION_JSON)
+    public Response getContextClaims(@PathParam("contextId") String contextId,
+                                     @DefaultValue("0") @QueryParam("offset") int offset,
+                                     @DefaultValue("20") @QueryParam("limit") int limit,
+                                     @DefaultValue("") @QueryParam("keyword") String keyword,
+                                     @DefaultValue("") @QueryParam("sortby") String orderby,
+                                     @DefaultValue("true") @QueryParam("descending") boolean descending,
+                                     @DefaultValue("") @QueryParam("types") List<String> types,
+                                     @HeaderParam("X-XSRF-TOKEN") String token,
+                                     @CookieParam("AccessToken") String  cookie,
+                                     @Context HttpServletRequest request) {
+//        @RequestParam(value="includeStates[]", defaultValue="1,2,3") String[] includeStates
+
+        if(token == null || token.isEmpty() || cookie == null || cookie.isEmpty() || !cookie.equals(token)){
+            authorization.logStatus(token,cookie);
+            return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. Maybe you are not registered."))
+                    .type(MediaType.APPLICATION_JSON)
+                    .build();
+        }
+//        logger.debug("Calling API for context with token " + token);
+        UserInfo userInfo = authorization.getUserHandler().getUserInfo(token);
+        if(authorization.isCommunityCurator(userInfo) || authorization.isClaimCurator(token) || this.emailSender.getManagerUtils().isCommunityManager(contextId, userInfo.email )) {
+
+            int total = -1;
+            if (contextId == null || contextId.isEmpty()) {
+                return Response.status(Response.Status.BAD_REQUEST).entity(compose400Message("Context id cannot be empty."))
+                        .type(MediaType.APPLICATION_JSON).build();
+            }
+            logger.debug("Types are " + types);
+            List<Claim> claims = null;
+
+            try {
+                claims = fetchClaimHandler.fetchClaimsByContext(contextId, limit, offset, keyword, orderby, descending, types,false);
+                total = fetchClaimHandler.countClaimsByContext(contextId, keyword, types);
+
+            } catch (SQLStoreException|Exception e) {
+                logger.error("Could not fetch claims for context with id " + contextId, e);
+                return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500Message("Fail to fetch claims" +
+                        " for context with id " + contextId + ".", e)).type(MediaType.APPLICATION_JSON).build();
+            }
+
+            return Response.status(200).entity(composeDataResponse(request, claims, total, offset, limit)).build();
+        }
+
+        return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access"))
+                .type(MediaType.APPLICATION_JSON)
+                .build();
+    }
+
+
+    @GET
+    @Path("/results/{resultId}/claims")
+    @Produces(MediaType.APPLICATION_JSON)
+    public Response getResultClaims(@PathParam("resultId") String resultId,
+                                    @DefaultValue("0") @QueryParam("offset") int offset,
+                                    @DefaultValue("20") @QueryParam("limit") int limit,
+                                    @DefaultValue("") @QueryParam("keyword") String keyword,
+                                    @DefaultValue("") @QueryParam("sortby") String orderby,
+                                    @DefaultValue("true") @QueryParam("descending") boolean descending,
+                                    @DefaultValue("") @QueryParam("types") List<String> types,
+                                    @HeaderParam("X-XSRF-TOKEN") String token,
+                                    @CookieParam("AccessToken") String  cookie,
+                                    @Context HttpServletRequest request) {
+
+
+        if(token == null || token.isEmpty() || cookie == null || cookie.isEmpty() || !cookie.equals(token)){
+            authorization.logStatus(token,cookie);
+            return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. Maybe you are not registered."))
+                    .type(MediaType.APPLICATION_JSON)
+                    .build();
+        }
+
+        if(authorization.isClaimCurator(token)) {
+
+            int total = -1;
+            if (resultId == null || resultId.isEmpty()) {
+                return Response.status(Response.Status.BAD_REQUEST).entity(compose400Message("Context id cannot be empty."))
+                        .type(MediaType.APPLICATION_JSON).build();
+            }
+
+            List<Claim> claims = null;
+            try {
+                claims = fetchClaimHandler.fetchClaimsByResult(resultId, limit, offset, keyword, orderby, descending, types,false);
+                total = fetchClaimHandler.countClaimsByResult(resultId, keyword, types);
+
+            } catch (SQLStoreException|Exception e) {
+                logger.error("Could not fetch claims for result with id " + resultId, e);
+                return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500Message("Fail to fetch claims" +
+                        " for result with id " + resultId + ".", e)).type(MediaType.APPLICATION_JSON).build();
+            }
+
+            return Response.status(200).entity(composeDataResponse(request, claims, total, offset, limit)).build();
+        }
+
+        return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access"))
+                .type(MediaType.APPLICATION_JSON)
+                .build();
+    }
+
+
+    @GET
+    @Path("/users/claims")
+    @Produces(MediaType.APPLICATION_JSON)
+    public Response getUserClaims(@DefaultValue("0") @QueryParam("offset") int offset,
+                                  @DefaultValue("20") @QueryParam("limit") int limit,
+                                  @DefaultValue("") @QueryParam("keyword") String keyword,
+                                  @DefaultValue("") @QueryParam("sortby") String orderby,
+                                  @DefaultValue("true") @QueryParam("descending") boolean descending,
+                                  @DefaultValue("") @QueryParam("types") List<String> types,
+                                  @HeaderParam("X-XSRF-TOKEN") String token,
+                                  @CookieParam("AccessToken") String  cookie,
+                                  @Context HttpServletRequest request) {
+
+
+        if(token == null || token.isEmpty() || cookie == null || cookie.isEmpty() || !cookie.equals(token)){
+            return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. Maybe you are not registered."))
+                    .type(MediaType.APPLICATION_JSON)
+                    .build();
+        }
+
+        UserInfo userInfo = authorization.getUserHandler().getUserInfo(token);
+        if(authorization.isRegistered(userInfo)) {
+            String userMail = userInfo.getEmail();
+            logger.debug("User is registerd "  );
+            int total = -1;
+            EmailValidator emailValidator = EmailValidator.getInstance();
+
+            if (userMail == null || userMail.isEmpty()) {
+                return Response.status(Response.Status.BAD_REQUEST).entity(compose400Message("User e-mail cannot be empty."))
+                        .type(MediaType.APPLICATION_JSON).build();
+            }
+
+            if (!emailValidator.isValid(userMail)) {
+                return Response.status(Response.Status.BAD_REQUEST).entity(compose400Message("User e-mail is not valid."))
+                        .type(MediaType.APPLICATION_JSON).build();
+            }
+
+            List<Claim> claims = null;
+            try {
+                logger.debug("About to fetch claims"  );
+                claims = fetchClaimHandler.fetchClaimsByUser(userMail, limit, offset, keyword, orderby, descending, types,false);
+                total = fetchClaimHandler.countClaimsByUser(userMail, keyword, types);
+
+            } catch (SQLStoreException|Exception e) {
+                logger.error("Could not fetch claims for user with mail " + userMail, e);
+                return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500Message("Fail to fetch claims" +
+                        " for user with e-mail " + userMail + ".", e)).type(MediaType.APPLICATION_JSON).build();
+            }
+
+            return Response.status(200).entity(composeDataResponse(request, claims, total, offset, limit)).build();
+        }
+        logger.debug("User is *NOT* registerd "  );
+        return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. You are not registered."))
+                .type(MediaType.APPLICATION_JSON)
+                .build();
+    }
+
+    @GET
+    @Path("/claims/{claimId}")
+    @Produces(MediaType.APPLICATION_JSON)
+    public Response getClaimsById(@PathParam("claimId") String claimId,
+                                  @DefaultValue("0") @QueryParam("offset") int offset,
+                                  @DefaultValue("20") @QueryParam("limit") int limit,
+                                  @HeaderParam("X-XSRF-TOKEN") String token,
+                                  @CookieParam("AccessToken") String  cookie,
+                                  @Context HttpServletRequest request) {
+
+
+        if(token == null || token.isEmpty() || cookie == null || cookie.isEmpty() || !cookie.equals(token)){
+            return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. Maybe you are not registered."))
+                    .type(MediaType.APPLICATION_JSON)
+                    .build();
+        }
+
+        if(authorization.isRegistered(token)) {
+
+            List<Claim> claims = null;
+
+            int total = -1;
+            if (claimId == null || claimId.isEmpty()) {
+                try {
+                    claims = fetchClaimHandler.fetchAllClaims(limit, offset,false);
+                    total = fetchClaimHandler.countAllClaims("", new ArrayList<String>());
+
+                    return Response.status(200).entity(composeDataResponse(request, claims, total, offset, limit)).type(MediaType.APPLICATION_JSON).build();
+
+                } catch (SQLStoreException|Exception e) {
+                    logger.error("Could not fetch claims.", e);
+                    return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500Message("Fail to fetch claims.", e))
+                            .type(MediaType.APPLICATION_JSON).build();
+                }
+            }
+
+            try {
+                Claim claim = fetchClaimHandler.fetchClaimById(claimId,false);
+                if (claim == null) {
+                    return Response.status(Response.Status.NOT_FOUND).entity(compose404Message("Cannot find claim with id " + claimId + "."))
+                            .type(MediaType.APPLICATION_JSON).build();
+                }
+
+                return Response.status(200).entity(composeDataResponse(claim)).build();
+
+            } catch (SQLStoreException|Exception e) {
+                return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500Message("Fail to fetch claim " +
+                        "with id " + claimId + " id.", e)).type(MediaType.APPLICATION_JSON).build();
+            }
+        }
+        return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. You are not registered."))
+                .type(MediaType.APPLICATION_JSON)
+                .build();
+    }
+
+    @GET
+    @Path("/claims")
+    @Produces(MediaType.APPLICATION_JSON)
+    public Response getAllClaims(@DefaultValue("0") @QueryParam("offset") int offset,
+                                 @DefaultValue("20") @QueryParam("limit") int limit,
+                                 @DefaultValue("") @QueryParam("keyword") String keyword,
+                                 @DefaultValue("date") @QueryParam("sortby") String orderby,
+                                 @DefaultValue("true") @QueryParam("descending") boolean descending,
+                                 @DefaultValue("") @QueryParam("types") List<String> types,
+                                 @HeaderParam("X-XSRF-TOKEN") String token,
+                                 @HeaderParam("Origin") String origin,
+                                 @CookieParam("AccessToken") String  cookie,
+                                 @Context HttpServletRequest request) {
+
+
+        logger.debug("Header  \"Origin\" has value  " + origin);
+
+
+
+        if(token == null || token.isEmpty() || cookie == null || cookie.isEmpty() || !cookie.equals(token)){
+            logger.debug("User is not  authorized - Eroor 403");
+
+            return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. Maybe you are not registered."))
+                    .type(MediaType.APPLICATION_JSON)
+                    .build();
+        }
+
+        if(authorization.isClaimCurator(token)) {
+            logger.debug("User is authorized ! !");
+            List<Claim> claims = null;
+
+            int total = -1;
+            try {
+                claims = fetchClaimHandler.fetchAllClaims(limit, offset, keyword, orderby, descending, types,false);
+                total = fetchClaimHandler.countAllClaims(keyword, types);
+
+                return Response.status(200).entity(composeDataResponse(request, claims, total, offset, limit)).build();
+
+            } catch (SQLStoreException|Exception e) {
+                logger.error("Could not fetch claims.", e);
+                return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500Message("Fail to fetch claims.", e))
+                        .type(MediaType.APPLICATION_JSON).build();
+            }
+        }
+
+        return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access"))
+                .type(MediaType.APPLICATION_JSON)
+                .build();
+    }
+
+    @DELETE
+    @Path("/claims/bulk")
+    @Produces(MediaType.APPLICATION_JSON)
+    public Response deleteBulkClaims(@QueryParam("claimId") List<String> claimIds,
+                                     @HeaderParam("X-XSRF-TOKEN") String token,
+                                     @HeaderParam("Origin") String origin,
+                                     @CookieParam("AccessToken") String  cookie){
+
+
+
+        if(!authorization.hasBasicAuthorization(token, origin, cookie)){
+            return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. Maybe you are not registered."))
+                    .type(MediaType.APPLICATION_JSON)
+                    .build();
+        }
+
+
+        ArrayList<String> deletedIds= new ArrayList<String>();
+        ArrayList<String> notFoundIds= new ArrayList<String>();
+
+        if (claimIds == null || claimIds.size() == 0) {
+            return Response.status(Response.Status.NOT_FOUND).entity(compose404BulkDeleteMessage("Claim ids cannot be empty.",deletedIds,notFoundIds))
+                    .type(MediaType.APPLICATION_JSON).build();
+        }
+
+        logger.debug("Trying to delete claims with ids: " + claimIds.toString() + ".");
+        UserInfo userInfo = authorization.getUserHandler().getUserInfo(token);
+        for (String claimId : claimIds) {
+            try {
+
+                if (authorization.isRegistered(userInfo)) {
+                    if (authorization.isClaimCurator(userInfo) || authorization.isCommunityCurator(userInfo) || userInfo.getEmail().equals(fetchClaimHandler.fetchClaimById(claimId,false).getUserMail())) {
+                        if (claimHandler.deleteClaim(claimId)) {
+                            deletedIds.add(claimId);
+                        } else {
+                            notFoundIds.add(claimId);
+                        }
+                    } else {
+                        return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to delete."))
+                                .type(MediaType.APPLICATION_JSON)
+                                .build();
+                    }
+                } else {
+                    return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. Maybe you are not registered."))
+                            .type(MediaType.APPLICATION_JSON)
+                            .build();
+                }
+            } catch (SQLStoreException|Exception e) {
+                logger.error("Fail to delete claim with id " + claimId + ".", e);
+                notFoundIds.add(claimId);
+            }
+        }
+        logger.debug("Successfully deleted " + deletedIds.size() + " from " + claimIds.size()  +". Deleted claims with ids: " + deletedIds.toString() + ".");
+        if (claimIds.size() == notFoundIds.size()) {
+            return Response.status(Response.Status.NOT_FOUND).entity(compose404BulkDeleteMessage("Claim ids cannot be empty.",deletedIds,notFoundIds))
+                    .type(MediaType.APPLICATION_JSON).build();
+        } else if (claimIds.size() == notFoundIds.size()) {
+            return Response.status(204).entity(compose204BulkDeleteMessage(deletedIds,notFoundIds)).type(MediaType.APPLICATION_JSON).build();
+        } else {
+            return Response.status(204).entity(compose204BulkDeleteMessage(deletedIds,notFoundIds)).type(MediaType.APPLICATION_JSON).build();
+        }
+    }
+
+    @POST
+    @Path("/claims")
+    @Produces(MediaType.APPLICATION_JSON)
+    @Consumes(MediaType.APPLICATION_JSON)
+    public Response addClaim(String input, @Context HttpServletRequest request,
+                             @HeaderParam("X-XSRF-TOKEN") String token,
+                             @HeaderParam("Origin") String origin,
+                             @CookieParam("AccessToken") String  cookie) {
+
+
+        if(!authorization.hasBasicAuthorization(token, origin, cookie)){
+            return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. Maybe you are not registered."))
+                    .type(MediaType.APPLICATION_JSON)
+                    .build();
+        }
+
+        UserInfo userInfo = authorization.getUserHandler().getUserInfo(token);
+        if(authorization.isRegistered(userInfo)) {
+            JsonObject jsonObject = new JsonParser().parse(input).getAsJsonObject();
+
+            String claimedBy = userInfo.getEmail();
+            logger.info("claimedBy " + claimedBy);
+
+            EmailValidator emailValidator = EmailValidator.getInstance();
+            if (!emailValidator.isValid(claimedBy)) {
+                return Response.status(Response.Status.BAD_REQUEST).entity(compose400Message("User e-mail is invalid."))
+                        .type(MediaType.APPLICATION_JSON).build();
+            }
+
+
+            try {
+                String claimId = this.getInfoAndBuildClaim(jsonObject,claimedBy);
+                return Response.status(200).entity(compose201PostMessage(request, claimId)).type(MediaType.APPLICATION_JSON).build();
+
+            } catch (ClaimValidationException ve) {
+                return Response.status(Response.Status.BAD_REQUEST).entity(compose400Message("The given ids are wrong.", ve))
+                        .type(MediaType.APPLICATION_JSON).build();
+
+            } catch (SQLStoreException|Exception e) {
+                logger.error("Fail to add new claim.", e);
+                return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500Message("Fail to add new claim.", e))
+                        .type(MediaType.APPLICATION_JSON).build();
+            }
+        }
+        return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access."))
+                .type(MediaType.APPLICATION_JSON)
+                .build();
+    }
+
+    @POST
+    @Path("/claims/bulk")
+    @Produces(MediaType.APPLICATION_JSON)
+    @Consumes(MediaType.APPLICATION_JSON)
+    public Response addBulkClaims(String input, @Context HttpServletRequest request,
+                                  @HeaderParam("X-XSRF-TOKEN") String token,
+                                  @HeaderParam("Origin") String origin,
+                                  @CookieParam("AccessToken") String  cookie) {
+
+
+        if(!authorization.hasBasicAuthorization(token, origin, cookie)){
+            return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. Maybe you are not registered."))
+                    .type(MediaType.APPLICATION_JSON)
+                    .build();
+        }
+
+        UserInfo userInfo = authorization.getUserHandler().getUserInfo(token);
+        if(authorization.isRegistered(userInfo)) {
+            ArrayList<String> insertedIds = new ArrayList<String>();
+            JsonArray errorInClaims = new JsonArray();
+
+            int code200 = 0;
+            int code400 = 0;
+            int code500 = 0;
+
+            JsonArray jsonArray = new JsonParser().parse(input).getAsJsonArray();
+            for (JsonElement je : jsonArray) {
+                JsonObject jsonObject = je.getAsJsonObject();
+
+                String claimedBy = userInfo.getEmail();
+                logger.info("claimedBy " + claimedBy);
+                logger.debug(jsonObject);
+
+
+                EmailValidator emailValidator = EmailValidator.getInstance();
+                if (!emailValidator.isValid(claimedBy)) {
+                    jsonObject.addProperty("error", "user");
+                    logger.error("no valid user");
+                    //                return Response.status(Response.Status.BAD_REQUEST).entity(compose400Message("User e-mail is invalid."))
+                    //                        .type(MediaType.APPLICATION_JSON).build();
+                    code400++;
+                    errorInClaims.add(jsonObject);
+                }
+
+
+                try {
+                    String claimId = this.getInfoAndBuildClaim(jsonObject,claimedBy);
+                    insertedIds.add(claimId);
+                    code200++;
+                    //                return Response.status(200).entity(compose201PostMessage(request, claimId)).type(MediaType.APPLICATION_JSON).build();
+
+                } catch (ClaimValidationException ve) {
+//                    logger.error("Validation Failed fo claim "+jsonObject);
+                    //                return Response.status(Response.Status.BAD_REQUEST).entity(compose400Message("The given ids are wrong.", ve))
+                    //                        .type(MediaType.APPLICATION_JSON).build();
+                    jsonObject.addProperty("error", "validation");
+                    errorInClaims.add(jsonObject);
+                    code400++;
+
+                } catch (SQLStoreException|Exception e) {
+                    logger.error("Fail to add new claim.", e);
+                    //                return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500Message("Fail to add new claim.", e))
+                    //                        .type(MediaType.APPLICATION_JSON).build();
+                    jsonObject.addProperty("error", "insertion");
+                    errorInClaims.add(jsonObject);
+                    code500++;
+                }
+            }
+            if (jsonArray.size() == code500) {
+                return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500BulkInsertMessage("Fail to add new claim.", insertedIds, errorInClaims))
+                        .type(MediaType.APPLICATION_JSON).build();
+            } else if (code200 > 0) {
+                return Response.status(200).entity(compose201BulkInsertMessage(insertedIds, errorInClaims)).type(MediaType.APPLICATION_JSON).build();
+            } else {
+                return Response.status(Response.Status.BAD_REQUEST).entity(compose400BulkInsertMessage("The given ids are wrong.", insertedIds, errorInClaims))
+                        .type(MediaType.APPLICATION_JSON).build();
+            }
+        }
+        return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. You are not registered."))
+                .type(MediaType.APPLICATION_JSON)
+                .build();
+
+    }
+    @POST
+    @Path("/curate/bulk")
+    @Produces(MediaType.APPLICATION_JSON)
+    @Consumes(MediaType.APPLICATION_JSON)
+    public Response curateBulkClaims(String input, @Context HttpServletRequest request,
+                                     @HeaderParam("X-XSRF-TOKEN") String token,
+                                     @HeaderParam("Origin") String origin,
+                                     @CookieParam("AccessToken") String  cookie) {
+
+
+        if(!authorization.hasBasicAuthorization(token, origin, cookie)){
+            return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. Maybe you are not registered."))
+                    .type(MediaType.APPLICATION_JSON)
+                    .build();
+        }
+        UserInfo userInfo = authorization.getUserHandler().getUserInfo(token);
+        if (authorization.isRegistered(userInfo)) {
+            ArrayList<String> insertedIds = new ArrayList<String>();
+            JsonArray errorInClaims = new JsonArray();
+            int code200 = 0;
+            int code400 = 0;
+            int code500 = 0;
+            JsonArray jsonArray = new JsonParser().parse(input).getAsJsonArray();
+            String curatedBy =userInfo.getEmail();
+
+            for (JsonElement je : jsonArray) {
+                JsonObject jsonObject = je.getAsJsonObject();
+
+                String id = jsonObject.get("id").getAsString();
+                logger.info("id " + id);
+
+                Boolean approved = jsonObject.get("approved").getAsBoolean();
+                logger.info("approved " + approved);
+                EmailValidator emailValidator = EmailValidator.getInstance();
+                if (!emailValidator.isValid(curatedBy)) {
+                    jsonObject.addProperty("error", "user");
+                    //                return Response.status(Response.Status.BAD_REQUEST).entity(compose400Message("User e-mail is invalid."))
+                    //                        .type(MediaType.APPLICATION_JSON).build();
+                    code400++;
+                    errorInClaims.add(jsonObject);
+                }
+
+                try {
+                    claimHandler.updateClaimCurationInfo(curatedBy,id, approved);
+                    insertedIds.add(id);
+                    code200++;
+
+                } catch (SQLStoreException|Exception e) {
+                    jsonObject.addProperty("error", "insertion");
+                    errorInClaims.add(jsonObject);
+                    code500++;
+                }
+            }
+            if (jsonArray.size() == code500) {
+                return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500BulkInsertMessage("Fail to update claims.", insertedIds, errorInClaims))
+                        .type(MediaType.APPLICATION_JSON).build();
+            } else if (code200 > 0) {
+                return Response.status(200).entity(compose201BulkInsertMessage(insertedIds, errorInClaims)).type(MediaType.APPLICATION_JSON).build();
+            } else {
+                return Response.status(Response.Status.BAD_REQUEST).entity(compose400BulkInsertMessage("The given ids are wrong.", insertedIds, errorInClaims))
+                        .type(MediaType.APPLICATION_JSON).build();
+            }
+        }
+        return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. You are not registered."))
+                .type(MediaType.APPLICATION_JSON)
+                .build();
+
+    }
+    @POST
+    @Path("/feed/bulk")
+    @Produces(MediaType.APPLICATION_JSON)
+    @Consumes(MediaType.APPLICATION_JSON)
+    public Response feedBulkRecords(String input, @Context HttpServletRequest request,
+                                    @HeaderParam("X-XSRF-TOKEN") String token,
+                                    @HeaderParam("Origin") String origin,
+                                    @CookieParam("AccessToken") String  cookie) {
+
+
+        if(!authorization.hasBasicAuthorization(token, origin, cookie)){
+
+            return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. Maybe you are not registered."))
+                    .type(MediaType.APPLICATION_JSON)
+                    .build();
+        }
+
+        if (authorization.isRegistered(token)) {
+            ArrayList<String> insertedIds = new ArrayList<String>();
+            JsonArray errorInClaims = new JsonArray();
+            int code200 = 0;
+            int code400 = 0;
+            int code500 = 0;
+            JsonArray jsonArray = new JsonParser().parse(input).getAsJsonArray();
+            for (JsonElement je : jsonArray) {
+                JsonObject jsonObject = je.getAsJsonObject();
+                Boolean inserted = directIndexHandler.insertRecord(new Gson().toJson(jsonObject.get("record")));
+                if (inserted) {
+                    insertedIds.add(jsonObject.get("id").getAsString());
+                    code200++;
+                } else {
+                    errorInClaims.add(jsonObject.get("id").getAsString());
+                    code400++;
+                }
+
+
+            }
+            if (jsonArray.size() == code500) {
+                return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500BulkInsertMessage("Fail to add new claim.", insertedIds, errorInClaims))
+                        .type(MediaType.APPLICATION_JSON).build();
+            } else if (code200 > 0) {
+                return Response.status(200).entity(compose201BulkInsertMessage(insertedIds, errorInClaims)).type(MediaType.APPLICATION_JSON).build();
+            } else {
+                return Response.status(Response.Status.BAD_REQUEST).entity(compose400BulkInsertMessage("The given ids are wrong.", insertedIds, errorInClaims))
+                        .type(MediaType.APPLICATION_JSON).build();
+            }
+        }
+        return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. You are not registered."))
+                .type(MediaType.APPLICATION_JSON)
+                .build();
+
+    }
+
+    @GET
+    @Path("/users/notification")
+    @Produces(MediaType.APPLICATION_JSON)
+    public Response getUserEmailNotificationPreferences(@QueryParam("communityId") String openaireId,
+                                                        @HeaderParam("X-XSRF-TOKEN") String token,
+                                                        @CookieParam("AccessToken") String  cookie,
+                                                        @Context HttpServletRequest request) {
+
+        if(token == null || token.isEmpty() || cookie == null || cookie.isEmpty() || !cookie.equals(token)){
+            return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. Maybe you are not registered."))
+                    .type(MediaType.APPLICATION_JSON)
+                    .build();
+        }
+
+        UserInfo userInfo = authorization.getUserHandler().getUserInfo(token);
+        if(authorization.isRegistered(userInfo)) {
+            String userMail = userInfo.getEmail();
+            logger.debug("User is registerd "  );
+
+            EmailValidator emailValidator = EmailValidator.getInstance();
+
+            if (userMail == null || userMail.isEmpty()) {
+                return Response.status(Response.Status.BAD_REQUEST).entity(compose400Message("User e-mail cannot be empty."))
+                        .type(MediaType.APPLICATION_JSON).build();
+            }
+
+            if (!emailValidator.isValid(userMail)) {
+                return Response.status(Response.Status.BAD_REQUEST).entity(compose400Message("User e-mail is not valid."))
+                        .type(MediaType.APPLICATION_JSON).build();
+            }
+
+            List<Notification> notifications = null;
+            try {
+                if(openaireId != null) {
+//                    CommunityUtils communityInfo = this.emailSender.getCommunityUtils().getCommunityInfo(openaireId);
+                    if(this.emailSender.getManagerUtils().isCommunityManager(openaireId, userMail) || authorization.isCommunityCurator(userInfo)) {
+
+                        Notification notification = null;
+                        logger.debug("About to fetch notification");
+                        notification = fetchNotificationHandler.fetchNotification(openaireId, userMail);
+
+                        if (notification != null) {
+                            notifications = new ArrayList<Notification>();
+                            notification.setOpenaireName(openaireId);
+                            notifications.add(notification);
+                        }
+                    }else{
+                        return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. You are not registered."))
+                                .type(MediaType.APPLICATION_JSON)
+                                .build();
+                    }
+                } else {
+                    Map<String, String> projectIdsAndNames = fetchProjectHandler.fetchProjectIdsAndNamesByProjectManagerMail(userMail);
+                    if(projectIdsAndNames != null) {
+                        for (Map.Entry<String, String> projectIdAndName : projectIdsAndNames.entrySet()) {
+                            Notification notification = null;
+                            logger.debug("About to fetch notification");
+                            notification = fetchNotificationHandler.fetchNotification(projectIdAndName.getKey(), userMail);
+
+                            if (notifications == null) {
+                                notifications = new ArrayList<Notification>();
+                            }
+                            if(notification == null) {
+                                notification = new Notification(projectIdAndName.getKey(), projectIdAndName.getValue(), userMail, Integer.parseInt(defaultFrequencyInHours), true);
+                            } else {
+                                notification.setOpenaireName(projectIdAndName.getValue());
+                            }
+                            notifications.add(notification);
+                            logger.debug(notification);
+                            logger.debug("notification openaireId:"+notification.getOpenaireId());
+                            logger.debug(notifications.size());
+                        }
+                    }
+                }
+
+            } catch (SQLStoreException|Exception e) {
+                logger.error("Could not fetch notification preferences for user with mail " + userMail, e);
+                return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500Message("Fail to fetch notification preferences" +
+                        " for user with e-mail " + userMail + ".", e)).type(MediaType.APPLICATION_JSON).build();
+            }
+
+            if (notifications == null || notifications.isEmpty()) {
+                return Response.status(Response.Status.NOT_FOUND).entity(compose404Message("There are no notifications for user with mail " + userMail)).type(MediaType.APPLICATION_JSON).build();
+            }
+
+            return Response.status(200).entity(composeDataResponse(notifications)).build();
+
+        }
+        logger.debug("User is *NOT* registerd "  );
+        return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. You are not registered."))
+                .type(MediaType.APPLICATION_JSON)
+                .build();
+    }
+
+    @POST
+    @Path("/users/notification/save")
+    @Produces(MediaType.APPLICATION_JSON)
+    @Consumes(MediaType.APPLICATION_JSON)
+    public Response saveOrUpdateUserEmailNotificationPreferences(String input, @Context HttpServletRequest request,
+                                                                 @HeaderParam("X-XSRF-TOKEN") String token,
+                                                                 @HeaderParam("Origin") String origin,
+                                                                 @CookieParam("AccessToken") String  cookie) {
+
+
+        if(!authorization.hasBasicAuthorization(token, origin, cookie)){
+            return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. Maybe you are not registered."))
+                    .type(MediaType.APPLICATION_JSON)
+                    .build();
+        }
+        UserInfo userInfo = authorization.getUserHandler().getUserInfo(token);
+        if (authorization.isRegistered(userInfo)) {
+            ArrayList<String> insertedIds = new ArrayList<String>();
+            JsonArray errorInClaims = new JsonArray();
+            int code200 = 0;
+            int code400 = 0;
+            int code500 = 0;
+            JsonObject jsonObject = new JsonParser().parse(input).getAsJsonObject();
+
+            String userMail =userInfo.getEmail();
+
+            String openaireId = jsonObject.get("openaireId").getAsString();
+            logger.info("openaireId " + openaireId);
+
+            boolean notify = jsonObject.get("notify").getAsBoolean();
+            logger.info("notify "+notify);
+
+            int frequency = jsonObject.get("frequency").getAsInt();
+            logger.info("frequency " + frequency);
+
+            EmailValidator emailValidator = EmailValidator.getInstance();
+            if (!emailValidator.isValid(userMail)) {
+                jsonObject.addProperty("error", "user");
+                return Response.status(Response.Status.BAD_REQUEST).entity(compose400Message("User e-mail is invalid."))
+                        .type(MediaType.APPLICATION_JSON).build();
+            }
+
+            try {
+                boolean continueProcedure = false;
+                List<String> managers = null;
+                try {
+                    managers = fetchProjectHandler.fetchContactEmailsByProjectId(openaireId);
+                } catch (Exception e) {
+                    e.printStackTrace();
+                } catch (SQLStoreException e) {
+                    e.printStackTrace();
+                }
+                if(managers != null && managers.contains(userMail)) {
+                    continueProcedure = true;
+                } else {
+//                    CommunityUtils communityInfo = this.emailSender.getCommunityUtils().getCommunityInfo(openaireId);
+                    if(this.emailSender.getManagerUtils().isCommunityManager(openaireId, userMail) || authorization.isCommunityCurator(userInfo) ) {
+                        continueProcedure = true;
+                    }
+                }
+
+                if(continueProcedure) {
+                    Notification notification = null;
+                    logger.debug("About to fetch notification");
+                    notification = fetchNotificationHandler.fetchNotification(openaireId, userMail);
+
+                    if (notification == null) {
+                        logger.debug("About to insert notification");
+                        notificationHandler.buildAndInsertNotification(openaireId, userMail, frequency, notify);
+                    } else {
+                        logger.debug("About to update notification");
+                        notificationHandler.updateNotificationPreferences(openaireId, userMail, frequency, notify);
+                    }
+                } else {
+                    return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. You are not registered."))
+                            .type(MediaType.APPLICATION_JSON)
+                            .build();
+                }
+            } catch (SQLStoreException|Exception e) {
+                logger.error("Could not save or update notification preferences for user with mail " + userMail, e);
+                return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500Message("Fail to fetch notification preferences" +
+                        " for user with e-mail " + userMail + ".", e)).type(MediaType.APPLICATION_JSON).build();
+            }
+
+            return Response.status(200).entity(compose200Message("Save or Update for notification successful")).type(MediaType.APPLICATION_JSON).build();
+        }
+        return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. You are not registered."))
+                .type(MediaType.APPLICATION_JSON)
+                .build();
+    }
+
+    private String xml2Json(List<String> input) {
+        StringBuilder builder = new StringBuilder();
+        for(String category: input) {
+            builder.append(category);
+        }
+        return builder.toString();
+    }
+
+    private  String compose200Message(String message){
+        return " { \"status\" : \"success\", \"code\": \"200\", \"message\" : \"  " + message +" \" }";
+    }
+
+    private String compose204Message(String message) {
+        return  "{ \"status\" : \"error\", \"code\" : \"204\", \"message\" : \"  " + message +" \" }";
+    }
+
+    private String compose400Message(String message) {
+        return  "{ \"status\" : \"error\", \"code\" : \"400\", \"message\" : \"  " + message +" \" }";
+    }
+
+    private String compose400Message(String message, Exception exception) {
+        return  "{ \"status\" : \"error\", \"code\" : \"400\", \"message\" : \"  " + message +"\", " +
+                "\"description\" : \""+  exception.getMessage() +"\" }";
+    }
+
+    private String compose403Message(String message) {
+        return  "{ \"status\" : \"error\", \"code\" : \"403\", \"message\" : \"  " + message +"\", " +
+                "\"description\" : \"\" }";
+    }
+
+    private String compose404BulkDeleteMessage(String message, List<String> deletedIds, List<String> notFoundIds) {
+        return  "{ \"status\" : \"error\", \"code\" : \"404\", \"message\" : \"  " + message +" \","+  "\"deletedIds\" : " + new Gson().toJson(deletedIds) +","+  "\"notFoundIds\" : " + new Gson().toJson(notFoundIds) + " }";
+    }
+    private String compose404Message(String message) {
+        return  "{ \"status\" : \"error\", \"code\" : \"404\", \"message\" : \"  " + message +" \" }";
+    }
+
+    private String compose400BulkInsertMessage(String message, List<String> insertedIds,JsonArray errorInClaims) {
+        return  "{ \"status\" : \"error\", \"code\" : \"400\", \"message\" : \"  " + message +" \""+  ", \"insertedIds\" : " + new Gson().toJson(insertedIds) +","+  "\"errorInClaims\" : " + new Gson().toJson(errorInClaims) + " }";
+    }
+
+    private String compose500Message(String message, Throwable throwable) {
+        return  "{ \"status\" : \"fail\", \"code\" : \"500\", \"message\" : \"  " + message + "\", " +
+                "\"description\" : \""+  throwable.getMessage() +"\" }";
+    }
+
+    private String compose500BulkInsertMessage(String message,  List<String> insertedIds, JsonArray errorInClaims) {
+        return  "{ \"status\" : \"fail\", \"code\" : \"500\", \"message\" : \"  " + message + "\", " +
+                "\"description\" : \""+   "\" , " +  "\"insertedIds\" : " + new Gson().toJson(insertedIds) +","+  "\"errorInClaims\" : " + new Gson().toJson(errorInClaims) + " }";
+    }
+
+    /*
+    TODO check if needed
+    private String compose500BulkDeleteMessage(String message,  List<String> deletedIds, List<String> notFoundIds, Exception exception) {
+        return  "{ \"status\" : \"fail\", \"code\" : \"500\", \"message\" : \"  " + message + "\", " +
+                "\"description\" : \""+  exception.getMessage() +"\" ," +  "\"deletedIds\" : " + new Gson().toJson(deletedIds) +","+  "\"notFoundIds\" : " + new Gson().toJson(notFoundIds) + " }";
+    }
+
+
+
+    TODO check if needed
+    private  String compose204Message(){
+        return " { \"status\" : \"success\", \"code\": \"204\" }";
+    } */
+
+    private  String compose204BulkDeleteMessage(List<String> deletedIds, List<String> notFoundIds){
+        return " { \"status\" : \"success\", \"code\": \"204\", "+ "\"deletedIds\" : " + new Gson().toJson(deletedIds) +","+  "\"notFoundIds\" : " + new Gson().toJson(notFoundIds) + "}";
+    }
+
+
+    private  String compose201PostMessage(@Context HttpServletRequest request, String claimId){
+        String url = request.getRequestURL().toString();
+        //String query = request.getQueryString();
+
+        return " { \"status\" : \"success\", \"code\": \"201\", \"link\": \"" + url  +"/"+ claimId +"\" }";
+    }
+    private  String compose201BulkInsertMessage(List<String> insertedIds, JsonArray errorInClaims){
+        //String url = request.getRequestURL().toString();
+        //String query = request.getQueryString();
+
+        return " { \"status\" : \"success\", \"code\": \"201\","+ "\"insertedIds\" : " + new Gson().toJson(insertedIds) +","+  "\"errorInClaims\" : " + new Gson().toJson(errorInClaims)+ "}";
+    }
+    private String composeDataResponse(HttpServletRequest request, List<Claim> claims, int total, int offset, int limit) {
+        if(offset != -1 && limit != -1) {   // if offset and limit are -1, no paging in the response
+            return " { \"status\" : \"success\", \"code\": \"200\",  "+composeTotalResults(total)+", " + composePaging(request, total, offset, limit) + ", "
+                    + "\"data\" : " + new Gson().toJson(claims) + " }";
+        } else {
+            return " { \"status\" : \"success\", \"code\": \"200\",  "+composeTotalResults(total)+", "
+                    + "\"data\" : " + new Gson().toJson(claims) + " }";
+        }
+    }
+
+    private String composeDataResponse(String xml) {
+        return " { \"status\" : \"success\", \"code\": \"200\", "
+                + "\"data\" : " + XML.toJSONObject(xml).toString() + " }";
+    }
+
+    private String composeDataResponse(Claim claim) {
+        return " { \"status\" : \"success\", \"code\": \"200\", " + "\"data\" : " + new Gson().toJson(claim) + " }";
+    }
+
+    private String composeDataResponse(List<Notification> notifications) {
+        return " { \"status\" : \"success\", \"code\": \"200\", " + "\"data\" : " + new Gson().toJson(notifications) + " }";
+    }
+
+    private static String composePaging(HttpServletRequest request, int total, int currentOffset, int limit) {
+        logger.info("total " + total);
+        logger.info("currentOffset " + currentOffset);
+        logger.info("limit " + limit);
+
+        String url = request.getRequestURL().toString();
+        //String query = request.getQueryString();
+
+        String first = url+"?offset=0&limit=20";
+
+        int previousPage;
+        int nextPage;
+        int lastPage;
+
+        if (total <= limit) {
+            lastPage = 0;
+        } else {
+            if(total%limit == 0) {
+                lastPage = total/limit-1;
+            } else {
+                lastPage = total/limit ;
+            }
+        }
+        String last = url+"?offset=" + lastPage + "&limit=20";
+
+        if (currentOffset-1 <= 0) {
+            previousPage = 0;
+        } else {
+            previousPage = currentOffset-1;
+        }
+        String previous = url+"?offset=" + previousPage + "&limit=20";
+
+        if (currentOffset+1 >= lastPage) {
+            nextPage = lastPage;
+
+        } else {
+            nextPage = currentOffset + 1;
+        }
+        String next = url+"?offset=" + nextPage + "&limit=20";
+
+        return "\"paging\": [" +  "{\"rel\":\"first\", \"href\":\"" + first +"\"}, {\"rel\":\"last\", \"href\":\"" + last + "\"}, {\"rel\":\"previous\", \"href\": \"" + previous + "\"}, {\"rel\":\"next\", \"href\":\"" +  next +"\"}"+ "]";
+    }
+    private String composeTotalResults(int total) {
+        return "\"total\": \""+total+"\"";
+    }
+
+    public static void main(String[] args) {
+
+/*
+         EmailValidator emailValidator = EmailValidator.getInstance();
+         System.out.println(emailValidator.isValid("jate@gdddd"));
+
+         InternetAddress emailAddr = null;
+         try {
+             emailAddr = new InternetAddress("jate@gdddd");
+             emailAddr.validate();
+         } catch (AddressException e) {
+             System.out.println("false");
+         }
+         System.out.println("true");
+
+         ArrayList<String> insertedIds= new ArrayList<String>();
+         insertedIds.add("1");
+         insertedIds.add("2");
+         insertedIds.add("3");
+         System.out.println(helloWorldService.compose403Message("hello"));
+
+*/
+//         BasicConfigurator.configure();
+//         ApplicationContext context = new ClassPathXmlApplicationContext("eu/dnetlib/openaire/rest/springContext-claims-authorization.xml");
+//
+//         Authorization authorization =  context.getBean(Authorization.class);
+//         UserHandler userHandler = context.getBean(UserHandler.class);
+//         System.out.println(authorization.getAdminRoles());
+//         authorization.isClaimCurator("eyJraWQiOiJvaWRjIiwiYWxnIjoiUlMyNTYifQ.eyJzdWIiOiIwOTMxNzMwMTMyODMzNjMyQG9wZW5taW50ZWQuZXUiLCJhenAiOiIyNGU4MzE3Ni0xMzEyLTRiYTMtYmMwYi1mZmVlYmVhMTYwM2UiLCJpc3MiOiJodHRwczpcL1wvYWFpLm9wZW5taW50ZWQuZXVcL29pZGNcLyIsImV4cCI6MTQ5ODQ4NTk3NiwiaWF0IjoxNDk4NDcxNTc2LCJqdGkiOiJkMWRlZjc1Yi00MTEyLTRiZDktYTIyNi0wZThhOWI2M2Y3MWQifQ.WVYOb_yO8OaxIIt2jRYEDQBhGGFRDTBw3DgtVV_smuN5yx1ScCj6aehLu3JKPSArme4m2SGF4TEGhpwNJkwhM2WapGtxmtuCmCzYIo_QlC1Yki9hr2OT2rXMcQsJCiKaBSf6pLue6Sn78GMB5yaUTvOQHRgidXGiZXH5lsuZUx15Q6Equ_wzond_rgP9mRheRkTyIFuvvg4PuzmudBc11Ty863vIIQtoWF7_p98zTbHxiNF9lLPwzPZKxDoQ8JeayQEC-jsWVLgxmp-h0jG_Ko5jFVVJeeosqMMucOrs2FT_NKHVYVqB6VVh0C6nOufeiLrNDeMUlDT4dAvKD2zE9w");
+
+    }
+
+//    @GET
+//    @Path("email-notifications")
+//    public void forceSendEmailNotifications() {
+//        emailSender.run();
+//    }
+
+    @GET
+    @Path("test-email")
+    public void testEmail() {
+        ArrayList<String> list = new ArrayList<String>();
+        list.add("konstantinagalouni@gmail.com");
+        list.add("argirok@di.uoa.gr");
+        emailSender.send("openaire_id_test", "openaire_name_test", "community", list);
+    }
+
+    private String getvalueOf(JsonObject jsonObject, String field){
+        String value = (jsonObject.get(field) != null && !jsonObject.get(field).isJsonNull())?jsonObject.get(field).getAsString():null;
+        logger.info(field + ": " + value);
+        return value;
+
+
+    }
+    private String getvalueOfDefault(JsonObject jsonObject, String field, String defaultValue){
+        String value = this.getvalueOf(jsonObject, field);
+        logger.debug("Field:"+field+"->"+value+"<-");
+        return (value!=null && !value.equals("")?value:defaultValue);
+    }
+
+    private String getInfoAndBuildClaim(JsonObject jsonObject, String claimedBy ) throws SQLStoreException, Exception {
+        String claimedInDashboard = getvalueOfDefault(jsonObject, "claimedInDashboard", null);
+
+        String sourceId = getvalueOf(jsonObject, "sourceId");
+        String sourceType = getvalueOf(jsonObject, "sourceType");
+        String sourceCollectedFrom = getvalueOf(jsonObject, "sourceCollectedFrom");
+        String sourceAccessRights = getvalueOf(jsonObject, "sourceAccessRights");
+        String sourceEmbargoEndDate = getvalueOfDefault(jsonObject, "sourceEmbargoEndDate", null);
+
+        String targetId = getvalueOf(jsonObject, "targetId");
+        String targetType = getvalueOf(jsonObject, "targetType");
+        String targetCollectedFrom = getvalueOf(jsonObject, "targetCollectedFrom");
+        String targetAccessRights = getvalueOf(jsonObject, "targetAccessRights");
+        String targetEmbargoEndDate = getvalueOfDefault(jsonObject, "targetEmbargoEndDate", null);
+
+
+        logger.debug("Claimed in"+claimedInDashboard);
+        return claimHandler.buildAndInsertClaim(claimedBy, sourceType, sourceId, sourceCollectedFrom, sourceAccessRights, sourceEmbargoEndDate, targetType, targetId, targetCollectedFrom, targetAccessRights, targetEmbargoEndDate,claimedInDashboard);
+    }
+    
+  
+}
Index: modules/uoa-claims-api/tags/uoa-claims-api-2.1.0/src/main/java/eu/dnetlib/openaire/rest/MetricsService.java
===================================================================
--- modules/uoa-claims-api/tags/uoa-claims-api-2.1.0/src/main/java/eu/dnetlib/openaire/rest/MetricsService.java	(nonexistent)
+++ modules/uoa-claims-api/tags/uoa-claims-api-2.1.0/src/main/java/eu/dnetlib/openaire/rest/MetricsService.java	(revision 62533)
@@ -0,0 +1,210 @@
+package eu.dnetlib.openaire.rest;
+
+
+import com.google.gson.JsonObject;
+import eu.dnetlib.data.claims.entity.Metrics;
+import eu.dnetlib.data.claims.handler.MetricsHandler;
+import eu.dnetlib.data.claims.sql.SQLStoreException;
+import org.apache.logging.log4j.LogManager;
+import org.apache.logging.log4j.Logger;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+import org.springframework.web.bind.annotation.CrossOrigin;
+
+import javax.ws.rs.CookieParam;
+import javax.ws.rs.GET;
+import javax.ws.rs.Path;
+import javax.ws.rs.Produces;
+import javax.ws.rs.core.MediaType;
+import java.sql.SQLException;
+import java.util.HashMap;
+import java.util.Map;
+
+
+@Component
+@CrossOrigin(origins = "*")
+@Path("/report")
+public class MetricsService {
+    private static final Logger logger = LogManager.getLogger(MetricsService.class);
+
+    @Autowired
+    public Authorization authorization = null;
+
+    @Autowired
+    private MetricsHandler metricsHandler = null;
+
+    public static void main(String[] args) {}
+
+
+//    @GET
+//    @Path("/euprojects")
+//    @Produces(MediaType.APPLICATION_JSON)
+//    public Response getNumOfEUProjects() {
+//        try {
+//            int count = metricsHandler.countEUProjects();
+//            return Response.status(200).entity(composeDataResponse(count)).build();
+//        } catch (SQLStoreException |Exception e) {
+//            logger.error("Could not fetch number of EU projects", e);
+//            return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(
+//                    compose500Message("Fail to fetch number of EU projects.", e)).
+//                    type(MediaType.APPLICATION_JSON).build();
+//        }
+//    }
+//
+//
+//    @GET
+//    @Path("/countries")
+//    @Produces(MediaType.APPLICATION_JSON)
+//    public Response getNumOfCountriesInClaims() {
+//        try {
+//            int count = metricsHandler.countCountriesFromClaimedBy();
+//            return Response.status(200).entity(composeDataResponse(count)).build();
+//        } catch (SQLStoreException |Exception e) {
+//            logger.error("Could not fetch number of countries for people who claimed", e);
+//            return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(
+//                    compose500Message("Fail to fetch number of countries for people who claimed.", e)).
+//                    type(MediaType.APPLICATION_JSON).build();
+//        }
+//    }
+//
+//    @GET
+//    @Path("/research-results")
+//    @Produces(MediaType.APPLICATION_JSON)
+//    public Response getNumOfUniqueResearchResults() {
+//        try {
+//            int count = metricsHandler.countUniqueResearchResults();
+//            return Response.status(200).entity(composeDataResponse(count)).build();
+//        } catch (SQLStoreException |Exception e) {
+//            logger.error("Could not fetch number of unique research results claimed", e);
+//            return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(
+//                    compose500Message("Fail to fetch number of unique research results claimed.", e)).
+//                    type(MediaType.APPLICATION_JSON).build();
+//        }
+//    }
+
+    @GET
+    @Path("/calc")
+    @Produces(MediaType.TEXT_PLAIN)
+    public String calculateMetrics(
+//            @HeaderParam("X-XSRF-TOKEN") String token,
+            @CookieParam("AccessToken") String  cookie
+    ) throws SQLStoreException, Exception {
+        if(cookie == null || cookie.isEmpty()){
+            return "Forbidden: You don't have permission to access. Maybe you are not registered.";
+        }
+
+        if(authorization.isPortalAdministrator(cookie)) {
+            metricsHandler.calculateMetrics();
+            return "metrics calculated!";
+        }
+        return "Forbidden: You don't have permission to access.";
+    }
+
+    @GET
+    @Path("/metrics")
+    @Produces(MediaType.TEXT_PLAIN)
+    public String getMetrics() throws SQLStoreException, SQLException {
+        Metrics metrics = metricsHandler.getMetrics();
+
+        String response = "";
+
+        if(metrics != null) {
+//            response += "# TYPE claims gauge\n";
+//            response += "claims " + metrics.getTotal_claims() + "\n";
+//
+//            response += "# TYPE claims_users gauge\n";
+//            response += "claims_users " + metrics.getTotal_users() + "\n";
+//
+//            response += "# TYPE claims_projects gauge\n";
+//            response += "claims_projects " + metrics.getProjects() + "\n";
+//
+//            response += "# TYPE claims_eu_projects gauge\n";
+//            response += "claims_eu_projects " + metrics.getEu_projects() + "\n";
+//
+//            response += "# TYPE claims_countries gauge\n";
+//            response += "claims_countries " + metrics.getCountries() + "\n";
+//
+//            response += "# TYPE claims_unique_research_results gauge\n";
+//            response += "claims_unique_research_results " + metrics.getResearch_results() + "\n";
+
+            Map<String, Integer> worksPerDashboard = new HashMap<>();
+            // 1st approach
+//            response += "# TYPE orcid_works gauge\n";
+
+            response += "# TYPE claims_recorded gauge\n";
+            for(JsonObject dashboardMetrics : metrics.getMetrics_per_dashboard()) {
+                if(dashboardMetrics.get("claims") != null) {
+                    response += "claims_recorded{environment=" + dashboardMetrics.get("environment") + " portal=" + dashboardMetrics.get("dashboard") + "}" + " " + dashboardMetrics.get("claims") + "\n";
+                }
+            }
+
+            response += "# TYPE claims_users gauge\n";
+            for(JsonObject dashboardMetrics : metrics.getMetrics_per_dashboard()) {
+                if(dashboardMetrics.get("users") != null) {
+                    response += "claims_users{environment=" + dashboardMetrics.get("environment") + " portal=" + dashboardMetrics.get("dashboard") + "}" + " " + dashboardMetrics.get("users") + "\n";
+                }
+            }
+
+            response += "# TYPE claims_projects gauge\n";
+            for(JsonObject dashboardMetrics : metrics.getMetrics_per_dashboard()) {
+                if(dashboardMetrics.get("projects") != null) {
+                    response += "claims_projects{environment=" + dashboardMetrics.get("environment") + " portal=" + dashboardMetrics.get("dashboard") + "}" + " " + dashboardMetrics.get("projects") + "\n";
+                }
+            }
+
+            response += "# TYPE claims_eu_projects gauge\n";
+            for(JsonObject dashboardMetrics : metrics.getMetrics_per_dashboard()) {
+                if(dashboardMetrics.get("eu_projects") != null) {
+                    response += "claims_eu_projects{environment=" + dashboardMetrics.get("environment") + " portal=" + dashboardMetrics.get("dashboard") + "}" + " " + dashboardMetrics.get("eu_projects") + "\n";
+                }
+            }
+
+            response += "# TYPE claims_countries gauge\n";
+            for(JsonObject dashboardMetrics : metrics.getMetrics_per_dashboard()) {
+                if(dashboardMetrics.get("countries") != null) {
+                    response += "claims_countries{environment=" + dashboardMetrics.get("environment") + " portal=" + dashboardMetrics.get("dashboard") + "}" + " " + dashboardMetrics.get("countries") + "\n";
+                }
+            }
+
+            response += "# TYPE claims_unique_research_results gauge\n";
+            for(JsonObject dashboardMetrics : metrics.getMetrics_per_dashboard()) {
+//            for(Object dashboardMetricsObj : (List) metrics.getMetrics_per_dashboard()) {
+//                Map<String, Object> dashboardMetrics = (HashMap<String, Object>) dashboardMetricsObj;
+                if(dashboardMetrics.get("research_results") != null) {
+                    response += "claims_unique_research_results{environment=" + dashboardMetrics.get("environment") + " portal=" + dashboardMetrics.get("dashboard") + "}" + " " + dashboardMetrics.get("research_results") + "\n";
+                }
+            }
+
+            if(metrics.getDate() != null) {
+                response += "claims_last_metrics_updater_run_timestamp_seconds " + (metrics.getDate().getTime() / 1000) + "\n";
+            }
+        }
+        return response;
+    }
+
+    private String composeResults(int total, String label) {
+        return "\""+label+"\": \""+total+"\"";
+    }
+
+    private String composeTotalResults(int total) {
+        return "\"total\": \""+total+"\"";
+    }
+
+    private String composeDataResponse(int count) {
+        return " { \"status\" : \"success\", \"code\": \"200\",  "+composeTotalResults(count) + " }";
+    }
+
+//    private String composeDataResponse(Metrics metrics) {
+//        return " { \"status\" : \"success\", \"code\": \"200\",  "
+//                +composeResults(metrics.getCountries(), "countries")
+//                +composeResults(metrics.getEu_projects(), "eu_projects")
+//                +composeResults(metrics.getResearch_results(), "research_results")+ " }";
+//    }
+
+    private String compose500Message(String message, Throwable throwable) {
+        return  "{ \"status\" : \"fail\", \"code\" : \"500\", \"message\" : \"  " + message + "\", " +
+                "\"description\" : \""+  throwable.getMessage() +"\" }";
+    }
+
+
+}
Index: modules/uoa-claims-api/tags/uoa-claims-api-2.1.0/src/main/java/eu/dnetlib/openaire/rest/authorization/Authorization.java
===================================================================
--- modules/uoa-claims-api/tags/uoa-claims-api-2.1.0/src/main/java/eu/dnetlib/openaire/rest/authorization/Authorization.java	(nonexistent)
+++ modules/uoa-claims-api/tags/uoa-claims-api-2.1.0/src/main/java/eu/dnetlib/openaire/rest/authorization/Authorization.java	(revision 62533)
@@ -0,0 +1,43 @@
+package eu.dnetlib.openaire.rest.authorization;
+
+import io.jsonwebtoken.Claims;
+import io.jsonwebtoken.Jwts;
+import org.apache.logging.log4j.LogManager;
+import org.apache.logging.log4j.Logger;
+
+import javax.xml.bind.DatatypeConverter;
+
+/**
+ * Created by sofia on 20/4/2017.
+ */
+public class Authorization {
+
+    private static Logger logger = LogManager.getLogger(Authorization.class);
+
+    public static boolean isRegistered(String token) {
+
+        Claims claims = Jwts.parser()
+                .setSigningKey(DatatypeConverter.parseBase64Binary("my-very-secret"))
+                .parseClaimsJws(token).getBody();
+
+        if (claims.get("role").equals(1) || claims.get("role").equals(2)) {
+            logger.debug(claims.get("role"));
+            return true;
+        } else {
+            return false;
+        }
+    }
+
+    public static boolean isAdmin(String token) {
+        Claims claims = Jwts.parser()
+                .setSigningKey(DatatypeConverter.parseBase64Binary("my-very-secret"))
+                .parseClaimsJws(token).getBody();
+
+        if (claims.get("role").equals(2)) {
+            return true;
+        } else {
+            return false;
+        }
+    }
+
+}
Index: modules/uoa-claims-api/tags/uoa-claims-api-2.1.0/src/main/java/eu/dnetlib/openaire/rest/inputHandler/UserHandler.java
===================================================================
--- modules/uoa-claims-api/tags/uoa-claims-api-2.1.0/src/main/java/eu/dnetlib/openaire/rest/inputHandler/UserHandler.java	(nonexistent)
+++ modules/uoa-claims-api/tags/uoa-claims-api-2.1.0/src/main/java/eu/dnetlib/openaire/rest/inputHandler/UserHandler.java	(revision 62533)
@@ -0,0 +1,130 @@
+package eu.dnetlib.openaire.rest.inputHandler;
+
+import com.google.gson.Gson;
+import eu.dnetlib.openaire.rest.UserInfo;
+import org.apache.logging.log4j.LogManager;
+import org.apache.logging.log4j.Logger;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.io.StringReader;
+import java.net.HttpURLConnection;
+import java.net.URL;
+
+/**
+ * Created by sofia on 20/4/2017.
+ */
+public class UserHandler{
+    private static Logger logger = LogManager.getLogger(UserHandler.class);
+
+    String userInfoUrl = null;
+//        public  String getMail(String token) {
+//
+//            Claims claims = Jwts.parser()
+//                    .setSigningKey(DatatypeConverter.parseBase64Binary("my-very-secret"))
+//                    .parseClaimsJws(token).getBody();
+//
+//            return (String) claims.get("email");
+//
+//        }
+
+    public  UserInfo getUserInfo(String accessToken){
+        String url=userInfoUrl+accessToken;
+        URL obj = null;
+        String responseStr=null;
+        logger.debug("User info url is "+url);
+
+            try {
+                obj = new URL(url);
+                HttpURLConnection con = (HttpURLConnection) obj.openConnection();
+                logger.debug("User info response code is: " + con.getResponseCode());
+                if (con.getResponseCode() != 200) {
+                    return null;
+                }
+                BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
+                StringBuffer response = new StringBuffer();
+                String inputLine;
+                while ((inputLine = in.readLine()) != null) {
+                    response.append(inputLine).append("\n");
+                }
+                in.close();
+                responseStr = response.toString();
+            }catch(Exception e){
+                logger.error("An error occured while trying to fetch user info ",e);
+                return null;
+            }
+        return json2UserInfo(responseStr);
+    }
+
+    private  UserInfo json2UserInfo(String json) {
+
+//        logger.debug("Try to create userInfo class from json: "+json);
+         if (json == null){
+            return null;
+        }
+
+        BufferedReader br = new BufferedReader(new StringReader(json));
+        //convert the json string back to object
+        Gson gson = new Gson();
+        UserInfo userInfo = null;
+        try {
+            userInfo = gson.fromJson(br, UserInfo.class);
+        }catch(Exception e){
+            logger.debug("Error in parsing json response. Given json is : "+json, e);
+            return null;
+        }
+
+//        logger.debug("Original response.........: "+userInfo.toString());
+        try {
+        if(userInfo != null && userInfo.getEdu_person_entitlements() != null ) {
+
+            for (int i = 0; i < userInfo.getEdu_person_entitlements().size(); i++) {
+                String role = userInfo.getEdu_person_entitlements().get(i);
+//                logger.debug("AAI role: "+role);
+                role = role.split(":")[role.split(":").length-1];
+                role = role.split("#")[0];
+                role = role.replace("+"," ");
+//                logger.debug("Adding parsed role : "+role);
+                userInfo.getEdu_person_entitlements().set(i,role);
+            }
+        }
+        }catch(Exception e){
+            logger.debug("Error in parsing  Edu_person_entitlements : ",e);
+            return null;
+        }
+        logger.debug("After handling roles : "+userInfo.toString());
+
+
+        return userInfo;
+    }
+
+    public String getUserInfoUrl() {
+        return userInfoUrl;
+    }
+
+    public void setUserInfoUrl(String userInfoUrl) {
+        this.userInfoUrl = userInfoUrl;
+    }
+
+    public static void main(String[] args) throws IOException {
+//        BasicConfigurator.configure();
+//        ApplicationContext context = new ClassPathXmlApplicationContext("eu/dnetlib/openaire/rest/springContext-claims-authorization.xml");
+//
+//        Authorization authorization =  context.getBean(Authorization.class);
+//        UserHandler userHandler = context.getBean(UserHandler.class);
+//        System.out.println("\n\nAdmin Roles "+authorization.getAdminRoles().size()+"   "+authorization.getAdminRoles()+"\n\n\n");
+//        System.out.println("\n\ngetProjectCuratorRoles Roles "+authorization.getProjectCuratorRoles().size()+"   "+authorization.getProjectCuratorRoles()+"\n\n\n");
+//        System.out.println("\n\ngetRegisteredRoles Roles "+authorization.getRegisteredRoles().size()+"   "+authorization.getRegisteredRoles()+"\n\n\n");
+//        System.out.println("\n\nIs Admin::\n"+authorization.isRegistered("eyJraWQiOiJvaWRjIiwiYWxnIjoiUlMyNTYifQ.eyJzdWIiOiIwOTMxNzMwMTMyODMzNjMyQG9wZW5taW50ZWQuZXUiLCJhenAiOiIyNGU4MzE3Ni0xMzEyLTRiYTMtYmMwYi1mZmVlYmVhMTYwM2UiLCJpc3MiOiJodHRwczpcL1wvYWFpLm9wZW5taW50ZWQuZXVcL29pZGNcLyIsImV4cCI6MTQ5OTg4MjI4NCwiaWF0IjoxNDk5ODY3ODg0LCJqdGkiOiIxNzJiOWNkYS1kNmZjLTQ3MTgtYTI1My02YTJjYmNiYmI0ZWIifQ.XtKm96oOeRe0_7mzr_NPdFAG6JJN3dh9Oy6-bFHE59UaN3TMuZAYgLND49vryWK_m4s23F_1TvZAN7WMDnkx3YH6RqTUsMS57sJGIOoDg4eYSzgDfLriyaANqp1Fh2PotMXWuFZXmtKdyLYw2jfcnBXjfd7DkMHylsFWII88GQVRFujsrJfjr5DKcz09Ad_tF874r-Emq0ARxtSHjmjp56cKmiia9GcjOgMVRMdUgArVKPToiMoYizXyG51t3yOnYI6JI0batB3UjmocX-YXBJmLZfS3zqlaKuf_hHgcs09EQK_McJ_igpgZ9CeBUHyDzzITtniLmftKB7o_AfxaMw")
+//                +"\n\n\n");
+//        userHandler.json2UserInfo("{\"sub\":\"123456@openminted.eu\",\"name\":\"όνομα και επιθετο\",\"given_name\":\"όνομα\",\"family_name\":\"επίθετο\",\"email\":\"mail1@mail.com\",\"edu_person_entitlements\":[\"urn:mace:openminted.eu:aai.openminted.eu:group:OpenAIRE+Super+Administrator\",\"urn:mace:openminted.eu:aai.openminted.eu:group:OpenAIRE+User+Manager\"]}");
+//        UserInfo u = userHandler.json2UserInfo("{\"sub\":\"12345678@openminted.eu\",\"name\":\" a name\",\"given_name\":\"a\",\"family_name\":\"name\",\"email\":\"mail2@mail.com\",\"edu_person_scoped_affiliations\":[\"faculty@university\"],\"edu_person_entitlements\":[\"urn:mace:openminted.eu:aai.openminted.eu:group:OpenAIRE+Super+Administrator\"]}");
+//        boolean b=authorization.isProjectCurator(u);
+//        System.out.println(b);
+//        userHandler.json2UserInfo("{\"sub\":\"1234567899@openminted.eu\",\"name\":\" test name\",\"given_name\":\"test\",\"family_name\":\"test surname\",\"email\":\"mail2@mail.com\",\"edu_person_scoped_affiliations\":[\"faculty@uni\"]}");
+//        userHandler.json2UserInfo(null);
+//        userHandler.json2UserInfo("mpla mpla mpla .... {}");
+//        userHandler.getUserInfo("eyJraWQiOiJvaWRjIiwiYWxnIjoiUlMyNTYifQ.eyJzdWIiOiIwOTMxNzMwMTMyODMzNjMyQG9wZW5taW50ZWQuZXUiLCJhenAiOiIyNGU4MzE3Ni0xMzEyLTRiYTMtYmMwYi1mZmVlYmVhMTYwM2UiLCJpc3MiOiJodHRwczpcL1wvYWFpLm9wZW5taW50ZWQuZXVcL29pZGNcLyIsImV4cCI6MTQ5ODQ4NTk3NiwiaWF0IjoxNDk4NDcxNTc2LCJqdGkiOiJkMWRlZjc1Yi00MTEyLTRiZDktYTIyNi0wZThhOWI2M2Y3MWQifQ.WVYOb_yO8OaxIIt2jRYEDQBhGGFRDTBw3DgtVV_smuN5yx1ScCj6aehLu3JKPSArme4m2SGF4TEGhpwNJkwhM2WapGtxmtuCmCzYIo_QlC1Yki9hr2OT2rXMcQsJCiKaBSf6pLue6Sn78GMB5yaUTvOQHRgidXGiZXH5lsuZUx15Q6Equ_wzond_rgP9mRheRkTyIFuvvg4PuzmudBc11Ty863vIIQtoWF7_p98zTbHxiNF9lLPwzPZKxDoQ8JeayQEC-jsWVLgxmp-h0jG_Ko5jFVVJeeosqMMucOrs2FT_NKHVYVqB6VVh0C6nOufeiLrNDeMUlDT4dAvKD2zE9w");
+    }
+}
Index: modules/uoa-claims-api/tags/uoa-claims-api-2.1.0/src/main/java/eu/dnetlib/openaire/rest/security/JWTValidator.java
===================================================================
--- modules/uoa-claims-api/tags/uoa-claims-api-2.1.0/src/main/java/eu/dnetlib/openaire/rest/security/JWTValidator.java	(nonexistent)
+++ modules/uoa-claims-api/tags/uoa-claims-api-2.1.0/src/main/java/eu/dnetlib/openaire/rest/security/JWTValidator.java	(revision 62533)
@@ -0,0 +1,66 @@
+package eu.dnetlib.openaire.rest.security;
+
+import io.jsonwebtoken.*;
+import org.apache.logging.log4j.LogManager;
+import org.apache.logging.log4j.Logger;
+
+import javax.xml.bind.DatatypeConverter;
+
+/**
+ * Created by kiatrop on 10/4/2017.
+ */
+public class JWTValidator {
+
+    private static final Logger logger = LogManager.getLogger(JWTValidator.class);
+
+    public static boolean isValid(String token) {
+
+        //String subject = "my-very-secret";
+        try {
+
+            //This line will throw an exception if it is not a signed JWS (as expected)
+            Claims claims = Jwts.parser()
+                .setSigningKey(DatatypeConverter.parseBase64Binary("my-very-secret"))
+                .parseClaimsJws(token).getBody();
+
+            logger.debug("Id: " + claims.get("userId"));
+            logger.debug("Subject: " + claims.getSubject());
+            logger.debug("Fullname: " + claims.get("fullname"));
+            logger.debug("Email: " + claims.get("email"));
+            logger.debug("Role: " + claims.get("role"));
+            logger.debug("Expiration: " + claims.getExpiration());
+
+            return true;
+
+        } catch (SignatureException e) {
+            logger.error("Either calculating a signature or verifying an existing signature of a JWT failed", e);
+            return false;
+        } catch(PrematureJwtException e) {
+            logger.error("A JWT was accepted before it is allowed to be accessed and must be rejected", e);
+            return false;
+        } catch(ClaimJwtException e){
+            logger.error("After a validation of a JWT claim failed", e);
+            return false;
+        } catch(MalformedJwtException e){
+            logger.error("A JWT was not correctly constructed and should be rejected", e);
+            return false;
+        } catch(UnsupportedJwtException e){
+            logger.error("Receiving a JWT in a particular format/configuration that does not match the format expected by the application", e);
+            return false;
+        }
+    }
+
+//    public static void main(String[] args) {
+//
+//        // valid (isValid("eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJBcmdpcm8iLCJmdWxsbmFtZSI6IkFyZ2lybyBLb2tvZ2lhbmFraSIsInVzZXJJZCI6IjgiLCJlbWFpbCI6ImFyZ2lyb0BnbWFpbC5jb20iLCJyb2xlIjoyLCJleHAiOjE0OTIwMDEyMzN9.u2xTTyjF6_n60yiz-Pfj72TQIaVNRgxt7Qe8w_AxoTBulKuiq6ldzZHDvgcef2jsA12TFRgfIyfXhsTj-04P5A"))
+//        // not valid "eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJBcmdpcm8iLCJmdWxsbmFtZSI6IkFyZ2lybyBLb2tvZ2lhbmFraSIsInVzZXJJZCI6IjgiLCJlbWFpbCI6ImFyZ2lyb0BnbWFpbC5jb20iLCJyb2xlIjoyLCJleHAiOjE0OTE5ODk2Njh9.JUiFGEverBVbo3eXlV2nX265cwNTYH1EJGZT0IcGyY31WUDHiGmtnTY-NwZsy0R93irVhAzVhTlmZI_DSRQ"
+//        //if (isValid("eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJzYmEiLCJmdWxsbmFtZSI6InNvZmlhICIsInVzZXJJZCI6IjYiLCJlbWFpbCI6InNvZmllX21wbEBob3RtYWlsLmNvbSIsInJvbGUiOjEsImV4cCI6MTQ5Mjc3ODY2M30.LcgYcBuI0V8tsZZR_Pnnb5Kk0_GfblxNC6FH1CHT2q7u4j9hcETb1EYLIKPZdkErXJ_MSC1jHNUiS5qCzEQQ2w"))
+//
+//        if(isValid("eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJBcmdpcm8iLCJmdWxsbmFtZSI6IkFyZ2lybyBLb2tvZ2lhbmFraSIsInVzZXJJZCI6IjgiLCJlbWFpbCI6ImFyZ2lyb0BnbWFpbC5jb20iLCJyb2xlIjoyLCJleHAiOjE0OTI3ODY4MTl9.F-cFGmSvZLAF70PCz9PE6jOwSg6aAiUW2lklkS-eKCxkjwbqPJLWlNWP10Czg4j1_iKDTvHR7wbhbRyJPoqvNQ"))
+//            System.out.println("Valid");
+//        else
+//            System.out.println("Not Valid");
+//
+//    }
+
+}
Index: modules/uoa-claims-api/tags/uoa-claims-api-2.1.0/src/main/java/eu/dnetlib/openaire/rest/UserInfo.java
===================================================================
--- modules/uoa-claims-api/tags/uoa-claims-api-2.1.0/src/main/java/eu/dnetlib/openaire/rest/UserInfo.java	(nonexistent)
+++ modules/uoa-claims-api/tags/uoa-claims-api-2.1.0/src/main/java/eu/dnetlib/openaire/rest/UserInfo.java	(revision 62533)
@@ -0,0 +1,46 @@
+package eu.dnetlib.openaire.rest;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * Created by argirok on 23/6/2017.
+ */
+public class UserInfo {
+    String name;
+    String email;
+    List<String> edu_person_entitlements =  new ArrayList<String>();
+
+    @Override
+    public String toString() {
+        return "UserInfo{" +
+                "name='" + name + '\'' +
+                ", email='" + email + '\'' +
+                ", edu_person_entitlements=" + edu_person_entitlements +
+                '}';
+    }
+
+    public String getName() {
+        return name;
+    }
+
+    public void setName(String name) {
+        this.name = name;
+    }
+
+    public String getEmail() {
+        return email;
+    }
+
+    public void setEmail(String email) {
+        this.email = email;
+    }
+
+    public List<String> getEdu_person_entitlements() {
+        return edu_person_entitlements;
+    }
+
+    public void setEdu_person_entitlements(List<String> edu_person_entitlements) {
+        this.edu_person_entitlements = edu_person_entitlements;
+    }
+}
Index: modules/uoa-claims-api/tags/uoa-claims-api-2.1.0/src/main/resources/eu/dnetlib/openaire/rest/springContext-claims-authorization.properties
===================================================================
--- modules/uoa-claims-api/tags/uoa-claims-api-2.1.0/src/main/resources/eu/dnetlib/openaire/rest/springContext-claims-authorization.properties	(nonexistent)
+++ modules/uoa-claims-api/tags/uoa-claims-api-2.1.0/src/main/resources/eu/dnetlib/openaire/rest/springContext-claims-authorization.properties	(revision 62533)
@@ -0,0 +1,7 @@
+
+services.claims.authorization.userInfoUrl = http://mpagasas.di.uoa.gr:8080/dnet-openaire-users-1.0.0-SNAPSHOT/api/users/getUserInfo?accessToken=
+services.claims.authorization.originServer = .di.uoa.gr
+services.claims.authorization.registeredRoles = Super Administrator,Portal Administrator,Expert - Community,Expert - Funder,Curator - Claim,Curator - Project,Curator - Community,Curator - Institution,Author,Registered User,User Manager
+services.claims.authorization.claimCuratorRoles = Super Administrator,Curator - Claim,Portal Administrator
+services.claims.authorization.projectCuratorRoles = Curator - Project,Super Administrator,Curator - Claim,Portal Administrator
+services.claims.authorization.communityCuratorRoles = Curator - Community,Expert - Community,Portal Administrator,Registered User
Index: modules/uoa-claims-api/tags/uoa-claims-api-2.1.0/src/main/resources/eu/dnetlib/openaire/rest/springContext-claims-authorization.xml
===================================================================
--- modules/uoa-claims-api/tags/uoa-claims-api-2.1.0/src/main/resources/eu/dnetlib/openaire/rest/springContext-claims-authorization.xml	(nonexistent)
+++ modules/uoa-claims-api/tags/uoa-claims-api-2.1.0/src/main/resources/eu/dnetlib/openaire/rest/springContext-claims-authorization.xml	(revision 62533)
@@ -0,0 +1,37 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<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"
+       xmlns:cxf="http://cxf.apache.org/core"
+       xmlns:jaxws="http://cxf.apache.org/jaxws"
+       xmlns:p="http://http://www.springframework.org/schema/p"
+       xmlns:template="http://dnetlib.eu/springbeans/template"
+       xmlns:t="http://dnetlib.eu/springbeans/t"
+
+       xsi:schemaLocation="
+		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
+        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
+        http://cxf.apache.org/core http://cxf.apache.org/schemas/core.xsd
+        http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd
+	http://dnetlib.eu/springbeans/template http://dnetlib.eu/springbeans/template.xsd"
+       default-autowire="byName">
+    <!--Un comment in order to run the tests / Comment to deploy-->
+    <!--<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">-->
+    <!--<property name="locations" value="classpath:eu/dnetlib/openaire/rest/springContext-claims-authorization.properties"/>-->
+    <!--</bean>-->
+    <bean id="userHandler" class="eu.dnetlib.openaire.rest.inputHandler.UserHandler" >
+        <property name="userInfoUrl" value="${services.claims.authorization.userInfoUrl}"/>
+    </bean>
+
+    <bean id="authorization" class="eu.dnetlib.openaire.rest.Authorization" >
+        <property name="registeredRoles" value="#{'${services.claims.authorization.registeredRoles}'.split(',')}"/>
+        <property name="claimCuratorRoles"   value="#{'${services.claims.authorization.claimCuratorRoles}'.split(',')}"/>
+        <property name="projectCuratorRoles" value="#{'${services.claims.authorization.projectCuratorRoles}'.split(',')}"/>
+        <property name="communityCuratorRoles" value="#{'${services.claims.authorization.communityCuratorRoles}'.split(',')}"/>
+        <property name="userHandler" ref="userHandler"/>
+        <property name="originServer" value="${services.claims.authorization.originServer}"/>
+
+     </bean>
+
+
+</beans>
\ No newline at end of file
Index: modules/uoa-claims-api/tags/uoa-claims-api-2.1.0/src/main/resources/eu/dnetlib/openaire/utils/claims.sql
===================================================================
--- modules/uoa-claims-api/tags/uoa-claims-api-2.1.0/src/main/resources/eu/dnetlib/openaire/utils/claims.sql	(nonexistent)
+++ modules/uoa-claims-api/tags/uoa-claims-api-2.1.0/src/main/resources/eu/dnetlib/openaire/utils/claims.sql	(revision 62533)
@@ -0,0 +1,45 @@
+select
+        r.resultid                                          as dri_objidentifier,
+        r.title                                             as dc_title,
+        array_agg(DISTINCT lpad('0'||aut.rank,5,'0')||'§§§'||ltrim(replace(per.surname||', '||per.name,'UNKNOWN, ',''), ', ')) as dc_creator,
+      r.description                                       as dc_description,
+        r.publisher                                         as dc_publisher,
+        r.keywords                                          as dc_subject,
+        r.language                                          as dc_language,
+        array_agg(DISTINCT ws.file_url)                     as dc_identifier,
+        r.publication_date                                  as oaf_publicationdate,
+        r.embargo_end_date                                  as oaf_embargoenddate,
+        r.access_mode                                       as oaf_accessmode,
+        r.haskind                                           as oaf_haskind,
+        r.hastype                                           as "dr_CobjCategory",
+        r.storagedate                                           as oaf_storagedate,
+        createdfrom                                         as createdfrom,
+        array_agg(DISTINCT p.projectid)                     as oaf_projectid,
+        array_agg(DISTINCT cr.creator)                              as creators
+
+from
+
+       results r
+        left outer join results_projects rp on (r.resultid = rp.result)
+        left outer join projects p on (p.projectid = rp.project)
+        left outer join projects_projectsubjects ps on (ps.project = p.projectID)
+        left outer join fundingschemes fs on (p.fundedhow = fs.fundingschemeid)
+        left outer join programs s on (p.fundedby = s.programid)
+        left outer join specificprograms sp on (s.hasspecificprogram = sp.specificprogramid)
+        left outer join frameworkprograms fp on (sp.hasframeworkprogram = fp.frameworkprogramid)
+        left outer join authorships aut on (r.resultid = aut.result)
+        left outer join persons per on (per.personid = aut.author)
+        left outer join organizations o on (o.organizationid = aut.affiliation)
+        left outer join instances i on (r.resultid = i.resource)
+        left outer join webresources_instances wsi on (wsi.instanceid = i.instanceid)
+        left outer join webresources ws on (ws.webresourceid = wsi.webresourceid)
+
+        join creations cr on cr.creation = r.resultid
+
+where
+        r.pmhdeleted != true and r.pendingforclaim = false
+
+group by
+        r.resultid, r.title, r.description, r.publisher, r.keywords, r.language,
+        r.publication_date, r.embargo_end_date, r.access_mode, r.haskind, r.hastype,
+        r.storagedate, r.createdfrom
\ No newline at end of file
Index: modules/uoa-claims-api/tags/uoa-claims-api-2.1.0/src
===================================================================
--- modules/uoa-claims-api/tags/uoa-claims-api-2.1.0/src	(nonexistent)
+++ modules/uoa-claims-api/tags/uoa-claims-api-2.1.0/src	(revision 62533)

Property changes on: modules/uoa-claims-api/tags/uoa-claims-api-2.1.0/src
___________________________________________________________________
Added: svn:ignore
## -0,0 +1 ##
+
Index: modules/uoa-claims-api/tags/uoa-claims-api-2.1.0/deploy.info
===================================================================
--- modules/uoa-claims-api/tags/uoa-claims-api-2.1.0/deploy.info	(nonexistent)
+++ modules/uoa-claims-api/tags/uoa-claims-api-2.1.0/deploy.info	(revision 62533)
@@ -0,0 +1,10 @@
+{
+  "type_source": "SVN", 
+  "goal": "package -U -T 4C source:jar", 
+  "url": "http://svn-public.driver.research-infrastructures.eu/driver/dnet45/modules/uoa-claims-api/trunk", 
+  "deploy_repository": "dnet45-snapshots", 
+  "version": "4", 
+  "mail": "kiatrop@di.uoa.gr, argirok@di.uoa.gr, kgalouni@di.uoa.gr", 
+  "deploy_repository_url": "http://maven.research-infrastructures.eu/nexus/content/repositories/dnet45-snapshots", 
+  "name": "uoa-openaire-connector"
+}
Index: modules/uoa-claims-api/tags/uoa-claims-api-2.1.0
===================================================================
--- modules/uoa-claims-api/tags/uoa-claims-api-2.1.0	(nonexistent)
+++ modules/uoa-claims-api/tags/uoa-claims-api-2.1.0	(revision 62533)

Property changes on: modules/uoa-claims-api/tags/uoa-claims-api-2.1.0
___________________________________________________________________
Added: svn:ignore
## -0,0 +1,6 ##
+.classpath
+.project
+.settings
+.idea
+*.iml
+target
