Project

General

Profile

« Previous | Next » 

Revision 62533

[maven-release-plugin] copy for tag uoa-claims-api-2.1.0

View differences:

modules/uoa-claims-api/tags/uoa-claims-api-2.1.0/pom.xml
1
<?xml version="1.0"?>
2
<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">
3
    <parent>
4
        <groupId>eu.dnetlib</groupId>
5
        <artifactId>uoa-global-parent</artifactId>
6
        <version>1.0.1</version>
7
    </parent>
8
	<modelVersion>4.0.0</modelVersion>
9
	<groupId>eu.dnetlib</groupId>
10
	<artifactId>uoa-claims-api</artifactId>
11
	<version>2.1.0</version>
12
        <scm>
13
                <developerConnection>scm:svn:https://svn.driver.research-infrastructures.eu/driver/dnet45/modules/uoa-claims-api/tags/uoa-claims-api-2.1.0</developerConnection>
14
        </scm>
15
	<pluginRepositories>
16
		<pluginRepository>
17
			<id>dtrotts</id>
18
			<name>Repository for maven thrift plugin</name>
19
			<url>http://maven.davidtrott.com/repository</url>
20
			<layout>default</layout>
21
		</pluginRepository>
22
	</pluginRepositories>
23
	<build>
24
        <plugins>
25
            <plugin>
26
                <groupId>org.apache.maven.plugins</groupId>
27
                <artifactId>maven-compiler-plugin</artifactId>
28
                <configuration>
29
                    <source>1.7</source>
30
                    <target>1.7</target>
31
                </configuration>
32
            </plugin>
33
        </plugins>
34
    </build>
35
    <dependencies>
36
        <dependency>
37
            <groupId>junit</groupId>
38
            <artifactId>junit</artifactId>
39
            <version>[0.0.0,)</version>
40
            <scope>test</scope>
41
        </dependency>
42
        <dependency>
43
            <groupId>org.slf4j</groupId>
44
            <artifactId>slf4j-api</artifactId>
45
            <version>1.7.5</version>
46
        </dependency>
47
        <dependency>
48
            <groupId>commons-dbcp</groupId>
49
            <artifactId>commons-dbcp</artifactId>
50
            <version>[1.2, 1.3)</version>
51
        </dependency>
52
        <dependency>
53
            <groupId>eu.dnetlib</groupId>
54
            <artifactId>uoa-claims</artifactId>
55
            <version>2.1.0</version>
56
        </dependency>
57
        <dependency>
58
            <groupId>javax.servlet</groupId>
59
            <artifactId>servlet-api</artifactId>
60
            <version>2.5</version>
61
            <scope>provided</scope>
62
        </dependency>
63
        <dependency>
64
            <groupId>org.postgresql</groupId>
65
            <artifactId>jdbc4driver</artifactId>
66
            <version>9.1</version>
67
        </dependency>
68
        <dependency>
69
            <groupId>org.springframework</groupId>
70
            <artifactId>spring-tx</artifactId>
71
            <version>4.2.5.RELEASE</version>
72
        </dependency>
73
        <dependency>
74
            <groupId>org.springframework</groupId>
75
            <artifactId>spring-jdbc</artifactId>
76
            <version>4.2.5.RELEASE</version>
77
        </dependency>
78
        <dependency>
79
            <groupId>oro</groupId>
80
            <artifactId>oro</artifactId>
81
            <version>2.0.8</version>
82
        </dependency>
83

  
84

  
85
        <!-- Jersey -->
86
        <dependency>
87
            <groupId>asm</groupId>
88
            <artifactId>asm</artifactId>
89
            <version>3.3.1</version>
90
        </dependency>
91
        <dependency>
92
            <groupId>com.sun.jersey</groupId>
93
            <artifactId>jersey-bundle</artifactId>
94
            <version>1.19</version>
95
        </dependency>
96
        <dependency>
97
            <groupId>org.json</groupId>
98
            <artifactId>json</artifactId>
99
            <version>20140107</version>
100
        </dependency>
101
        <dependency>
102
            <groupId>com.sun.jersey</groupId>
103
            <artifactId>jersey-server</artifactId>
104
            <version>1.19</version>
105
        </dependency>
106
        <dependency>
107
            <groupId>com.sun.jersey</groupId>
108
            <artifactId>jersey-core</artifactId>
109
            <version>1.19</version>
110
        </dependency>
111
        <dependency>
112
            <groupId>commons-validator</groupId>
113
            <artifactId>commons-validator</artifactId>
114
            <version>1.3.1</version>
115
        </dependency>
116
        <dependency>
117
            <groupId>com.sun.jersey.contribs</groupId>
118
            <artifactId>jersey-spring</artifactId>
119
            <version>1.8</version>
120
            <exclusions>
121
                <exclusion>
122
                    <groupId>org.springframework</groupId>
123
                    <artifactId>spring</artifactId>
124
                </exclusion>
125
                <exclusion>
126
                    <groupId>org.springframework</groupId>
127
                    <artifactId>spring-core</artifactId>
128
                </exclusion>
129
                <exclusion>
130
                    <groupId>org.springframework</groupId>
131
                    <artifactId>spring-web</artifactId>
132
                </exclusion>
133
                <exclusion>
134
                    <groupId>org.springframework</groupId>
135
                    <artifactId>spring-beans</artifactId>
136
                </exclusion>
137
                <exclusion>
138
                    <groupId>org.springframework</groupId>
139
                    <artifactId>spring-context</artifactId>
140
                </exclusion>
141
                <exclusion>
142
                    <groupId>org.springframework</groupId>
143
                    <artifactId>spring-utils</artifactId>
144
                </exclusion>
145
                <exclusion>
146
                    <groupId>org.springframework</groupId>
147
                    <artifactId>spring-aop</artifactId>
148
                </exclusion>
149
            </exclusions>
150
        </dependency>
151
        <dependency>
152
            <groupId>io.jsonwebtoken</groupId>
153
            <artifactId>jjwt</artifactId>
154
            <version>0.7.0</version>
155
        </dependency>
156
        <dependency>
157
            <groupId>eu.dnetlib</groupId>
158
            <artifactId>uoa-claims</artifactId>
159
            <version>2.1.0</version>
160
        </dependency>
161
    </dependencies>
162
</project>
modules/uoa-claims-api/tags/uoa-claims-api-2.1.0/src/main/java/eu/dnetlib/openaire/rest/Authorization.java
1
package eu.dnetlib.openaire.rest;
2

  
3
import eu.dnetlib.openaire.rest.inputHandler.UserHandler;
4
import org.apache.logging.log4j.LogManager;
5
import org.apache.logging.log4j.Logger;
6

  
7
import java.util.ArrayList;
8
import java.util.Arrays;
9
import java.util.List;
10

  
11
/**
12
 * Created by sofia on 20/4/2017.
13
 */
14
public class Authorization {
15

  
16
    private static Logger logger = LogManager.getLogger(Authorization.class);
17
    List<String> registeredRoles = new ArrayList<String>(Arrays.asList("Super Administrator", "Portal Administrator", "Expert - Community",
18
            "Expert - Funder", "Curator - Claim", "Curator - Project", "Curator - Community", "Curator - Institution", "Cuthor", "Registered", "User Manager"));
19
    List<String> claimCuratorRoles = new ArrayList<String>(Arrays.asList("Super Administrator", "Curator - Claim", "Portal Administrator"));
20
    List<String> projectCuratorRoles = new ArrayList<String>(Arrays.asList("Curator - Project"));
21
    List<String> communityCuratorRoles = new ArrayList<String>(Arrays.asList("Curator - Community"));
22
    List<String> portalAdminRoles = new ArrayList<String>(Arrays.asList("Portal Administrator"));
23
    UserHandler userHandler = null;
24
    String originServer = null;
25

  
26
    //    public static boolean isRegistered(String token) {
27
//
28
//        Claims claims = Jwts.parser()
29
//                .setSigningKey(DatatypeConverter.parseBase64Binary("my-very-secret"))
30
//                .parseClaimsJws(token).getBody();
31
//
32
//        if (claims.get("role").equals("1") || claims.get("role").equals("2")) {
33
//            logger.debug("It's  registered with role " + claims.get("role"));
34
//            return true;
35
//        } else {
36
//            logger.debug("It's *not*  registered with role " + claims.get("role"));
37
//
38
//            return false;
39
//        }
40
//    }
41
//
42
//    public static boolean isClaimCurator(String token) {
43
//        Claims claims = Jwts.parser()
44
//                .setSigningKey(DatatypeConverter.parseBase64Binary("my-very-secret"))
45
//                .parseClaimsJws(token).getBody();
46
//        if (claims.get("role").equals("2")) {
47
//            logger.debug("It's  admin with role " + claims.get("role"));
48
//            return true;
49
//        } else {
50
//            logger.debug("It's *not*  admin with role " + claims.get("role"));
51
//            return false;
52
//        }
53
//    }
54
    public boolean isRegistered(String token) {
55
        UserInfo userInfo = userHandler.getUserInfo(token);
56
        return isRegistered(userInfo);
57

  
58
    }
59
    public void logStatus(String token, String cookie) {
60

  
61
        if(token == null || token.isEmpty()) {
62
            logger.debug("No proper value: header \"X-XSRF-TOKEN\" has value " + token);
63
        }else if(cookie == null || cookie.isEmpty() || !cookie.equals(token)) {
64
            logger.debug("No proper value: cookie  \"AccessToken\" has value  " + cookie);
65
        }else if( !cookie.equals(token)) {
66
            logger.debug("No proper values:for cookie " + cookie + " and token "+token);
67
        }
68
    }
69

  
70
    public boolean isRegistered(UserInfo userInfo) {
71
        if (userInfo != null && userInfo.getEdu_person_entitlements() != null) {
72

  
73
            return hasRole(userInfo.getEdu_person_entitlements(), registeredRoles);
74
        } else {
75
            return false;
76
        }
77

  
78
    }
79

  
80
    public boolean isClaimCurator(String token) {
81
        UserInfo userInfo = userHandler.getUserInfo(token);
82
        return isClaimCurator(userInfo);
83

  
84
    }
85

  
86
    public boolean isClaimCurator(UserInfo userInfo) {
87
        if (userInfo != null && userInfo.getEdu_person_entitlements() != null) {
88

  
89
            return hasRole(userInfo.getEdu_person_entitlements(), claimCuratorRoles);
90
        } else {
91
            logger.debug(" User has no Valid UserInfo");
92
            return false;
93
        }
94

  
95
    }
96

  
97
    public boolean isCommunityCurator(String token) {
98
        UserInfo userInfo = userHandler.getUserInfo(token);
99
        return isCommunityCurator(userInfo);
100

  
101
    }
102

  
103
    public boolean isCommunityCurator(UserInfo userInfo) {
104
        if (userInfo != null && userInfo.getEdu_person_entitlements() != null) {
105

  
106
            return hasRole(userInfo.getEdu_person_entitlements(), communityCuratorRoles);
107
        } else {
108
            logger.debug(" User has no Valid UserInfo");
109
            return false;
110
        }
111

  
112
    }
113
    public boolean isProjectCurator(String token) {
114
        UserInfo userInfo = userHandler.getUserInfo(token);
115
        return isProjectCurator(userInfo);
116

  
117
    }
118

  
119
    public boolean isProjectCurator(UserInfo userInfo) {
120
        if (userInfo != null && userInfo.getEdu_person_entitlements() != null) {
121

  
122
            return hasRole(userInfo.getEdu_person_entitlements(), projectCuratorRoles);
123
        } else {
124
            return false;
125
        }
126

  
127
    }
128

  
129
    public boolean isPortalAdministrator(String token) {
130
        UserInfo userInfo = userHandler.getUserInfo(token);
131
        return isPortalAdministrator(userInfo);
132

  
133
    }
134

  
135
    public boolean isPortalAdministrator(UserInfo userInfo) {
136
        if (userInfo != null && userInfo.getEdu_person_entitlements() != null) {
137

  
138
            return hasRole(userInfo.getEdu_person_entitlements(), portalAdminRoles);
139
        } else {
140
            logger.debug(" User has no Valid UserInfo");
141
            return false;
142
        }
143

  
144
    }
145

  
146
    public boolean hasRole(List<String> givenRoles, List<String> authorizedRoles) {
147

  
148
        logger.debug("It's  registered with role " + givenRoles);
149
        for (String gRole : givenRoles) {
150
            if (authorizedRoles.indexOf(gRole) != -1) {
151
                return true;
152
            }
153
        }
154
        logger.debug("Not Authorized. Authorized roles are" + authorizedRoles);
155
        return false;
156

  
157
    }
158

  
159
    public boolean hasValidOrigin(String origin) {
160
        logger.debug("Origin is "+origin +" originServer: "+originServer);
161
        if (origin != null && origin.indexOf(originServer)!=-1) {
162
            return true;
163
        }
164
        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. ");
165
        return false;
166
    }
167

  
168
    public boolean hasBasicAuthorization(String token, String origin, String  cookie){
169
        if(token == null || token.isEmpty() || cookie == null || cookie.isEmpty() || !cookie.equals(token)|| !hasValidOrigin(origin)){
170
            return false;
171
        }
172
        return true;
173
    }
174

  
175
    public List<String> getRegisteredRoles() {
176
        return registeredRoles;
177
    }
178

  
179
    public void setRegisteredRoles(List<String> registeredRoles) {
180
        this.registeredRoles = registeredRoles;
181
    }
182

  
183
    public List<String> getClaimCuratorRoles() {
184
        return claimCuratorRoles;
185
    }
186

  
187
    public void setClaimCuratorRoles(List<String> claimCuratorRoles) {
188
        this.claimCuratorRoles = claimCuratorRoles;
189
    }
190

  
191
    public List<String> getCommunityCuratorRoles() {
192
        return communityCuratorRoles;
193
    }
194

  
195
    public void setCommunityCuratorRoles(List<String> communityCuratorRoles) {
196
        this.communityCuratorRoles = communityCuratorRoles;
197
    }
198

  
199
    public List<String> getProjectCuratorRoles() {
200
        return projectCuratorRoles;
201
    }
202

  
203
    public void setProjectCuratorRoles(List<String> projectCuratorRoles) {
204
        this.projectCuratorRoles = projectCuratorRoles;
205
    }
206

  
207
    public UserHandler getUserHandler() {
208
        return userHandler;
209
    }
210

  
211
    public void setUserHandler(UserHandler userHandler) {
212
        this.userHandler = userHandler;
213
    }
214

  
215
    public String getOriginServer() {
216
        return originServer;
217
    }
218

  
219
    public void setOriginServer(String originServer) {
220
        this.originServer = originServer;
221
    }
222
}
modules/uoa-claims-api/tags/uoa-claims-api-2.1.0/src/main/java/eu/dnetlib/openaire/rest/ClaimsService.java
1
package eu.dnetlib.openaire.rest;
2

  
3
import com.google.gson.*;
4
import eu.dnetlib.data.claims.entity.Claim;
5
import eu.dnetlib.data.claims.entity.Notification;
6
import eu.dnetlib.data.claims.handler.*;
7
import eu.dnetlib.data.claims.sql.SQLStoreException;
8
import eu.dnetlib.data.claims.utils.ClaimValidationException;
9
import eu.dnetlib.data.emailSender.EmailSender;
10
import org.apache.commons.validator.EmailValidator;
11
import org.apache.logging.log4j.LogManager;
12
import org.apache.logging.log4j.Logger;
13
import org.json.XML;
14
import org.springframework.beans.factory.annotation.Autowired;
15
import org.springframework.stereotype.Component;
16
import org.springframework.web.bind.annotation.CrossOrigin;
17

  
18
import javax.servlet.http.HttpServletRequest;
19
import javax.ws.rs.*;
20
import javax.ws.rs.core.Context;
21
import javax.ws.rs.core.MediaType;
22
import javax.ws.rs.core.Response;
23
import java.util.ArrayList;
24
import java.util.List;
25
import java.util.Map;
26

  
27

  
28
/**
29
 * Created by kiatrop on 15/4/2016.
30
 */
31
@Component
32
@CrossOrigin(origins = "*")
33
@Path("/claimsService")
34
public class ClaimsService {
35

  
36
    private static final Logger logger = LogManager.getLogger(ClaimsService.class);
37

  
38
    @Autowired
39
    private FetchClaimHandler fetchClaimHandler = null;
40

  
41
    @Autowired
42
    private FetchProjectHandler fetchProjectHandler= null;
43

  
44
    @Autowired
45
    private FetchNotificationHandler fetchNotificationHandler = null;
46

  
47
    @Autowired
48
    private NotificationHandler notificationHandler = null;
49

  
50

  
51
    @Autowired
52
    private ClaimHandler claimHandler = null;
53

  
54
    @Autowired
55
    private DirectIndexHandler directIndexHandler = null;
56

  
57
    @Autowired
58
    public Authorization authorization = null;
59

  
60
    @Autowired
61
    private String defaultFrequencyInHours;
62

  
63
    @Autowired
64
    private EmailSender emailSender;
65

  
66
    @GET
67
    @Path("projects/{projectId}/claims")
68
    @Produces(MediaType.APPLICATION_JSON)
69
    public Response getProjectClaims(@PathParam("projectId") String projectId,
70
                                     @DefaultValue("0") @QueryParam("offset") int offset,
71
                                     @DefaultValue("20") @QueryParam("limit") int limit,
72
                                     @DefaultValue("") @QueryParam("keyword") String keyword,
73
                                     @DefaultValue("") @QueryParam("sortby") String orderby,
74
                                     @DefaultValue("true") @QueryParam("descending") boolean descending,
75
                                     @DefaultValue("") @QueryParam("types") List<String> types,
76
                                     @HeaderParam("X-XSRF-TOKEN") String token,
77
                                     @CookieParam("AccessToken") String  cookie,
78
                                     @Context HttpServletRequest request) {
79

  
80
        if(token == null || token.isEmpty() || cookie == null || cookie.isEmpty() || !cookie.equals(token)){
81
            authorization.logStatus(token,cookie);
82
            return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. Maybe you are not registered."))
83
                    .type(MediaType.APPLICATION_JSON)
84
                    .build();
85
        }
86

  
87
        if(authorization.isClaimCurator(token)) {
88

  
89
            int total = -1;
90

  
91
            if (projectId == null || projectId.isEmpty()) {
92
                return Response.status(Response.Status.BAD_REQUEST).entity(compose400Message("Project id cannot be empty."))
93
                        .type(MediaType.APPLICATION_JSON).build();
94
            }
95

  
96
            List<Claim> claims = null;
97
            try {
98
                claims = fetchClaimHandler.fetchClaimsByProject(projectId, limit, offset, keyword, orderby, descending, types,false);
99
                total = fetchClaimHandler.countClaimsByProject(projectId, keyword, types);
100

  
101
            } catch (SQLStoreException|Exception e) {  //TODO check this with exception
102
                logger.error("Could not fetch claims for project with id " + projectId, e);
103
                return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500Message("Fail to fetch claims" +
104
                        " for projects with id " + projectId + ".", e)).type(MediaType.APPLICATION_JSON).build();
105

  
106
            }
107

  
108
            return Response.status(200).entity(composeDataResponse(request, claims, total, offset, limit)).build();
109
        }
110

  
111
        return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access"))
112
                .type(MediaType.APPLICATION_JSON)
113
                .build();
114
    }
115

  
116
    @GET
117
    @Path("projects/{projectId}/all_claims")
118
    @Produces(MediaType.APPLICATION_JSON)
119
    public Response getAllProjectClaims(@PathParam("projectId") String projectId,
120
                                        @DefaultValue("-1") @QueryParam("offset") int offset,
121
                                        @DefaultValue("-1") @QueryParam("limit") int limit,
122
                                        @DefaultValue("") @QueryParam("keyword") String keyword,
123
                                        @DefaultValue("") @QueryParam("sortby") String orderby,
124
                                        @DefaultValue("true") @QueryParam("descending") boolean descending,
125
                                        @DefaultValue("") @QueryParam("types") List<String> types,
126
                                        @HeaderParam("X-XSRF-TOKEN") String token,
127
                                        @CookieParam("AccessToken") String  cookie,
128
                                        @Context HttpServletRequest request) {
129

  
130
        if(token == null || token.isEmpty() || cookie == null || cookie.isEmpty() || !cookie.equals(token)){
131
            authorization.logStatus(token,cookie);
132
            return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. Maybe you are not registered."))
133
                    .type(MediaType.APPLICATION_JSON)
134
                    .build();
135
        }
136

  
137
        UserInfo userInfo = authorization.getUserHandler().getUserInfo(token);
138
//        if(authorization.isProjectCurator(userInfo)) {
139
        String userMail = userInfo.getEmail();
140

  
141
        int total = -1;
142

  
143
        if (projectId == null || projectId.isEmpty()) {
144
            return Response.status(Response.Status.BAD_REQUEST).entity(compose400Message("Project id cannot be empty."))
145
                    .type(MediaType.APPLICATION_JSON).build();
146
        }
147

  
148
        List<Claim> claims = null;
149
        try {
150
            boolean forbidden = true;
151
            if(authorization.isProjectCurator(userInfo)) {
152
                forbidden = false;
153
            } else {
154
                List<String> contact_emails = fetchProjectHandler.fetchContactEmailsByProjectId(projectId);
155
                logger.debug(contact_emails);
156
                if(contact_emails != null && contact_emails.contains(userMail)) {
157
                    forbidden = false;
158
                }
159
            }
160

  
161
            if(forbidden){
162
                return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access"))
163
                        .type(MediaType.APPLICATION_JSON)
164
                        .build();
165
            }else{
166
                if(offset == -1 && limit == -1) {
167
                    // when offset and limit are -1 fetch claims with null values, to ignore paging and limit clause
168
                    claims = fetchClaimHandler.fetchClaimsByProject(projectId, null, null, keyword, orderby, descending, types, true);
169
                } else {
170
                    claims = fetchClaimHandler.fetchClaimsByProject(projectId, limit, offset, keyword, orderby, descending, types, true);
171
                }
172
                total = fetchClaimHandler.countClaimsByProject(projectId, keyword, types);
173

  
174
                return Response.status(200).entity(composeDataResponse(request, claims, total, offset, limit)).build();
175
            }
176

  
177
        } catch (SQLStoreException|Exception e) {
178
            logger.error("Could not fetch claims for project with id " + projectId, e);
179
            return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500Message("Fail to fetch claims" +
180
                    " for projects with id " + projectId + ".", e)).type(MediaType.APPLICATION_JSON).build();
181
        }
182
    }
183
/*
184
    @GET
185
    @Path("project/claims")
186
    @Produces(MediaType.APPLICATION_JSON)
187
    public Response getProjectClaimsByToken(@QueryParam("projectToken") String projectToken,
188
                                     @DefaultValue("-1") @QueryParam("offset") int offset,
189
                                     @DefaultValue("-1") @QueryParam("limit") int limit,
190
                                     @DefaultValue("") @QueryParam("keyword") String keyword,
191
                                     @DefaultValue("") @QueryParam("sortby") String orderby,
192
                                     @DefaultValue("true") @QueryParam("descending") boolean descending,
193
                                     @DefaultValue("") @QueryParam("types") List<String> types,
194
                                     @HeaderParam("X-XSRF-TOKEN") String token,
195
                                     @CookieParam("AccessToken") String  cookie,
196
                                     @Context HttpServletRequest request) {
197

  
198

  
199
        if(token == null || token.isEmpty() || cookie == null || cookie.isEmpty() || !cookie.equals(token)){
200
            authorization.logStatus(token,cookie);
201
            return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. Maybe you are not registered."))
202
                    .type(MediaType.APPLICATION_JSON)
203
                    .build();
204
        }
205

  
206
        UserInfo userInfo = authorization.getUserHandler().getUserInfo(token);
207
//        if(authorization.isProjectCurator(userInfo)) {
208
            String userMail = userInfo.getEmail();
209

  
210
            int total = -1;
211

  
212
            if (projectToken == null || projectToken.isEmpty()) {
213
                return Response.status(Response.Status.BAD_REQUEST).entity(compose400Message("Project token cannot be empty."))
214
                        .type(MediaType.APPLICATION_JSON).build();
215
            }
216

  
217
            List<Claim> claims = null;
218
            try {
219
                String projectId = null;
220
                if(authorization.isProjectCurator(userInfo)) {
221
                    projectId = fetchProjectHandler.fetchProjectIdByToken(projectToken);
222
                } else {
223
                    projectId = fetchProjectHandler.fetchProjectIdByTokenAndEmail(projectToken, userMail);
224
                }
225
                //String projectId = fetchProjectHandler.fetchProjectIdByToken(projectToken,userMail);
226
                if(projectId == null){
227
                    return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access"))
228
                            .type(MediaType.APPLICATION_JSON)
229
                            .build();
230
                }else{
231
                    if(offset == -1 && limit == -1) {
232
                        // when offset and limit are -1 fetch claims with null values, to ignore paging and limit clause
233
                        claims = fetchClaimHandler.fetchClaimsByProject(projectId, null, null, keyword, orderby, descending, types, true);
234
                    } else {
235
                        claims = fetchClaimHandler.fetchClaimsByProject(projectId, limit, offset, keyword, orderby, descending, types, true);
236
                    }
237
                    total = fetchClaimHandler.countClaimsByProject(projectId, keyword, types);
238

  
239
                    return Response.status(200).entity(composeDataResponse(request, claims, total, offset, limit)).build();
240
                }
241

  
242
            } catch (SQLStoreException|Exception e) {
243
                logger.error("Could not fetch claims for project token " + projectToken, e);
244
                return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500Message("Fail to fetch claims" +
245
                        " for projects with token " + projectToken + ".", e)).type(MediaType.APPLICATION_JSON).build();
246
            }
247
//        }
248

  
249
//        return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access"))
250
//                .type(MediaType.APPLICATION_JSON)
251
//                .build();
252
    }
253
*/
254

  
255
    @GET
256
    @Path("/contexts/{contextId}/claims")
257
    @Produces(MediaType.APPLICATION_JSON)
258
    public Response getContextClaims(@PathParam("contextId") String contextId,
259
                                     @DefaultValue("0") @QueryParam("offset") int offset,
260
                                     @DefaultValue("20") @QueryParam("limit") int limit,
261
                                     @DefaultValue("") @QueryParam("keyword") String keyword,
262
                                     @DefaultValue("") @QueryParam("sortby") String orderby,
263
                                     @DefaultValue("true") @QueryParam("descending") boolean descending,
264
                                     @DefaultValue("") @QueryParam("types") List<String> types,
265
                                     @HeaderParam("X-XSRF-TOKEN") String token,
266
                                     @CookieParam("AccessToken") String  cookie,
267
                                     @Context HttpServletRequest request) {
268
//        @RequestParam(value="includeStates[]", defaultValue="1,2,3") String[] includeStates
269

  
270
        if(token == null || token.isEmpty() || cookie == null || cookie.isEmpty() || !cookie.equals(token)){
271
            authorization.logStatus(token,cookie);
272
            return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. Maybe you are not registered."))
273
                    .type(MediaType.APPLICATION_JSON)
274
                    .build();
275
        }
276
//        logger.debug("Calling API for context with token " + token);
277
        UserInfo userInfo = authorization.getUserHandler().getUserInfo(token);
278
        if(authorization.isCommunityCurator(userInfo) || authorization.isClaimCurator(token) || this.emailSender.getManagerUtils().isCommunityManager(contextId, userInfo.email )) {
279

  
280
            int total = -1;
281
            if (contextId == null || contextId.isEmpty()) {
282
                return Response.status(Response.Status.BAD_REQUEST).entity(compose400Message("Context id cannot be empty."))
283
                        .type(MediaType.APPLICATION_JSON).build();
284
            }
285
            logger.debug("Types are " + types);
286
            List<Claim> claims = null;
287

  
288
            try {
289
                claims = fetchClaimHandler.fetchClaimsByContext(contextId, limit, offset, keyword, orderby, descending, types,false);
290
                total = fetchClaimHandler.countClaimsByContext(contextId, keyword, types);
291

  
292
            } catch (SQLStoreException|Exception e) {
293
                logger.error("Could not fetch claims for context with id " + contextId, e);
294
                return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500Message("Fail to fetch claims" +
295
                        " for context with id " + contextId + ".", e)).type(MediaType.APPLICATION_JSON).build();
296
            }
297

  
298
            return Response.status(200).entity(composeDataResponse(request, claims, total, offset, limit)).build();
299
        }
300

  
301
        return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access"))
302
                .type(MediaType.APPLICATION_JSON)
303
                .build();
304
    }
305

  
306

  
307
    @GET
308
    @Path("/results/{resultId}/claims")
309
    @Produces(MediaType.APPLICATION_JSON)
310
    public Response getResultClaims(@PathParam("resultId") String resultId,
311
                                    @DefaultValue("0") @QueryParam("offset") int offset,
312
                                    @DefaultValue("20") @QueryParam("limit") int limit,
313
                                    @DefaultValue("") @QueryParam("keyword") String keyword,
314
                                    @DefaultValue("") @QueryParam("sortby") String orderby,
315
                                    @DefaultValue("true") @QueryParam("descending") boolean descending,
316
                                    @DefaultValue("") @QueryParam("types") List<String> types,
317
                                    @HeaderParam("X-XSRF-TOKEN") String token,
318
                                    @CookieParam("AccessToken") String  cookie,
319
                                    @Context HttpServletRequest request) {
320

  
321

  
322
        if(token == null || token.isEmpty() || cookie == null || cookie.isEmpty() || !cookie.equals(token)){
323
            authorization.logStatus(token,cookie);
324
            return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. Maybe you are not registered."))
325
                    .type(MediaType.APPLICATION_JSON)
326
                    .build();
327
        }
328

  
329
        if(authorization.isClaimCurator(token)) {
330

  
331
            int total = -1;
332
            if (resultId == null || resultId.isEmpty()) {
333
                return Response.status(Response.Status.BAD_REQUEST).entity(compose400Message("Context id cannot be empty."))
334
                        .type(MediaType.APPLICATION_JSON).build();
335
            }
336

  
337
            List<Claim> claims = null;
338
            try {
339
                claims = fetchClaimHandler.fetchClaimsByResult(resultId, limit, offset, keyword, orderby, descending, types,false);
340
                total = fetchClaimHandler.countClaimsByResult(resultId, keyword, types);
341

  
342
            } catch (SQLStoreException|Exception e) {
343
                logger.error("Could not fetch claims for result with id " + resultId, e);
344
                return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500Message("Fail to fetch claims" +
345
                        " for result with id " + resultId + ".", e)).type(MediaType.APPLICATION_JSON).build();
346
            }
347

  
348
            return Response.status(200).entity(composeDataResponse(request, claims, total, offset, limit)).build();
349
        }
350

  
351
        return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access"))
352
                .type(MediaType.APPLICATION_JSON)
353
                .build();
354
    }
355

  
356

  
357
    @GET
358
    @Path("/users/claims")
359
    @Produces(MediaType.APPLICATION_JSON)
360
    public Response getUserClaims(@DefaultValue("0") @QueryParam("offset") int offset,
361
                                  @DefaultValue("20") @QueryParam("limit") int limit,
362
                                  @DefaultValue("") @QueryParam("keyword") String keyword,
363
                                  @DefaultValue("") @QueryParam("sortby") String orderby,
364
                                  @DefaultValue("true") @QueryParam("descending") boolean descending,
365
                                  @DefaultValue("") @QueryParam("types") List<String> types,
366
                                  @HeaderParam("X-XSRF-TOKEN") String token,
367
                                  @CookieParam("AccessToken") String  cookie,
368
                                  @Context HttpServletRequest request) {
369

  
370

  
371
        if(token == null || token.isEmpty() || cookie == null || cookie.isEmpty() || !cookie.equals(token)){
372
            return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. Maybe you are not registered."))
373
                    .type(MediaType.APPLICATION_JSON)
374
                    .build();
375
        }
376

  
377
        UserInfo userInfo = authorization.getUserHandler().getUserInfo(token);
378
        if(authorization.isRegistered(userInfo)) {
379
            String userMail = userInfo.getEmail();
380
            logger.debug("User is registerd "  );
381
            int total = -1;
382
            EmailValidator emailValidator = EmailValidator.getInstance();
383

  
384
            if (userMail == null || userMail.isEmpty()) {
385
                return Response.status(Response.Status.BAD_REQUEST).entity(compose400Message("User e-mail cannot be empty."))
386
                        .type(MediaType.APPLICATION_JSON).build();
387
            }
388

  
389
            if (!emailValidator.isValid(userMail)) {
390
                return Response.status(Response.Status.BAD_REQUEST).entity(compose400Message("User e-mail is not valid."))
391
                        .type(MediaType.APPLICATION_JSON).build();
392
            }
393

  
394
            List<Claim> claims = null;
395
            try {
396
                logger.debug("About to fetch claims"  );
397
                claims = fetchClaimHandler.fetchClaimsByUser(userMail, limit, offset, keyword, orderby, descending, types,false);
398
                total = fetchClaimHandler.countClaimsByUser(userMail, keyword, types);
399

  
400
            } catch (SQLStoreException|Exception e) {
401
                logger.error("Could not fetch claims for user with mail " + userMail, e);
402
                return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500Message("Fail to fetch claims" +
403
                        " for user with e-mail " + userMail + ".", e)).type(MediaType.APPLICATION_JSON).build();
404
            }
405

  
406
            return Response.status(200).entity(composeDataResponse(request, claims, total, offset, limit)).build();
407
        }
408
        logger.debug("User is *NOT* registerd "  );
409
        return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. You are not registered."))
410
                .type(MediaType.APPLICATION_JSON)
411
                .build();
412
    }
413

  
414
    @GET
415
    @Path("/claims/{claimId}")
416
    @Produces(MediaType.APPLICATION_JSON)
417
    public Response getClaimsById(@PathParam("claimId") String claimId,
418
                                  @DefaultValue("0") @QueryParam("offset") int offset,
419
                                  @DefaultValue("20") @QueryParam("limit") int limit,
420
                                  @HeaderParam("X-XSRF-TOKEN") String token,
421
                                  @CookieParam("AccessToken") String  cookie,
422
                                  @Context HttpServletRequest request) {
423

  
424

  
425
        if(token == null || token.isEmpty() || cookie == null || cookie.isEmpty() || !cookie.equals(token)){
426
            return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. Maybe you are not registered."))
427
                    .type(MediaType.APPLICATION_JSON)
428
                    .build();
429
        }
430

  
431
        if(authorization.isRegistered(token)) {
432

  
433
            List<Claim> claims = null;
434

  
435
            int total = -1;
436
            if (claimId == null || claimId.isEmpty()) {
437
                try {
438
                    claims = fetchClaimHandler.fetchAllClaims(limit, offset,false);
439
                    total = fetchClaimHandler.countAllClaims("", new ArrayList<String>());
440

  
441
                    return Response.status(200).entity(composeDataResponse(request, claims, total, offset, limit)).type(MediaType.APPLICATION_JSON).build();
442

  
443
                } catch (SQLStoreException|Exception e) {
444
                    logger.error("Could not fetch claims.", e);
445
                    return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500Message("Fail to fetch claims.", e))
446
                            .type(MediaType.APPLICATION_JSON).build();
447
                }
448
            }
449

  
450
            try {
451
                Claim claim = fetchClaimHandler.fetchClaimById(claimId,false);
452
                if (claim == null) {
453
                    return Response.status(Response.Status.NOT_FOUND).entity(compose404Message("Cannot find claim with id " + claimId + "."))
454
                            .type(MediaType.APPLICATION_JSON).build();
455
                }
456

  
457
                return Response.status(200).entity(composeDataResponse(claim)).build();
458

  
459
            } catch (SQLStoreException|Exception e) {
460
                return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500Message("Fail to fetch claim " +
461
                        "with id " + claimId + " id.", e)).type(MediaType.APPLICATION_JSON).build();
462
            }
463
        }
464
        return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. You are not registered."))
465
                .type(MediaType.APPLICATION_JSON)
466
                .build();
467
    }
468

  
469
    @GET
470
    @Path("/claims")
471
    @Produces(MediaType.APPLICATION_JSON)
472
    public Response getAllClaims(@DefaultValue("0") @QueryParam("offset") int offset,
473
                                 @DefaultValue("20") @QueryParam("limit") int limit,
474
                                 @DefaultValue("") @QueryParam("keyword") String keyword,
475
                                 @DefaultValue("date") @QueryParam("sortby") String orderby,
476
                                 @DefaultValue("true") @QueryParam("descending") boolean descending,
477
                                 @DefaultValue("") @QueryParam("types") List<String> types,
478
                                 @HeaderParam("X-XSRF-TOKEN") String token,
479
                                 @HeaderParam("Origin") String origin,
480
                                 @CookieParam("AccessToken") String  cookie,
481
                                 @Context HttpServletRequest request) {
482

  
483

  
484
        logger.debug("Header  \"Origin\" has value  " + origin);
485

  
486

  
487

  
488
        if(token == null || token.isEmpty() || cookie == null || cookie.isEmpty() || !cookie.equals(token)){
489
            logger.debug("User is not  authorized - Eroor 403");
490

  
491
            return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. Maybe you are not registered."))
492
                    .type(MediaType.APPLICATION_JSON)
493
                    .build();
494
        }
495

  
496
        if(authorization.isClaimCurator(token)) {
497
            logger.debug("User is authorized ! !");
498
            List<Claim> claims = null;
499

  
500
            int total = -1;
501
            try {
502
                claims = fetchClaimHandler.fetchAllClaims(limit, offset, keyword, orderby, descending, types,false);
503
                total = fetchClaimHandler.countAllClaims(keyword, types);
504

  
505
                return Response.status(200).entity(composeDataResponse(request, claims, total, offset, limit)).build();
506

  
507
            } catch (SQLStoreException|Exception e) {
508
                logger.error("Could not fetch claims.", e);
509
                return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500Message("Fail to fetch claims.", e))
510
                        .type(MediaType.APPLICATION_JSON).build();
511
            }
512
        }
513

  
514
        return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access"))
515
                .type(MediaType.APPLICATION_JSON)
516
                .build();
517
    }
518

  
519
    @DELETE
520
    @Path("/claims/bulk")
521
    @Produces(MediaType.APPLICATION_JSON)
522
    public Response deleteBulkClaims(@QueryParam("claimId") List<String> claimIds,
523
                                     @HeaderParam("X-XSRF-TOKEN") String token,
524
                                     @HeaderParam("Origin") String origin,
525
                                     @CookieParam("AccessToken") String  cookie){
526

  
527

  
528

  
529
        if(!authorization.hasBasicAuthorization(token, origin, cookie)){
530
            return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. Maybe you are not registered."))
531
                    .type(MediaType.APPLICATION_JSON)
532
                    .build();
533
        }
534

  
535

  
536
        ArrayList<String> deletedIds= new ArrayList<String>();
537
        ArrayList<String> notFoundIds= new ArrayList<String>();
538

  
539
        if (claimIds == null || claimIds.size() == 0) {
540
            return Response.status(Response.Status.NOT_FOUND).entity(compose404BulkDeleteMessage("Claim ids cannot be empty.",deletedIds,notFoundIds))
541
                    .type(MediaType.APPLICATION_JSON).build();
542
        }
543

  
544
        logger.debug("Trying to delete claims with ids: " + claimIds.toString() + ".");
545
        UserInfo userInfo = authorization.getUserHandler().getUserInfo(token);
546
        for (String claimId : claimIds) {
547
            try {
548

  
549
                if (authorization.isRegistered(userInfo)) {
550
                    if (authorization.isClaimCurator(userInfo) || authorization.isCommunityCurator(userInfo) || userInfo.getEmail().equals(fetchClaimHandler.fetchClaimById(claimId,false).getUserMail())) {
551
                        if (claimHandler.deleteClaim(claimId)) {
552
                            deletedIds.add(claimId);
553
                        } else {
554
                            notFoundIds.add(claimId);
555
                        }
556
                    } else {
557
                        return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to delete."))
558
                                .type(MediaType.APPLICATION_JSON)
559
                                .build();
560
                    }
561
                } else {
562
                    return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. Maybe you are not registered."))
563
                            .type(MediaType.APPLICATION_JSON)
564
                            .build();
565
                }
566
            } catch (SQLStoreException|Exception e) {
567
                logger.error("Fail to delete claim with id " + claimId + ".", e);
568
                notFoundIds.add(claimId);
569
            }
570
        }
571
        logger.debug("Successfully deleted " + deletedIds.size() + " from " + claimIds.size()  +". Deleted claims with ids: " + deletedIds.toString() + ".");
572
        if (claimIds.size() == notFoundIds.size()) {
573
            return Response.status(Response.Status.NOT_FOUND).entity(compose404BulkDeleteMessage("Claim ids cannot be empty.",deletedIds,notFoundIds))
574
                    .type(MediaType.APPLICATION_JSON).build();
575
        } else if (claimIds.size() == notFoundIds.size()) {
576
            return Response.status(204).entity(compose204BulkDeleteMessage(deletedIds,notFoundIds)).type(MediaType.APPLICATION_JSON).build();
577
        } else {
578
            return Response.status(204).entity(compose204BulkDeleteMessage(deletedIds,notFoundIds)).type(MediaType.APPLICATION_JSON).build();
579
        }
580
    }
581

  
582
    @POST
583
    @Path("/claims")
584
    @Produces(MediaType.APPLICATION_JSON)
585
    @Consumes(MediaType.APPLICATION_JSON)
586
    public Response addClaim(String input, @Context HttpServletRequest request,
587
                             @HeaderParam("X-XSRF-TOKEN") String token,
588
                             @HeaderParam("Origin") String origin,
589
                             @CookieParam("AccessToken") String  cookie) {
590

  
591

  
592
        if(!authorization.hasBasicAuthorization(token, origin, cookie)){
593
            return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. Maybe you are not registered."))
594
                    .type(MediaType.APPLICATION_JSON)
595
                    .build();
596
        }
597

  
598
        UserInfo userInfo = authorization.getUserHandler().getUserInfo(token);
599
        if(authorization.isRegistered(userInfo)) {
600
            JsonObject jsonObject = new JsonParser().parse(input).getAsJsonObject();
601

  
602
            String claimedBy = userInfo.getEmail();
603
            logger.info("claimedBy " + claimedBy);
604

  
605
            EmailValidator emailValidator = EmailValidator.getInstance();
606
            if (!emailValidator.isValid(claimedBy)) {
607
                return Response.status(Response.Status.BAD_REQUEST).entity(compose400Message("User e-mail is invalid."))
608
                        .type(MediaType.APPLICATION_JSON).build();
609
            }
610

  
611

  
612
            try {
613
                String claimId = this.getInfoAndBuildClaim(jsonObject,claimedBy);
614
                return Response.status(200).entity(compose201PostMessage(request, claimId)).type(MediaType.APPLICATION_JSON).build();
615

  
616
            } catch (ClaimValidationException ve) {
617
                return Response.status(Response.Status.BAD_REQUEST).entity(compose400Message("The given ids are wrong.", ve))
618
                        .type(MediaType.APPLICATION_JSON).build();
619

  
620
            } catch (SQLStoreException|Exception e) {
621
                logger.error("Fail to add new claim.", e);
622
                return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500Message("Fail to add new claim.", e))
623
                        .type(MediaType.APPLICATION_JSON).build();
624
            }
625
        }
626
        return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access."))
627
                .type(MediaType.APPLICATION_JSON)
628
                .build();
629
    }
630

  
631
    @POST
632
    @Path("/claims/bulk")
633
    @Produces(MediaType.APPLICATION_JSON)
634
    @Consumes(MediaType.APPLICATION_JSON)
635
    public Response addBulkClaims(String input, @Context HttpServletRequest request,
636
                                  @HeaderParam("X-XSRF-TOKEN") String token,
637
                                  @HeaderParam("Origin") String origin,
638
                                  @CookieParam("AccessToken") String  cookie) {
639

  
640

  
641
        if(!authorization.hasBasicAuthorization(token, origin, cookie)){
642
            return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. Maybe you are not registered."))
643
                    .type(MediaType.APPLICATION_JSON)
644
                    .build();
645
        }
646

  
647
        UserInfo userInfo = authorization.getUserHandler().getUserInfo(token);
648
        if(authorization.isRegistered(userInfo)) {
649
            ArrayList<String> insertedIds = new ArrayList<String>();
650
            JsonArray errorInClaims = new JsonArray();
651

  
652
            int code200 = 0;
653
            int code400 = 0;
654
            int code500 = 0;
655

  
656
            JsonArray jsonArray = new JsonParser().parse(input).getAsJsonArray();
657
            for (JsonElement je : jsonArray) {
658
                JsonObject jsonObject = je.getAsJsonObject();
659

  
660
                String claimedBy = userInfo.getEmail();
661
                logger.info("claimedBy " + claimedBy);
662
                logger.debug(jsonObject);
663

  
664

  
665
                EmailValidator emailValidator = EmailValidator.getInstance();
666
                if (!emailValidator.isValid(claimedBy)) {
667
                    jsonObject.addProperty("error", "user");
668
                    logger.error("no valid user");
669
                    //                return Response.status(Response.Status.BAD_REQUEST).entity(compose400Message("User e-mail is invalid."))
670
                    //                        .type(MediaType.APPLICATION_JSON).build();
671
                    code400++;
672
                    errorInClaims.add(jsonObject);
673
                }
674

  
675

  
676
                try {
677
                    String claimId = this.getInfoAndBuildClaim(jsonObject,claimedBy);
678
                    insertedIds.add(claimId);
679
                    code200++;
680
                    //                return Response.status(200).entity(compose201PostMessage(request, claimId)).type(MediaType.APPLICATION_JSON).build();
681

  
682
                } catch (ClaimValidationException ve) {
683
//                    logger.error("Validation Failed fo claim "+jsonObject);
684
                    //                return Response.status(Response.Status.BAD_REQUEST).entity(compose400Message("The given ids are wrong.", ve))
685
                    //                        .type(MediaType.APPLICATION_JSON).build();
686
                    jsonObject.addProperty("error", "validation");
687
                    errorInClaims.add(jsonObject);
688
                    code400++;
689

  
690
                } catch (SQLStoreException|Exception e) {
691
                    logger.error("Fail to add new claim.", e);
692
                    //                return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500Message("Fail to add new claim.", e))
693
                    //                        .type(MediaType.APPLICATION_JSON).build();
694
                    jsonObject.addProperty("error", "insertion");
695
                    errorInClaims.add(jsonObject);
696
                    code500++;
697
                }
698
            }
699
            if (jsonArray.size() == code500) {
700
                return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500BulkInsertMessage("Fail to add new claim.", insertedIds, errorInClaims))
701
                        .type(MediaType.APPLICATION_JSON).build();
702
            } else if (code200 > 0) {
703
                return Response.status(200).entity(compose201BulkInsertMessage(insertedIds, errorInClaims)).type(MediaType.APPLICATION_JSON).build();
704
            } else {
705
                return Response.status(Response.Status.BAD_REQUEST).entity(compose400BulkInsertMessage("The given ids are wrong.", insertedIds, errorInClaims))
706
                        .type(MediaType.APPLICATION_JSON).build();
707
            }
708
        }
709
        return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. You are not registered."))
710
                .type(MediaType.APPLICATION_JSON)
711
                .build();
712

  
713
    }
714
    @POST
715
    @Path("/curate/bulk")
716
    @Produces(MediaType.APPLICATION_JSON)
717
    @Consumes(MediaType.APPLICATION_JSON)
718
    public Response curateBulkClaims(String input, @Context HttpServletRequest request,
719
                                     @HeaderParam("X-XSRF-TOKEN") String token,
720
                                     @HeaderParam("Origin") String origin,
721
                                     @CookieParam("AccessToken") String  cookie) {
722

  
723

  
724
        if(!authorization.hasBasicAuthorization(token, origin, cookie)){
725
            return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. Maybe you are not registered."))
726
                    .type(MediaType.APPLICATION_JSON)
727
                    .build();
728
        }
729
        UserInfo userInfo = authorization.getUserHandler().getUserInfo(token);
730
        if (authorization.isRegistered(userInfo)) {
731
            ArrayList<String> insertedIds = new ArrayList<String>();
732
            JsonArray errorInClaims = new JsonArray();
733
            int code200 = 0;
734
            int code400 = 0;
735
            int code500 = 0;
736
            JsonArray jsonArray = new JsonParser().parse(input).getAsJsonArray();
737
            String curatedBy =userInfo.getEmail();
738

  
739
            for (JsonElement je : jsonArray) {
740
                JsonObject jsonObject = je.getAsJsonObject();
741

  
742
                String id = jsonObject.get("id").getAsString();
743
                logger.info("id " + id);
744

  
745
                Boolean approved = jsonObject.get("approved").getAsBoolean();
746
                logger.info("approved " + approved);
747
                EmailValidator emailValidator = EmailValidator.getInstance();
748
                if (!emailValidator.isValid(curatedBy)) {
749
                    jsonObject.addProperty("error", "user");
750
                    //                return Response.status(Response.Status.BAD_REQUEST).entity(compose400Message("User e-mail is invalid."))
751
                    //                        .type(MediaType.APPLICATION_JSON).build();
752
                    code400++;
753
                    errorInClaims.add(jsonObject);
754
                }
755

  
756
                try {
757
                    claimHandler.updateClaimCurationInfo(curatedBy,id, approved);
758
                    insertedIds.add(id);
759
                    code200++;
760

  
761
                } catch (SQLStoreException|Exception e) {
762
                    jsonObject.addProperty("error", "insertion");
763
                    errorInClaims.add(jsonObject);
764
                    code500++;
765
                }
766
            }
767
            if (jsonArray.size() == code500) {
768
                return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500BulkInsertMessage("Fail to update claims.", insertedIds, errorInClaims))
769
                        .type(MediaType.APPLICATION_JSON).build();
770
            } else if (code200 > 0) {
771
                return Response.status(200).entity(compose201BulkInsertMessage(insertedIds, errorInClaims)).type(MediaType.APPLICATION_JSON).build();
772
            } else {
773
                return Response.status(Response.Status.BAD_REQUEST).entity(compose400BulkInsertMessage("The given ids are wrong.", insertedIds, errorInClaims))
774
                        .type(MediaType.APPLICATION_JSON).build();
775
            }
776
        }
777
        return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. You are not registered."))
778
                .type(MediaType.APPLICATION_JSON)
779
                .build();
780

  
781
    }
782
    @POST
783
    @Path("/feed/bulk")
784
    @Produces(MediaType.APPLICATION_JSON)
785
    @Consumes(MediaType.APPLICATION_JSON)
786
    public Response feedBulkRecords(String input, @Context HttpServletRequest request,
787
                                    @HeaderParam("X-XSRF-TOKEN") String token,
788
                                    @HeaderParam("Origin") String origin,
789
                                    @CookieParam("AccessToken") String  cookie) {
790

  
791

  
792
        if(!authorization.hasBasicAuthorization(token, origin, cookie)){
793

  
794
            return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. Maybe you are not registered."))
795
                    .type(MediaType.APPLICATION_JSON)
796
                    .build();
797
        }
798

  
799
        if (authorization.isRegistered(token)) {
800
            ArrayList<String> insertedIds = new ArrayList<String>();
801
            JsonArray errorInClaims = new JsonArray();
802
            int code200 = 0;
803
            int code400 = 0;
804
            int code500 = 0;
805
            JsonArray jsonArray = new JsonParser().parse(input).getAsJsonArray();
806
            for (JsonElement je : jsonArray) {
807
                JsonObject jsonObject = je.getAsJsonObject();
808
                Boolean inserted = directIndexHandler.insertRecord(new Gson().toJson(jsonObject.get("record")));
809
                if (inserted) {
810
                    insertedIds.add(jsonObject.get("id").getAsString());
811
                    code200++;
812
                } else {
813
                    errorInClaims.add(jsonObject.get("id").getAsString());
814
                    code400++;
815
                }
816

  
817

  
818
            }
819
            if (jsonArray.size() == code500) {
820
                return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500BulkInsertMessage("Fail to add new claim.", insertedIds, errorInClaims))
821
                        .type(MediaType.APPLICATION_JSON).build();
822
            } else if (code200 > 0) {
823
                return Response.status(200).entity(compose201BulkInsertMessage(insertedIds, errorInClaims)).type(MediaType.APPLICATION_JSON).build();
824
            } else {
825
                return Response.status(Response.Status.BAD_REQUEST).entity(compose400BulkInsertMessage("The given ids are wrong.", insertedIds, errorInClaims))
826
                        .type(MediaType.APPLICATION_JSON).build();
827
            }
828
        }
829
        return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. You are not registered."))
830
                .type(MediaType.APPLICATION_JSON)
831
                .build();
832

  
833
    }
834

  
835
    @GET
836
    @Path("/users/notification")
837
    @Produces(MediaType.APPLICATION_JSON)
838
    public Response getUserEmailNotificationPreferences(@QueryParam("communityId") String openaireId,
839
                                                        @HeaderParam("X-XSRF-TOKEN") String token,
840
                                                        @CookieParam("AccessToken") String  cookie,
841
                                                        @Context HttpServletRequest request) {
842

  
843
        if(token == null || token.isEmpty() || cookie == null || cookie.isEmpty() || !cookie.equals(token)){
844
            return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. Maybe you are not registered."))
845
                    .type(MediaType.APPLICATION_JSON)
846
                    .build();
847
        }
848

  
849
        UserInfo userInfo = authorization.getUserHandler().getUserInfo(token);
850
        if(authorization.isRegistered(userInfo)) {
851
            String userMail = userInfo.getEmail();
852
            logger.debug("User is registerd "  );
853

  
854
            EmailValidator emailValidator = EmailValidator.getInstance();
855

  
856
            if (userMail == null || userMail.isEmpty()) {
857
                return Response.status(Response.Status.BAD_REQUEST).entity(compose400Message("User e-mail cannot be empty."))
858
                        .type(MediaType.APPLICATION_JSON).build();
859
            }
860

  
861
            if (!emailValidator.isValid(userMail)) {
862
                return Response.status(Response.Status.BAD_REQUEST).entity(compose400Message("User e-mail is not valid."))
863
                        .type(MediaType.APPLICATION_JSON).build();
864
            }
865

  
866
            List<Notification> notifications = null;
867
            try {
868
                if(openaireId != null) {
869
//                    CommunityUtils communityInfo = this.emailSender.getCommunityUtils().getCommunityInfo(openaireId);
870
                    if(this.emailSender.getManagerUtils().isCommunityManager(openaireId, userMail) || authorization.isCommunityCurator(userInfo)) {
871

  
872
                        Notification notification = null;
873
                        logger.debug("About to fetch notification");
874
                        notification = fetchNotificationHandler.fetchNotification(openaireId, userMail);
875

  
876
                        if (notification != null) {
877
                            notifications = new ArrayList<Notification>();
878
                            notification.setOpenaireName(openaireId);
879
                            notifications.add(notification);
880
                        }
881
                    }else{
882
                        return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. You are not registered."))
883
                                .type(MediaType.APPLICATION_JSON)
884
                                .build();
885
                    }
886
                } else {
887
                    Map<String, String> projectIdsAndNames = fetchProjectHandler.fetchProjectIdsAndNamesByProjectManagerMail(userMail);
888
                    if(projectIdsAndNames != null) {
889
                        for (Map.Entry<String, String> projectIdAndName : projectIdsAndNames.entrySet()) {
890
                            Notification notification = null;
891
                            logger.debug("About to fetch notification");
892
                            notification = fetchNotificationHandler.fetchNotification(projectIdAndName.getKey(), userMail);
893

  
894
                            if (notifications == null) {
895
                                notifications = new ArrayList<Notification>();
896
                            }
897
                            if(notification == null) {
898
                                notification = new Notification(projectIdAndName.getKey(), projectIdAndName.getValue(), userMail, Integer.parseInt(defaultFrequencyInHours), true);
899
                            } else {
900
                                notification.setOpenaireName(projectIdAndName.getValue());
901
                            }
902
                            notifications.add(notification);
903
                            logger.debug(notification);
904
                            logger.debug("notification openaireId:"+notification.getOpenaireId());
905
                            logger.debug(notifications.size());
906
                        }
907
                    }
908
                }
909

  
910
            } catch (SQLStoreException|Exception e) {
911
                logger.error("Could not fetch notification preferences for user with mail " + userMail, e);
912
                return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500Message("Fail to fetch notification preferences" +
913
                        " for user with e-mail " + userMail + ".", e)).type(MediaType.APPLICATION_JSON).build();
914
            }
915

  
916
            if (notifications == null || notifications.isEmpty()) {
917
                return Response.status(Response.Status.NOT_FOUND).entity(compose404Message("There are no notifications for user with mail " + userMail)).type(MediaType.APPLICATION_JSON).build();
918
            }
919

  
920
            return Response.status(200).entity(composeDataResponse(notifications)).build();
921

  
922
        }
923
        logger.debug("User is *NOT* registerd "  );
924
        return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. You are not registered."))
925
                .type(MediaType.APPLICATION_JSON)
926
                .build();
927
    }
928

  
929
    @POST
930
    @Path("/users/notification/save")
931
    @Produces(MediaType.APPLICATION_JSON)
932
    @Consumes(MediaType.APPLICATION_JSON)
933
    public Response saveOrUpdateUserEmailNotificationPreferences(String input, @Context HttpServletRequest request,
934
                                                                 @HeaderParam("X-XSRF-TOKEN") String token,
935
                                                                 @HeaderParam("Origin") String origin,
936
                                                                 @CookieParam("AccessToken") String  cookie) {
937

  
938

  
939
        if(!authorization.hasBasicAuthorization(token, origin, cookie)){
940
            return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. Maybe you are not registered."))
941
                    .type(MediaType.APPLICATION_JSON)
942
                    .build();
943
        }
944
        UserInfo userInfo = authorization.getUserHandler().getUserInfo(token);
945
        if (authorization.isRegistered(userInfo)) {
946
            ArrayList<String> insertedIds = new ArrayList<String>();
947
            JsonArray errorInClaims = new JsonArray();
948
            int code200 = 0;
949
            int code400 = 0;
950
            int code500 = 0;
951
            JsonObject jsonObject = new JsonParser().parse(input).getAsJsonObject();
952

  
953
            String userMail =userInfo.getEmail();
954

  
955
            String openaireId = jsonObject.get("openaireId").getAsString();
956
            logger.info("openaireId " + openaireId);
957

  
958
            boolean notify = jsonObject.get("notify").getAsBoolean();
959
            logger.info("notify "+notify);
960

  
961
            int frequency = jsonObject.get("frequency").getAsInt();
962
            logger.info("frequency " + frequency);
963

  
964
            EmailValidator emailValidator = EmailValidator.getInstance();
965
            if (!emailValidator.isValid(userMail)) {
966
                jsonObject.addProperty("error", "user");
967
                return Response.status(Response.Status.BAD_REQUEST).entity(compose400Message("User e-mail is invalid."))
968
                        .type(MediaType.APPLICATION_JSON).build();
969
            }
970

  
971
            try {
972
                boolean continueProcedure = false;
973
                List<String> managers = null;
974
                try {
975
                    managers = fetchProjectHandler.fetchContactEmailsByProjectId(openaireId);
976
                } catch (Exception e) {
977
                    e.printStackTrace();
978
                } catch (SQLStoreException e) {
979
                    e.printStackTrace();
980
                }
981
                if(managers != null && managers.contains(userMail)) {
982
                    continueProcedure = true;
983
                } else {
984
//                    CommunityUtils communityInfo = this.emailSender.getCommunityUtils().getCommunityInfo(openaireId);
985
                    if(this.emailSender.getManagerUtils().isCommunityManager(openaireId, userMail) || authorization.isCommunityCurator(userInfo) ) {
986
                        continueProcedure = true;
987
                    }
988
                }
989

  
990
                if(continueProcedure) {
991
                    Notification notification = null;
992
                    logger.debug("About to fetch notification");
993
                    notification = fetchNotificationHandler.fetchNotification(openaireId, userMail);
994

  
995
                    if (notification == null) {
996
                        logger.debug("About to insert notification");
997
                        notificationHandler.buildAndInsertNotification(openaireId, userMail, frequency, notify);
998
                    } else {
999
                        logger.debug("About to update notification");
1000
                        notificationHandler.updateNotificationPreferences(openaireId, userMail, frequency, notify);
1001
                    }
1002
                } else {
1003
                    return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. You are not registered."))
1004
                            .type(MediaType.APPLICATION_JSON)
1005
                            .build();
1006
                }
1007
            } catch (SQLStoreException|Exception e) {
1008
                logger.error("Could not save or update notification preferences for user with mail " + userMail, e);
1009
                return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500Message("Fail to fetch notification preferences" +
1010
                        " for user with e-mail " + userMail + ".", e)).type(MediaType.APPLICATION_JSON).build();
1011
            }
1012

  
1013
            return Response.status(200).entity(compose200Message("Save or Update for notification successful")).type(MediaType.APPLICATION_JSON).build();
1014
        }
1015
        return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. You are not registered."))
1016
                .type(MediaType.APPLICATION_JSON)
1017
                .build();
1018
    }
1019

  
1020
    private String xml2Json(List<String> input) {
1021
        StringBuilder builder = new StringBuilder();
1022
        for(String category: input) {
1023
            builder.append(category);
1024
        }
1025
        return builder.toString();
1026
    }
1027

  
1028
    private  String compose200Message(String message){
1029
        return " { \"status\" : \"success\", \"code\": \"200\", \"message\" : \"  " + message +" \" }";
1030
    }
1031

  
1032
    private String compose204Message(String message) {
1033
        return  "{ \"status\" : \"error\", \"code\" : \"204\", \"message\" : \"  " + message +" \" }";
1034
    }
1035

  
1036
    private String compose400Message(String message) {
1037
        return  "{ \"status\" : \"error\", \"code\" : \"400\", \"message\" : \"  " + message +" \" }";
1038
    }
1039

  
1040
    private String compose400Message(String message, Exception exception) {
1041
        return  "{ \"status\" : \"error\", \"code\" : \"400\", \"message\" : \"  " + message +"\", " +
1042
                "\"description\" : \""+  exception.getMessage() +"\" }";
1043
    }
1044

  
1045
    private String compose403Message(String message) {
1046
        return  "{ \"status\" : \"error\", \"code\" : \"403\", \"message\" : \"  " + message +"\", " +
1047
                "\"description\" : \"\" }";
1048
    }
1049

  
1050
    private String compose404BulkDeleteMessage(String message, List<String> deletedIds, List<String> notFoundIds) {
1051
        return  "{ \"status\" : \"error\", \"code\" : \"404\", \"message\" : \"  " + message +" \","+  "\"deletedIds\" : " + new Gson().toJson(deletedIds) +","+  "\"notFoundIds\" : " + new Gson().toJson(notFoundIds) + " }";
1052
    }
1053
    private String compose404Message(String message) {
1054
        return  "{ \"status\" : \"error\", \"code\" : \"404\", \"message\" : \"  " + message +" \" }";
1055
    }
1056

  
1057
    private String compose400BulkInsertMessage(String message, List<String> insertedIds,JsonArray errorInClaims) {
1058
        return  "{ \"status\" : \"error\", \"code\" : \"400\", \"message\" : \"  " + message +" \""+  ", \"insertedIds\" : " + new Gson().toJson(insertedIds) +","+  "\"errorInClaims\" : " + new Gson().toJson(errorInClaims) + " }";
1059
    }
1060

  
1061
    private String compose500Message(String message, Throwable throwable) {
1062
        return  "{ \"status\" : \"fail\", \"code\" : \"500\", \"message\" : \"  " + message + "\", " +
1063
                "\"description\" : \""+  throwable.getMessage() +"\" }";
1064
    }
1065

  
1066
    private String compose500BulkInsertMessage(String message,  List<String> insertedIds, JsonArray errorInClaims) {
1067
        return  "{ \"status\" : \"fail\", \"code\" : \"500\", \"message\" : \"  " + message + "\", " +
1068
                "\"description\" : \""+   "\" , " +  "\"insertedIds\" : " + new Gson().toJson(insertedIds) +","+  "\"errorInClaims\" : " + new Gson().toJson(errorInClaims) + " }";
1069
    }
1070

  
1071
    /*
1072
    TODO check if needed
1073
    private String compose500BulkDeleteMessage(String message,  List<String> deletedIds, List<String> notFoundIds, Exception exception) {
1074
        return  "{ \"status\" : \"fail\", \"code\" : \"500\", \"message\" : \"  " + message + "\", " +
1075
                "\"description\" : \""+  exception.getMessage() +"\" ," +  "\"deletedIds\" : " + new Gson().toJson(deletedIds) +","+  "\"notFoundIds\" : " + new Gson().toJson(notFoundIds) + " }";
1076
    }
1077

  
1078

  
1079

  
1080
    TODO check if needed
1081
    private  String compose204Message(){
1082
        return " { \"status\" : \"success\", \"code\": \"204\" }";
1083
    } */
1084

  
1085
    private  String compose204BulkDeleteMessage(List<String> deletedIds, List<String> notFoundIds){
1086
        return " { \"status\" : \"success\", \"code\": \"204\", "+ "\"deletedIds\" : " + new Gson().toJson(deletedIds) +","+  "\"notFoundIds\" : " + new Gson().toJson(notFoundIds) + "}";
1087
    }
1088

  
1089

  
1090
    private  String compose201PostMessage(@Context HttpServletRequest request, String claimId){
1091
        String url = request.getRequestURL().toString();
1092
        //String query = request.getQueryString();
1093

  
1094
        return " { \"status\" : \"success\", \"code\": \"201\", \"link\": \"" + url  +"/"+ claimId +"\" }";
1095
    }
1096
    private  String compose201BulkInsertMessage(List<String> insertedIds, JsonArray errorInClaims){
1097
        //String url = request.getRequestURL().toString();
1098
        //String query = request.getQueryString();
1099

  
1100
        return " { \"status\" : \"success\", \"code\": \"201\","+ "\"insertedIds\" : " + new Gson().toJson(insertedIds) +","+  "\"errorInClaims\" : " + new Gson().toJson(errorInClaims)+ "}";
1101
    }
1102
    private String composeDataResponse(HttpServletRequest request, List<Claim> claims, int total, int offset, int limit) {
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff