Project

General

Profile

« Previous | Next » 

Revision 48535

Removing released version with SNAPSHOT

View differences:

modules/uoa-claims-api/tags/uoa-claims-api-2.0.1/deploy.info
1
{
2
  "type_source": "SVN", 
3
  "goal": "package -U -T 4C source:jar", 
4
  "url": "http://svn-public.driver.research-infrastructures.eu/driver/dnet45/modules/uoa-claims-api/trunk", 
5
  "deploy_repository": "dnet45-snapshots", 
6
  "version": "4", 
7
  "mail": "kiatrop@di.uoa.gr, argirok@di.uoa.gr, kgalouni@di.uoa.gr", 
8
  "deploy_repository_url": "http://maven.research-infrastructures.eu/nexus/content/repositories/dnet45-snapshots", 
9
  "name": "uoa-openaire-connector"
10
}
modules/uoa-claims-api/tags/uoa-claims-api-2.0.1/src/main/java/eu/dnetlib/openaire/rest/inputHandler/UserHandler.java
1
package eu.dnetlib.openaire.rest.inputHandler;
2

  
3
import com.google.gson.Gson;
4
import eu.dnetlib.openaire.rest.Authorization;
5
import eu.dnetlib.openaire.rest.UserInfo;
6
import io.jsonwebtoken.Claims;
7
import io.jsonwebtoken.Jwts;
8
import org.apache.log4j.BasicConfigurator;
9
import org.apache.log4j.Logger;
10
import org.springframework.context.ApplicationContext;
11
import org.springframework.context.support.ClassPathXmlApplicationContext;
12

  
13
import javax.xml.bind.DatatypeConverter;
14
import java.io.BufferedReader;
15
import java.io.IOException;
16
import java.io.InputStreamReader;
17
import java.io.StringReader;
18
import java.net.HttpURLConnection;
19
import java.net.URL;
20

  
21
/**
22
 * Created by sofia on 20/4/2017.
23
 */
24
public class UserHandler{
25
    private static Logger logger = Logger.getLogger(UserHandler.class);
26

  
27
    String userInfoUrl = null;
28
        public  String getMail(String token) {
29

  
30
            Claims claims = Jwts.parser()
31
                    .setSigningKey(DatatypeConverter.parseBase64Binary("my-very-secret"))
32
                    .parseClaimsJws(token).getBody();
33

  
34
            return (String) claims.get("email");
35

  
36
        }
37

  
38
    public  UserInfo getUserInfo(String accessToken){
39
        String url=userInfoUrl+accessToken;
40
        URL obj = null;
41
        String responseStr=null;
42
        logger.debug("User info url is "+url);
43

  
44
            try {
45
                obj = new URL(url);
46
                HttpURLConnection con = (HttpURLConnection) obj.openConnection();
47
                logger.debug("User info response code is: " + con.getResponseCode());
48
                if (con.getResponseCode() != 200) {
49
                    return null;
50
                }
51
                BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
52
                StringBuffer response = new StringBuffer();
53
                String inputLine;
54
                while ((inputLine = in.readLine()) != null) {
55
                    response.append(inputLine).append("\n");
56
                }
57
                in.close();
58
                responseStr = response.toString();
59
            }catch(Exception e){
60
                logger.error("An error occured while trying to fetch user info ",e);
61
                return null;
62
            }
63
        return json2UserInfo(responseStr);
64
    }
65

  
66
    private  UserInfo json2UserInfo(String json) {
67

  
68
        logger.debug("Try to create userInfo class from json: "+json);
69
         if (json == null){
70
            return null;
71
        }
72

  
73
        BufferedReader br = new BufferedReader(new StringReader(json));
74
        //convert the json string back to object
75
        Gson gson = new Gson();
76
        UserInfo userInfo = null;
77
        try {
78
            userInfo = gson.fromJson(br, UserInfo.class);
79
        }catch(Exception e){
80
            logger.debug("Error in parsing json response. Given json is : "+json);
81
            return null;
82
        }
83
        logger.debug("Original response : "+userInfo.toString());
84

  
85
        if(userInfo != null && userInfo.getEdu_person_entitlements() != null ) {
86
            for (int i = 0; i < userInfo.getEdu_person_entitlements().size(); i++) {
87
                String role = userInfo.getEdu_person_entitlements().get(i);
88
                role = role.split("urn:mace:openminted.eu:aai.openminted.eu:group:OpenAIRE\\+")[1];
89
                role = role.replace("+"," ");
90
                userInfo.getEdu_person_entitlements().set(i,role);
91
            }
92
        }
93
        logger.debug("After handling roles : "+userInfo.toString());
94

  
95

  
96
        return userInfo;
97
    }
98

  
99
    public String getUserInfoUrl() {
100
        return userInfoUrl;
101
    }
102

  
103
    public void setUserInfoUrl(String userInfoUrl) {
104
        this.userInfoUrl = userInfoUrl;
105
    }
106

  
107
    public static void main(String[] args) throws IOException {
108
        BasicConfigurator.configure();
109
        ApplicationContext context = new ClassPathXmlApplicationContext("eu/dnetlib/openaire/rest/springContext-claims-authorization.xml");
110

  
111
        Authorization authorization =  context.getBean(Authorization.class);
112
        UserHandler userHandler = context.getBean(UserHandler.class);
113
        System.out.println("\n\nAdmin Roles "+authorization.getAdminRoles().size()+"   "+authorization.getAdminRoles()+"\n\n\n");
114
        System.out.println("\n\ngetProjectCuratorRoles Roles "+authorization.getProjectCuratorRoles().size()+"   "+authorization.getProjectCuratorRoles()+"\n\n\n");
115
        System.out.println("\n\ngetRegisteredRoles Roles "+authorization.getRegisteredRoles().size()+"   "+authorization.getRegisteredRoles()+"\n\n\n");
116

  
117
        System.out.println("\n\nIs Admin::\n"+authorization.isAdmin("eyJraWQiOiJvaWRjIiwiYWxnIjoiUlMyNTYifQ.eyJzdWIiOiIwOTMxNzMwMTMyODMzNjMyQG9wZW5taW50ZWQuZXUiLCJhenAiOiIyNGU4MzE3Ni0xMzEyLTRiYTMtYmMwYi1mZmVlYmVhMTYwM2UiLCJpc3MiOiJodHRwczpcL1wvYWFpLm9wZW5taW50ZWQuZXVcL29pZGNcLyIsImV4cCI6MTQ5ODQ4NTk3NiwiaWF0IjoxNDk4NDcxNTc2LCJqdGkiOiJkMWRlZjc1Yi00MTEyLTRiZDktYTIyNi0wZThhOWI2M2Y3MWQifQ.WVYOb_yO8OaxIIt2jRYEDQBhGGFRDTBw3DgtVV_smuN5yx1ScCj6aehLu3JKPSArme4m2SGF4TEGhpwNJkwhM2WapGtxmtuCmCzYIo_QlC1Yki9hr2OT2rXMcQsJCiKaBSf6pLue6Sn78GMB5yaUTvOQHRgidXGiZXH5lsuZUx15Q6Equ_wzond_rgP9mRheRkTyIFuvvg4PuzmudBc11Ty863vIIQtoWF7_p98zTbHxiNF9lLPwzPZKxDoQ8JeayQEC-jsWVLgxmp-h0jG_Ko5jFVVJeeosqMMucOrs2FT_NKHVYVqB6VVh0C6nOufeiLrNDeMUlDT4dAvKD2zE9w")
118
                +"\n\n\n");
119
//        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\"]}");
120
//        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\"]}");
121
//        boolean b=authorization.isProjectCurator(u);
122
//        System.out.println(b);
123
//        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\"]}");
124
//        UserHandler.json2UserInfo(null);
125
//        UserHandler.json2UserInfo("mpla mpla mpla .... {}");
126
//        userHandler.getUserInfo("eyJraWQiOiJvaWRjIiwiYWxnIjoiUlMyNTYifQ.eyJzdWIiOiIwOTMxNzMwMTMyODMzNjMyQG9wZW5taW50ZWQuZXUiLCJhenAiOiIyNGU4MzE3Ni0xMzEyLTRiYTMtYmMwYi1mZmVlYmVhMTYwM2UiLCJpc3MiOiJodHRwczpcL1wvYWFpLm9wZW5taW50ZWQuZXVcL29pZGNcLyIsImV4cCI6MTQ5ODQ4NTk3NiwiaWF0IjoxNDk4NDcxNTc2LCJqdGkiOiJkMWRlZjc1Yi00MTEyLTRiZDktYTIyNi0wZThhOWI2M2Y3MWQifQ.WVYOb_yO8OaxIIt2jRYEDQBhGGFRDTBw3DgtVV_smuN5yx1ScCj6aehLu3JKPSArme4m2SGF4TEGhpwNJkwhM2WapGtxmtuCmCzYIo_QlC1Yki9hr2OT2rXMcQsJCiKaBSf6pLue6Sn78GMB5yaUTvOQHRgidXGiZXH5lsuZUx15Q6Equ_wzond_rgP9mRheRkTyIFuvvg4PuzmudBc11Ty863vIIQtoWF7_p98zTbHxiNF9lLPwzPZKxDoQ8JeayQEC-jsWVLgxmp-h0jG_Ko5jFVVJeeosqMMucOrs2FT_NKHVYVqB6VVh0C6nOufeiLrNDeMUlDT4dAvKD2zE9w");
127
    }
128
}
modules/uoa-claims-api/tags/uoa-claims-api-2.0.1/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.log4j.Logger;
5

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

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

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

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

  
55
    }
56

  
57
    public boolean isRegistered(UserInfo userInfo) {
58
        if (userInfo != null && userInfo.getEdu_person_entitlements() != null) {
59

  
60
            return hasRole(userInfo.getEdu_person_entitlements(), registeredRoles);
61
        } else {
62
            return false;
63
        }
64

  
65
    }
66

  
67
    public boolean isAdmin(String token) {
68
        UserInfo userInfo = userHandler.getUserInfo(token);
69
        return isAdmin(userInfo);
70

  
71
    }
72

  
73
    public boolean isAdmin(UserInfo userInfo) {
74
        if (userInfo != null && userInfo.getEdu_person_entitlements() != null) {
75

  
76
            return hasRole(userInfo.getEdu_person_entitlements(), adminRoles);
77
        } else {
78
            logger.debug(" User has no Valid UserInfo");
79
            return false;
80
        }
81

  
82
    }
83

  
84
    public boolean isProjectCurator(String token) {
85
        UserInfo userInfo = userHandler.getUserInfo(token);
86
        return isProjectCurator(userInfo);
87

  
88
    }
89

  
90
    public boolean isProjectCurator(UserInfo userInfo) {
91
        if (userInfo != null && userInfo.getEdu_person_entitlements() != null) {
92

  
93
            return hasRole(userInfo.getEdu_person_entitlements(), projectCuratorRoles);
94
        } else {
95
            return false;
96
        }
97

  
98
    }
99

  
100
    public boolean hasRole(List<String> givenRoles, List<String> authorizedRoles) {
101

  
102
        logger.debug("It's  registered with role " + givenRoles);
103
        for (String gRole : givenRoles) {
104
            if (authorizedRoles.indexOf(gRole) != -1) {
105
                return true;
106
            }
107
        }
108
        logger.debug("Not Authorized. Authorized roles are" + authorizedRoles);
109
        return false;
110

  
111
    }
112

  
113
    public boolean hasValidOrigin(String origin) {
114
        if (origin != null && originServer.equals(origin)) {
115
            return true;
116
        }
117
        return false;
118
    }
119

  
120
    public List<String> getRegisteredRoles() {
121
        return registeredRoles;
122
    }
123

  
124
    public void setRegisteredRoles(List<String> registeredRoles) {
125
        this.registeredRoles = registeredRoles;
126
    }
127

  
128
    public List<String> getAdminRoles() {
129
        return adminRoles;
130
    }
131

  
132
    public void setAdminRoles(List<String> adminRoles) {
133
        this.adminRoles = adminRoles;
134
    }
135

  
136
    public List<String> getProjectCuratorRoles() {
137
        return projectCuratorRoles;
138
    }
139

  
140
    public void setProjectCuratorRoles(List<String> projectCuratorRoles) {
141
        this.projectCuratorRoles = projectCuratorRoles;
142
    }
143

  
144
    public UserHandler getUserHandler() {
145
        return userHandler;
146
    }
147

  
148
    public void setUserHandler(UserHandler userHandler) {
149
        this.userHandler = userHandler;
150
    }
151

  
152
    public String getOriginServer() {
153
        return originServer;
154
    }
155

  
156
    public void setOriginServer(String originServer) {
157
        this.originServer = originServer;
158
    }
159
}
modules/uoa-claims-api/tags/uoa-claims-api-2.0.1/src/main/java/eu/dnetlib/openaire/rest/authorization/Authorization.java
1
package eu.dnetlib.openaire.rest.authorization;
2

  
3
import io.jsonwebtoken.Claims;
4
import io.jsonwebtoken.Jwts;
5
import org.apache.log4j.Logger;
6

  
7
import javax.xml.bind.DatatypeConverter;
8

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

  
14
    private static Logger logger = Logger.getLogger(Authorization.class);
15

  
16
    public static boolean isRegistered(String token) {
17

  
18
        Claims claims = Jwts.parser()
19
                .setSigningKey(DatatypeConverter.parseBase64Binary("my-very-secret"))
20
                .parseClaimsJws(token).getBody();
21

  
22
        if (claims.get("role").equals(1) || claims.get("role").equals(2)) {
23
            logger.debug(claims.get("role"));
24
            return true;
25
        } else {
26
            return false;
27
        }
28
    }
29

  
30
    public static boolean isAdmin(String token) {
31
        Claims claims = Jwts.parser()
32
                .setSigningKey(DatatypeConverter.parseBase64Binary("my-very-secret"))
33
                .parseClaimsJws(token).getBody();
34

  
35
        if (claims.get("role").equals(2)) {
36
            return true;
37
        } else {
38
            return false;
39
        }
40
    }
41

  
42
}
modules/uoa-claims-api/tags/uoa-claims-api-2.0.1/src/main/java/eu/dnetlib/openaire/rest/security/JWTValidator.java
1
package eu.dnetlib.openaire.rest.security;
2

  
3
import io.jsonwebtoken.*;
4
import org.apache.log4j.Logger;
5

  
6
import javax.xml.bind.DatatypeConverter;
7

  
8
/**
9
 * Created by kiatrop on 10/4/2017.
10
 */
11
public class JWTValidator {
12

  
13
    private static final Logger logger = Logger.getLogger(JWTValidator.class);
14

  
15
    public static boolean isValid(String token) {
16

  
17
        //String subject = "my-very-secret";
18
        try {
19

  
20
            //This line will throw an exception if it is not a signed JWS (as expected)
21
            Claims claims = Jwts.parser()
22
                .setSigningKey(DatatypeConverter.parseBase64Binary("my-very-secret"))
23
                .parseClaimsJws(token).getBody();
24

  
25
            logger.debug("Id: " + claims.get("userId"));
26
            logger.debug("Subject: " + claims.getSubject());
27
            logger.debug("Fullname: " + claims.get("fullname"));
28
            logger.debug("Email: " + claims.get("email"));
29
            logger.debug("Role: " + claims.get("role"));
30
            logger.debug("Expiration: " + claims.getExpiration());
31

  
32
            return true;
33

  
34
        } catch (SignatureException e) {
35
            logger.error("Either calculating a signature or verifying an existing signature of a JWT failed", e);
36
            return false;
37
        } catch(PrematureJwtException e) {
38
            logger.error("A JWT was accepted before it is allowed to be accessed and must be rejected", e);
39
            return false;
40
        } catch(ClaimJwtException e){
41
            logger.error("After a validation of a JWT claim failed", e);
42
            return false;
43
        } catch(MalformedJwtException e){
44
            logger.error("A JWT was not correctly constructed and should be rejected", e);
45
            return false;
46
        } catch(UnsupportedJwtException e){
47
            logger.error("Receiving a JWT in a particular format/configuration that does not match the format expected by the application", e);
48
            return false;
49
        }
50
    }
51

  
52
//    public static void main(String[] args) {
53
//
54
//        // valid (isValid("eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJBcmdpcm8iLCJmdWxsbmFtZSI6IkFyZ2lybyBLb2tvZ2lhbmFraSIsInVzZXJJZCI6IjgiLCJlbWFpbCI6ImFyZ2lyb0BnbWFpbC5jb20iLCJyb2xlIjoyLCJleHAiOjE0OTIwMDEyMzN9.u2xTTyjF6_n60yiz-Pfj72TQIaVNRgxt7Qe8w_AxoTBulKuiq6ldzZHDvgcef2jsA12TFRgfIyfXhsTj-04P5A"))
55
//        // not valid "eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJBcmdpcm8iLCJmdWxsbmFtZSI6IkFyZ2lybyBLb2tvZ2lhbmFraSIsInVzZXJJZCI6IjgiLCJlbWFpbCI6ImFyZ2lyb0BnbWFpbC5jb20iLCJyb2xlIjoyLCJleHAiOjE0OTE5ODk2Njh9.JUiFGEverBVbo3eXlV2nX265cwNTYH1EJGZT0IcGyY31WUDHiGmtnTY-NwZsy0R93irVhAzVhTlmZI_DSRQ"
56
//        //if (isValid("eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJzYmEiLCJmdWxsbmFtZSI6InNvZmlhICIsInVzZXJJZCI6IjYiLCJlbWFpbCI6InNvZmllX21wbEBob3RtYWlsLmNvbSIsInJvbGUiOjEsImV4cCI6MTQ5Mjc3ODY2M30.LcgYcBuI0V8tsZZR_Pnnb5Kk0_GfblxNC6FH1CHT2q7u4j9hcETb1EYLIKPZdkErXJ_MSC1jHNUiS5qCzEQQ2w"))
57
//
58
//        if(isValid("eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJBcmdpcm8iLCJmdWxsbmFtZSI6IkFyZ2lybyBLb2tvZ2lhbmFraSIsInVzZXJJZCI6IjgiLCJlbWFpbCI6ImFyZ2lyb0BnbWFpbC5jb20iLCJyb2xlIjoyLCJleHAiOjE0OTI3ODY4MTl9.F-cFGmSvZLAF70PCz9PE6jOwSg6aAiUW2lklkS-eKCxkjwbqPJLWlNWP10Czg4j1_iKDTvHR7wbhbRyJPoqvNQ"))
59
//            System.out.println("Valid");
60
//        else
61
//            System.out.println("Not Valid");
62
//
63
//    }
64

  
65
}
modules/uoa-claims-api/tags/uoa-claims-api-2.0.1/src/main/java/eu/dnetlib/openaire/rest/UserInfo.java
1
package eu.dnetlib.openaire.rest;
2

  
3
import java.util.ArrayList;
4
import java.util.List;
5

  
6
/**
7
 * Created by argirok on 23/6/2017.
8
 */
9
public class UserInfo {
10
    String name;
11
    String email;
12
    List<String> edu_person_entitlements =  new ArrayList<String>();
13

  
14
    @Override
15
    public String toString() {
16
        return "UserInfo{" +
17
                "name='" + name + '\'' +
18
                ", email='" + email + '\'' +
19
                ", edu_person_entitlements=" + edu_person_entitlements +
20
                '}';
21
    }
22

  
23
    public String getName() {
24
        return name;
25
    }
26

  
27
    public void setName(String name) {
28
        this.name = name;
29
    }
30

  
31
    public String getEmail() {
32
        return email;
33
    }
34

  
35
    public void setEmail(String email) {
36
        this.email = email;
37
    }
38

  
39
    public List<String> getEdu_person_entitlements() {
40
        return edu_person_entitlements;
41
    }
42

  
43
    public void setEdu_person_entitlements(List<String> edu_person_entitlements) {
44
        this.edu_person_entitlements = edu_person_entitlements;
45
    }
46
}
modules/uoa-claims-api/tags/uoa-claims-api-2.0.1/src/main/java/eu/dnetlib/openaire/rest/HelloWorldService.java
1
package eu.dnetlib.openaire.rest;
2

  
3
import com.google.gson.*;
4
import eu.dnetlib.api.enabling.ISLookUpService;
5
import eu.dnetlib.api.enabling.ISLookUpServiceException;
6
import eu.dnetlib.data.claims.migration.ClaimValidationException;
7
import eu.dnetlib.data.claims.migration.entity.Claim;
8
import eu.dnetlib.data.claims.migration.handler.ClaimHandler;
9
import eu.dnetlib.data.claims.migration.handler.DirectIndexHandler;
10
import eu.dnetlib.data.claims.migration.handler.FetchClaimHandler;
11
import eu.dnetlib.data.claims.migration.handler.FetchProjectHandler;
12
import eu.dnetlib.data.claimsDemo.SQLStoreException;
13
import gr.uoa.di.driver.util.ServiceLocator;
14
import org.apache.commons.validator.EmailValidator;
15
import org.apache.log4j.Logger;
16
import org.json.XML;
17
import org.springframework.beans.factory.annotation.Autowired;
18
import org.springframework.stereotype.Component;
19

  
20
import javax.annotation.Resource;
21
import javax.servlet.http.HttpServletRequest;
22
import javax.ws.rs.*;
23
import javax.ws.rs.core.Context;
24
import javax.ws.rs.core.MediaType;
25
import javax.ws.rs.core.Response;
26
import java.util.ArrayList;
27
import java.util.List;
28

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

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

  
38
    @Autowired
39
    private FetchClaimHandler fetchClaimHandler = null;
40

  
41
    @Autowired
42
    private FetchProjectHandler fetchProjectHandler= null;
43

  
44
    @Resource
45
    private ServiceLocator<ISLookUpService> lookupServiceLocator = null;
46

  
47
    @Autowired
48
    private ClaimHandler claimHandler = null;
49

  
50
    @Autowired
51
    private DirectIndexHandler directIndexHandler = null;
52

  
53
    @Autowired
54
    public Authorization authorization = null;
55

  
56

  
57
    @GET
58
    @Path("projects/{projectId}/claims")
59
    @Produces(MediaType.APPLICATION_JSON)
60
    public Response getProjectClaims(@PathParam("projectId") String projectId,
61
                           @DefaultValue("0") @QueryParam("offset") int offset,
62
                           @DefaultValue("20") @QueryParam("limit") int limit,
63
                           @DefaultValue("") @QueryParam("keyword") String keyword,
64
                           @DefaultValue("") @QueryParam("sortby") String orderby,
65
                           @DefaultValue("true") @QueryParam("descending") boolean descending,
66
                           @DefaultValue("") @QueryParam("types") String types,
67
                                     @HeaderParam("X-XSRF-TOKEN") String token,
68
                                     @CookieParam("AccessToken") String  cookie,
69
                           @Context HttpServletRequest request) {
70
        logger.debug("header \"X-XSRF-TOKEN\" has value " + token);
71
        logger.debug("cookie  \"AccessToken\" has value  " + cookie);
72

  
73
        if(token == null || token.isEmpty() || cookie == null || cookie.isEmpty() || !cookie.equals(token)){
74
            return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. Maybe you are not registered."))
75
                    .type(MediaType.APPLICATION_JSON)
76
                    .build();
77
        }
78

  
79
        if(authorization.isAdmin(token)) {
80

  
81
            int total = -1;
82

  
83
            if (projectId == null || projectId.isEmpty()) {
84
                return Response.status(Response.Status.BAD_REQUEST).entity(compose400Message("Project id cannot be empty."))
85
                        .type(MediaType.APPLICATION_JSON).build();
86
            }
87

  
88
            List<Claim> claims = null;
89
            List<String> listTypes = new ArrayList<String>();
90
            String[] types_array = types.split(",");
91
            for (int i = 0; i < types_array.length; i++) {
92
                if (types_array[i].length() > 0) {
93
                    listTypes.add(types_array[i]);
94
                }
95
            }
96
            try {
97
                claims = fetchClaimHandler.fetchClaimsByProject(projectId, limit, offset, keyword, orderby, descending, listTypes,false);
98
                total = fetchClaimHandler.countClaimsByProject(projectId, keyword, listTypes);
99

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

  
105
            }
106

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

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

  
115
    @GET
116
    @Path("project/claims")
117
    @Produces(MediaType.APPLICATION_JSON)
118
    public Response getProjectClaimsByToken(@QueryParam("projectToken") String projectToken,
119
                                     @DefaultValue("-1") @QueryParam("offset") int offset,
120
                                     @DefaultValue("-1") @QueryParam("limit") int limit,
121
                                     @DefaultValue("") @QueryParam("keyword") String keyword,
122
                                     @DefaultValue("") @QueryParam("sortby") String orderby,
123
                                     @DefaultValue("true") @QueryParam("descending") boolean descending,
124
                                     @DefaultValue("") @QueryParam("types") String types,
125
                                     @HeaderParam("X-XSRF-TOKEN") String token,
126
                                     @CookieParam("AccessToken") String  cookie,
127
                                     @Context HttpServletRequest request) {
128
        logger.debug("header \"X-XSRF-TOKEN\" has value " + token);
129
        logger.debug("cookie  \"AccessToken\" has value  " + cookie);
130

  
131
        if(token == null || token.isEmpty() || cookie == null || cookie.isEmpty() || !cookie.equals(token)){
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 (projectToken == null || projectToken.isEmpty()) {
144
                return Response.status(Response.Status.BAD_REQUEST).entity(compose400Message("Project token cannot be empty."))
145
                        .type(MediaType.APPLICATION_JSON).build();
146
            }
147

  
148
            List<Claim> claims = null;
149
            List<String> listTypes = new ArrayList<String>();
150
            String[] types_array = types.split(",");
151
            for (int i = 0; i < types_array.length; i++) {
152
                if (types_array[i].length() > 0) {
153
                    listTypes.add(types_array[i]);
154
                }
155
            }
156
            try {
157
                String projectId = fetchProjectHandler.fetchProjectIdByToken(projectToken,userMail);
158
                if(projectId == null){
159
                    return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access"))
160
                            .type(MediaType.APPLICATION_JSON)
161
                            .build();
162
                }else{
163
                    if(offset == -1 && limit == -1) {
164
                        // when offset and limit are -1 fetch claims with null values, to ignore paging and limit clause
165
                        claims = fetchClaimHandler.fetchClaimsByProject(projectId, null, null, keyword, orderby, descending, listTypes, true);
166
                    } else {
167
                        claims = fetchClaimHandler.fetchClaimsByProject(projectId, limit, offset, keyword, orderby, descending, listTypes, true);
168
                    }
169
                    total = fetchClaimHandler.countClaimsByProject(projectId, keyword, listTypes);
170

  
171
                    return Response.status(200).entity(composeDataResponse(request, claims, total, offset, limit)).build();
172
                }
173

  
174
            } catch (SQLStoreException|Exception e) {
175
                logger.error("Could not fetch claims for project token " + projectToken, e);
176
                return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500Message("Fail to fetch claims" +
177
                        " for projects with token " + projectToken + ".", e)).type(MediaType.APPLICATION_JSON).build();
178
            }
179
        }
180

  
181
        return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access"))
182
                .type(MediaType.APPLICATION_JSON)
183
                .build();
184
    }
185
    @GET
186
    @Path("/contexts/{contextId}/claims")
187
    @Produces(MediaType.APPLICATION_JSON)
188
    public Response getContextClaims(@PathParam("contextId") String contextId,
189
                           @DefaultValue("0") @QueryParam("offset") int offset,
190
                           @DefaultValue("20") @QueryParam("limit") int limit,
191
                           @DefaultValue("") @QueryParam("keyword") String keyword,
192
                           @DefaultValue("") @QueryParam("sortby") String orderby,
193
                           @DefaultValue("true") @QueryParam("descending") boolean descending,
194
                           @DefaultValue("") @QueryParam("types") String types,
195
                                     @HeaderParam("X-XSRF-TOKEN") String token,
196
                                     @CookieParam("AccessToken") String  cookie,
197
                                     @Context HttpServletRequest request) {
198
        logger.debug("header \"X-XSRF-TOKEN\" has value " + token);
199
        logger.debug("cookie  \"AccessToken\" has value  " + cookie);
200

  
201
        if(token == null || token.isEmpty() || cookie == null || cookie.isEmpty() || !cookie.equals(token)){
202
            return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. Maybe you are not registered."))
203
                    .type(MediaType.APPLICATION_JSON)
204
                    .build();
205
        }
206
        logger.debug("Calling API for context with token " + token);
207

  
208
        if(authorization.isAdmin(token)) {
209

  
210
            int total = -1;
211
            if (contextId == null || contextId.isEmpty()) {
212
                return Response.status(Response.Status.BAD_REQUEST).entity(compose400Message("Context id cannot be empty."))
213
                        .type(MediaType.APPLICATION_JSON).build();
214
            }
215

  
216
            List<Claim> claims = null;
217
            List<String> listTypes = new ArrayList<String>();
218
            String[] types_array = types.split(",");
219
            for (int i = 0; i < types_array.length; i++) {
220
                if (types_array[i].length() > 0) {
221
                    listTypes.add(types_array[i]);
222
                }
223
            }
224
            try {
225
                claims = fetchClaimHandler.fetchClaimsByContext(contextId, limit, offset, keyword, orderby, descending, listTypes,false);
226
                total = fetchClaimHandler.countClaimsByContext(contextId, keyword, listTypes);
227

  
228
            } catch (SQLStoreException|Exception e) {
229
                logger.error("Could not fetch claims for context with id " + contextId, e);
230
                return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500Message("Fail to fetch claims" +
231
                        " for context with id " + contextId + ".", e)).type(MediaType.APPLICATION_JSON).build();
232
            }
233

  
234
            return Response.status(200).entity(composeDataResponse(request, claims, total, offset, limit)).build();
235
        }
236

  
237
        return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access"))
238
                .type(MediaType.APPLICATION_JSON)
239
                .build();
240
    }
241

  
242

  
243
    @GET
244
    @Path("/results/{resultId}/claims")
245
    @Produces(MediaType.APPLICATION_JSON)
246
    public Response getResultClaims(@PathParam("resultId") String resultId,
247
                                    @DefaultValue("0") @QueryParam("offset") int offset,
248
                                    @DefaultValue("20") @QueryParam("limit") int limit,
249
                                    @DefaultValue("") @QueryParam("keyword") String keyword,
250
                                    @DefaultValue("") @QueryParam("sortby") String orderby,
251
                                    @DefaultValue("true") @QueryParam("descending") boolean descending,
252
                                    @DefaultValue("") @QueryParam("types") String types,
253
                                    @HeaderParam("X-XSRF-TOKEN") String token,
254
                                    @CookieParam("AccessToken") String  cookie,
255
                                    @Context HttpServletRequest request) {
256
        logger.debug("header \"X-XSRF-TOKEN\" has value " + token);
257
        logger.debug("cookie  \"AccessToken\" has value  " + cookie);
258

  
259
        if(token == null || token.isEmpty() || cookie == null || cookie.isEmpty() || !cookie.equals(token)){
260
            return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. Maybe you are not registered."))
261
                    .type(MediaType.APPLICATION_JSON)
262
                    .build();
263
        }
264

  
265
        if(authorization.isAdmin(token)) {
266

  
267
            int total = -1;
268
            if (resultId == null || resultId.isEmpty()) {
269
                return Response.status(Response.Status.BAD_REQUEST).entity(compose400Message("Context id cannot be empty."))
270
                        .type(MediaType.APPLICATION_JSON).build();
271
            }
272

  
273
            List<Claim> claims = null;
274
            List<String> listTypes = new ArrayList<String>();
275
            String[] types_array = types.split(",");
276
            for (int i = 0; i < types_array.length; i++) {
277
                if (types_array[i].length() > 0) {
278
                    listTypes.add(types_array[i]);
279
                }
280
            }
281

  
282
            try {
283
                claims = fetchClaimHandler.fetchClaimsByResult(resultId, limit, offset, keyword, orderby, descending, listTypes,false);
284
                total = fetchClaimHandler.countClaimsByResult(resultId, keyword, listTypes);
285

  
286
            } catch (SQLStoreException|Exception e) {
287
                logger.error("Could not fetch claims for result with id " + resultId, e);
288
                return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500Message("Fail to fetch claims" +
289
                        " for result with id " + resultId + ".", e)).type(MediaType.APPLICATION_JSON).build();
290
            }
291

  
292
            return Response.status(200).entity(composeDataResponse(request, claims, total, offset, limit)).build();
293
        }
294

  
295
        return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access"))
296
                .type(MediaType.APPLICATION_JSON)
297
                .build();
298
    }
299

  
300

  
301
    @GET
302
    @Path("/users/claims")
303
    @Produces(MediaType.APPLICATION_JSON)
304
    public Response getUserClaims(@DefaultValue("0") @QueryParam("offset") int offset,
305
                                  @DefaultValue("20") @QueryParam("limit") int limit,
306
                                  @DefaultValue("") @QueryParam("keyword") String keyword,
307
                                  @DefaultValue("") @QueryParam("sortby") String orderby,
308
                                  @DefaultValue("true") @QueryParam("descending") boolean descending,
309
                                  @DefaultValue("") @QueryParam("types") String types,
310
                                  @HeaderParam("X-XSRF-TOKEN") String token,
311
                                  @CookieParam("AccessToken") String  cookie,
312
                                  @Context HttpServletRequest request) {
313
        logger.debug("header \"X-XSRF-TOKEN\" has value " + token);
314
        logger.debug("cookie  \"AccessToken\" has value  " + cookie);
315

  
316
        if(token == null || token.isEmpty() || cookie == null || cookie.isEmpty() || !cookie.equals(token)){
317
            return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. Maybe you are not registered."))
318
                    .type(MediaType.APPLICATION_JSON)
319
                    .build();
320
        }
321

  
322
        UserInfo userInfo = authorization.getUserHandler().getUserInfo(token);
323
        if(authorization.isRegistered(userInfo)) {
324
            String userMail = userInfo.getEmail();
325
            logger.debug("User is registerd "  );
326
            int total = -1;
327
            EmailValidator emailValidator = EmailValidator.getInstance();
328

  
329
            if (userMail == null || userMail.isEmpty()) {
330
                return Response.status(Response.Status.BAD_REQUEST).entity(compose400Message("User e-mail cannot be empty."))
331
                        .type(MediaType.APPLICATION_JSON).build();
332
            }
333

  
334
            if (!emailValidator.isValid(userMail)) {
335
                return Response.status(Response.Status.BAD_REQUEST).entity(compose400Message("User e-mail is not valid."))
336
                        .type(MediaType.APPLICATION_JSON).build();
337
            }
338

  
339
            List<Claim> claims = null;
340
            List<String> listTypes = new ArrayList<String>();
341
            String[] types_array = types.split(",");
342
            for (int i = 0; i < types_array.length; i++) {
343
                if (types_array[i].length() > 0) {
344
                    listTypes.add(types_array[i]);
345
                }
346
            }
347
            try {
348
                logger.debug("About to fetch claims"  );
349
                claims = fetchClaimHandler.fetchClaimsByUser(userMail, limit, offset, keyword, orderby, descending, listTypes,false);
350
                total = fetchClaimHandler.countClaimsByUser(userMail, keyword, listTypes);
351

  
352
            } catch (SQLStoreException|Exception e) {
353
                logger.error("Could not fetch claims for result with id " + userMail, e);
354
                return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500Message("Fail to fetch claims" +
355
                        " for user with e-mail " + userMail + ".", e)).type(MediaType.APPLICATION_JSON).build();
356
            }
357

  
358
            return Response.status(200).entity(composeDataResponse(request, claims, total, offset, limit)).build();
359
        }
360
        logger.debug("User is *NOT* registerd "  );
361
        return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. You are not registered."))
362
                .type(MediaType.APPLICATION_JSON)
363
                .build();
364
    }
365

  
366
    @GET
367
    @Path("/claims/{claimId}")
368
    @Produces(MediaType.APPLICATION_JSON)
369
    public Response getClaimsById(@PathParam("claimId") String claimId,
370
                                  @DefaultValue("0") @QueryParam("offset") int offset,
371
                                  @DefaultValue("20") @QueryParam("limit") int limit,
372
                                  @HeaderParam("X-XSRF-TOKEN") String token,
373
                                  @CookieParam("AccessToken") String  cookie,
374
                                  @Context HttpServletRequest request) {
375
        logger.debug("header \"X-XSRF-TOKEN\" has value " + token);
376
        logger.debug("cookie  \"AccessToken\" has value  " + cookie);
377

  
378
        if(token == null || token.isEmpty() || cookie == null || cookie.isEmpty() || !cookie.equals(token)){
379
            return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. Maybe you are not registered."))
380
                    .type(MediaType.APPLICATION_JSON)
381
                    .build();
382
        }
383

  
384
        if(authorization.isRegistered(token)) {
385

  
386
            List<Claim> claims = null;
387

  
388
            int total = -1;
389
            if (claimId == null || claimId.isEmpty()) {
390
                try {
391
                    claims = fetchClaimHandler.fetchAllClaims(limit, offset,false);
392
                    total = fetchClaimHandler.countAllClaims("", new ArrayList<String>());
393

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

  
396
                } catch (SQLStoreException|Exception e) {
397
                    logger.error("Could not fetch claims.", e);
398
                    return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500Message("Fail to fetch claims.", e))
399
                            .type(MediaType.APPLICATION_JSON).build();
400
                }
401
            }
402

  
403
            try {
404
                Claim claim = fetchClaimHandler.fetchClaimById(claimId,false);
405
                if (claim == null) {
406
                    return Response.status(Response.Status.NOT_FOUND).entity(compose404Message("Cannot find claim with id " + claimId + "."))
407
                            .type(MediaType.APPLICATION_JSON).build();
408
                }
409

  
410
                return Response.status(200).entity(composeDataResponse(claim)).build();
411

  
412
            } catch (SQLStoreException|Exception e) {
413
                return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500Message("Fail to fetch claim " +
414
                        "with id " + claimId + " id.", e)).type(MediaType.APPLICATION_JSON).build();
415
            }
416
        }
417
        return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. You are not registered."))
418
                .type(MediaType.APPLICATION_JSON)
419
                .build();
420
    }
421

  
422
    @GET
423
    @Path("/claims")
424
    @Produces(MediaType.APPLICATION_JSON)
425
    public Response getAllClaims(@DefaultValue("0") @QueryParam("offset") int offset,
426
                                  @DefaultValue("20") @QueryParam("limit") int limit,
427
                                  @DefaultValue("") @QueryParam("keyword") String keyword,
428
                                  @DefaultValue("date") @QueryParam("sortby") String orderby,
429
                                  @DefaultValue("true") @QueryParam("descending") boolean descending,
430
                                  @DefaultValue("") @QueryParam("types") String types,
431
                                 @HeaderParam("X-XSRF-TOKEN") String token,
432
                                 @HeaderParam("Origin") String origin,
433
                                 @CookieParam("AccessToken") String  cookie,
434
                                  @Context HttpServletRequest request) {
435

  
436
        logger.debug("header \"X-XSRF-TOKEN\" has value " + token);
437
        logger.debug("cookie  \"AccessToken\" has value  " + cookie);
438
        logger.debug("Header  \"Origin\" has value  " + origin);
439
   
440

  
441

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

  
445
            return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. Maybe you are not registered."))
446
                    .type(MediaType.APPLICATION_JSON)
447
                    .build();
448
        }
449

  
450
        if(authorization.isAdmin(token)) {
451
            logger.debug("User is authorized ! !");
452
            List<Claim> claims = null;
453
            List<String> listTypes = new ArrayList<String>();
454
            String[] types_array = types.split(",");
455
            for (int i = 0; i < types_array.length; i++) {
456
                if (types_array[i].length() > 0) {
457
                    listTypes.add(types_array[i]);
458
                }
459
            }
460
            logger.debug("Types: " + listTypes.toString());
461

  
462
            int total = -1;
463
            try {
464
                claims = fetchClaimHandler.fetchAllClaims(limit, offset, keyword, orderby, descending, listTypes,false);
465
                total = fetchClaimHandler.countAllClaims(keyword, listTypes);
466

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

  
469
            } catch (SQLStoreException|Exception e) {
470
                logger.error("Could not fetch claims.", e);
471
                return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500Message("Fail to fetch claims.", e))
472
                        .type(MediaType.APPLICATION_JSON).build();
473
            }
474
        }
475

  
476
        return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access"))
477
               .type(MediaType.APPLICATION_JSON)
478
               .build();
479
    }
480

  
481
    //ARGIRO TODO: Na thn tsekarw
482
//    @POST
483
//    @Path("/claims/{claimId}")
484
//    @Produces(MediaType.APPLICATION_JSON)
485
//    public Response deleteClaim(@PathParam("claimId") String claimId,
486
//                                @QueryParam("token") String token) {
487
//
488
//        if(!JWTValidator.isValid(token)) {
489
//            return Response.status(Response.Status.UNAUTHORIZED).entity(compose404Message("Not valid Token"))
490
//                    .type(MediaType.APPLICATION_JSON)
491
//                    .build();
492
//        }
493
//        try {
494
//
495
//            if (authorization.isRegistered(token) && (authorization.getUserHandler().getMail(token).equals(fetchClaimHandler.fetchClaimById(claimId).getUserMail()))) {
496
//                if (claimId == null || claimId.isEmpty()) {
497
//                    return Response.status(Response.Status.NOT_FOUND).entity(compose404Message("Claim id cannot be empty."))
498
//                            .type(MediaType.APPLICATION_JSON).build();
499
//                }
500
//
501
//                try {
502
//                    if (claimHandler.deleteClaim(claimId)) {
503
//                        return Response.status(204).entity(compose204Message()).type(MediaType.APPLICATION_JSON).build();
504
//                    }
505
//
506
//                } catch (Exception e) {
507
//                    logger.error("Fail to delete claim with id " + claimId + ".", e);
508
//                    return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500Message("Fail to delete claim with id " + claimId + ".", e))
509
//                            .type(MediaType.APPLICATION_JSON).build();
510
//                }
511
//
512
//                return Response.status(Response.Status.NOT_FOUND).entity(compose404Message("Claim id cannot be empty."))
513
//                        .type(MediaType.APPLICATION_JSON).build();
514
//            }
515
//
516
//            return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. Maybe you are not registered."))
517
//                    .type(MediaType.APPLICATION_JSON)
518
//                    .build();
519
//
520
//        } catch (Exception e) {
521
//            logger.error("Could not fetch claims.", e);
522
//            return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500Message("Fail to fetch claims.", e))
523
//                    .type(MediaType.APPLICATION_JSON).build();
524
//        }
525
//    }
526
/*
527

  
528
    @DELETE
529
    @Path("/claims/{claimId}")
530
    public Response deleteClaim(@PathParam("claimId") String claimId) {
531

  
532
        if (claimId == null || claimId.isEmpty()) {
533
            return Response.status(Response.Status.NOT_FOUND).entity(compose404Message("Claim id cannot be empty.")).header("Access-Control-Allow-Origin", "*")
534
                    .header("Access-Control-Allow-Methods", "DELETE")
535
                    .type(MediaType.APPLICATION_JSON).build();
536
        }
537

  
538
        try {
539
            if(claimHandler.deleteClaim(claimId)) {
540
                return Response.status(204).entity(compose204Message()).header("Access-Control-Allow-Origin", "*")
541
                        .header("Access-Control-Allow-Methods", "DELETE").type(MediaType.APPLICATION_JSON).build();
542
            }
543

  
544
        } catch (Exception e) {return Response.status(Response.Status.UNAUTHORIZED).entity(compose404Message("Not valid Token"))
545
                    .type(MediaType.APPLICATION_JSON)
546
                    .build();
547
            logger.error("Fail to delete claim with id " + claimId + ".", e);
548
            return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500Message("Fail to delete claim with id " + claimId +".", e))
549
                    .header("Access-Control-Allow-Origin", "*")
550
                    .header("Access-Control-Allow-Methods", "DELETE")
551
                    .type(MediaType.APPLICATION_JSON).build();
552
        }
553

  
554
        return Response.status(Response.Status.NOT_FOUND).entity(compose404Message("Claim id cannot be empty.")).header("Access-Control-Allow-Origin", "*")
555
                .header("Access-Control-Allow-Methods", "DELETE")
556
                .type(MediaType.APPLICATION_JSON).build();
557
    }
558
 */
559
    @DELETE
560
    @Path("/claims/bulk")
561
    @Produces(MediaType.APPLICATION_JSON)
562
    public Response deleteBulkClaims(@QueryParam("claimId") List<String> claimIds,
563
                                     @HeaderParam("X-XSRF-TOKEN") String token,
564
                                     @HeaderParam("Origin") String origin,
565
                                     @CookieParam("AccessToken") String  cookie){
566

  
567
        logger.debug("header \"X-XSRF-TOKEN\" has value " + token);
568
        logger.debug("cookie  \"AccessToken\" has value  " + cookie);
569

  
570
         if(token == null || token.isEmpty() || cookie == null || cookie.isEmpty() || !cookie.equals(token)|| !authorization.hasValidOrigin(origin)){
571
             return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. Maybe you are not registered."))
572
                     .type(MediaType.APPLICATION_JSON)
573
                     .build();
574
         }
575

  
576

  
577
        ArrayList<String> deletedIds= new ArrayList<String>();
578
        ArrayList<String> notFoundIds= new ArrayList<String>();
579

  
580
        if (claimIds == null || claimIds.size() == 0) {
581
            return Response.status(Response.Status.NOT_FOUND).entity(compose404BulkDeleteMessage("Claim ids cannot be empty.",deletedIds,notFoundIds))
582
                    .type(MediaType.APPLICATION_JSON).build();
583
        }
584

  
585
        logger.debug("Trying to delete claims with ids: " + claimIds.toString() + ".");
586

  
587
        for (String claimId : claimIds) {
588
            try {
589

  
590
                if (authorization.isRegistered(token)) {
591
                    if (authorization.isAdmin(token) || authorization.getUserHandler().getMail(token).equals(fetchClaimHandler.fetchClaimById(claimId,false).getUserMail())) {
592
                        if (claimHandler.deleteClaim(claimId)) {
593
                            deletedIds.add(claimId);
594
                        } else {
595
                            notFoundIds.add(claimId);
596
                        }
597
                    } else {
598
                        return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to delete."))
599
                                .type(MediaType.APPLICATION_JSON)
600
                                .build();
601
                    }
602
                } else {
603
                    return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. Maybe you are not registered."))
604
                            .type(MediaType.APPLICATION_JSON)
605
                            .build();
606
                }
607
            } catch (SQLStoreException|Exception e) {
608
                logger.error("Fail to delete claim with id " + claimId + ".", e);
609
                notFoundIds.add(claimId);
610
            }
611
        }
612
        logger.debug("Successfully deleted " + deletedIds.size() + " from " + claimIds.size()  +". Deleted claims with ids: " + deletedIds.toString() + ".");
613
        if (claimIds.size() == notFoundIds.size()) {
614
            return Response.status(Response.Status.NOT_FOUND).entity(compose404BulkDeleteMessage("Claim ids cannot be empty.",deletedIds,notFoundIds))
615
                    .type(MediaType.APPLICATION_JSON).build();
616
        } else if (claimIds.size() == notFoundIds.size()) {
617
            return Response.status(204).entity(compose204BulkDeleteMessage(deletedIds,notFoundIds)).type(MediaType.APPLICATION_JSON).build();
618
        } else {
619
            return Response.status(204).entity(compose204BulkDeleteMessage(deletedIds,notFoundIds)).type(MediaType.APPLICATION_JSON).build();
620
        }
621
    }
622

  
623
    @POST
624
    @Path("/claims")
625
    @Produces(MediaType.APPLICATION_JSON)
626
    @Consumes(MediaType.APPLICATION_JSON)
627
    public Response addClaim(String input, @Context HttpServletRequest request,
628
                             @HeaderParam("X-XSRF-TOKEN") String token,
629
                             @HeaderParam("Origin") String origin,
630
                             @CookieParam("AccessToken") String  cookie) {
631
        logger.debug("header \"X-XSRF-TOKEN\" has value " + token);
632
        logger.debug("cookie  \"AccessToken\" has value  " + cookie);
633

  
634
        if(token == null || token.isEmpty() || cookie == null || cookie.isEmpty() || !cookie.equals(token) || !authorization.hasValidOrigin(origin)){
635
            return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. Maybe you are not registered."))
636
                    .type(MediaType.APPLICATION_JSON)
637
                    .build();
638
        }
639

  
640
        UserInfo userInfo = authorization.getUserHandler().getUserInfo(token);
641
        if(authorization.isRegistered(userInfo)) {
642
            JsonObject jsonObject = new JsonParser().parse(input).getAsJsonObject();
643

  
644
            String claimedBy = userInfo.getEmail();
645
            logger.info("claimedBy " + claimedBy);
646

  
647
            String sourceId = jsonObject.get("sourceId").getAsString();
648
            logger.info("sourceId " + sourceId);
649
            String sourceType = jsonObject.get("sourceType").getAsString();
650
            logger.info("sourceType " + sourceType);
651
            String sourceCollectedFrom = jsonObject.get("sourceCollectedFrom").getAsString();
652
            logger.info("sourceCollectedFrom " + sourceCollectedFrom);
653
            String sourceAccessRights = jsonObject.get("sourceAccessRights").getAsString();
654
            logger.info("sourceAccessRights " + sourceAccessRights);
655
            String sourceEmbargoEndDate = jsonObject.get("sourceEmbargoEndDate").getAsString();
656
            sourceEmbargoEndDate = (sourceEmbargoEndDate != null && sourceEmbargoEndDate.equals("")) ? null : sourceEmbargoEndDate;
657
            logger.info("sourceEmbargoEndDate " + sourceEmbargoEndDate);
658

  
659
            String targetId = jsonObject.get("targetId").getAsString();
660
            logger.info("targetId " + targetId);
661
            String targetType = jsonObject.get("targetType").getAsString();
662
            logger.info("targetType " + targetType);
663
            String targetCollectedFrom = jsonObject.get("targetCollectedFrom").getAsString();
664
            logger.info("targetCollectedFrom " + targetCollectedFrom);
665
            String targetAccessRights = jsonObject.get("targetAccessRights").getAsString();
666
            logger.info("targetAccessRights " + targetAccessRights);
667
            String targetEmbargoEndDate = jsonObject.get("targetEmbargoEndDate").getAsString();
668
            targetEmbargoEndDate = (targetEmbargoEndDate != null && targetEmbargoEndDate.equals("")) ? null : targetEmbargoEndDate;
669
            logger.info("targetEmbargoEndDate " + targetEmbargoEndDate);
670

  
671
            EmailValidator emailValidator = EmailValidator.getInstance();
672
            if (!emailValidator.isValid(claimedBy)) {
673
                return Response.status(Response.Status.BAD_REQUEST).entity(compose400Message("User e-mail is invalid."))
674
                        .type(MediaType.APPLICATION_JSON).build();
675
            }
676

  
677

  
678
            try {
679
                String claimId = claimHandler.buildAndInsertClaim(claimedBy, sourceType, sourceId, sourceCollectedFrom, sourceAccessRights, sourceEmbargoEndDate, targetType, targetId, targetCollectedFrom, targetAccessRights, targetEmbargoEndDate);
680
                return Response.status(200).entity(compose201PostMessage(request, claimId)).type(MediaType.APPLICATION_JSON).build();
681

  
682
            } catch (ClaimValidationException ve) {
683
                return Response.status(Response.Status.BAD_REQUEST).entity(compose400Message("The given ids are wrong.", ve))
684
                        .type(MediaType.APPLICATION_JSON).build();
685

  
686
            } catch (SQLStoreException|Exception e) {
687
                logger.error("Fail to add new claim.", e);
688
                return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500Message("Fail to add new claim.", e))
689
                        .type(MediaType.APPLICATION_JSON).build();
690
            }
691
        }
692
        return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access."))
693
                .type(MediaType.APPLICATION_JSON)
694
                .build();
695
    }
696

  
697
    @POST
698
    @Path("/claims/bulk")
699
    @Produces(MediaType.APPLICATION_JSON)
700
    @Consumes(MediaType.APPLICATION_JSON)
701
    public Response addBulkClaims(String input, @Context HttpServletRequest request,
702
                                  @HeaderParam("X-XSRF-TOKEN") String token,
703
                                  @HeaderParam("Origin") String origin,
704
                                  @CookieParam("AccessToken") String  cookie) {
705
        logger.debug("header \"X-XSRF-TOKEN\" has value " + token);
706
        logger.debug("cookie  \"AccessToken\" has value  " + cookie);
707

  
708
        if(token == null || token.isEmpty() || cookie == null || cookie.isEmpty() || !cookie.equals(token)|| !authorization.hasValidOrigin(origin)){
709
            return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. Maybe you are not registered."))
710
                    .type(MediaType.APPLICATION_JSON)
711
                    .build();
712
        }
713

  
714
        UserInfo userInfo = authorization.getUserHandler().getUserInfo(token);
715
        if(authorization.isRegistered(userInfo)) {
716
            ArrayList<String> insertedIds = new ArrayList<String>();
717
            JsonArray errorInClaims = new JsonArray();
718

  
719
            int code200 = 0;
720
            int code400 = 0;
721
            int code500 = 0;
722

  
723
            JsonArray jsonArray = new JsonParser().parse(input).getAsJsonArray();
724
            for (JsonElement je : jsonArray) {
725
                JsonObject jsonObject = je.getAsJsonObject();
726

  
727
                logger.info("targetId " + jsonObject.toString());
728
                String claimedBy = userInfo.getEmail();
729
                logger.info("claimedBy " + claimedBy);
730

  
731
                String sourceId = jsonObject.get("sourceId").getAsString();
732
                logger.info("sourceId " + sourceId);
733
                String sourceType = jsonObject.get("sourceType").getAsString();
734
                logger.info("sourceType " + sourceType);
735
                String sourceCollectedFrom = jsonObject.get("sourceCollectedFrom").getAsString();
736
                logger.info("sourceCollectedFrom " + sourceCollectedFrom);
737
                String sourceAccessRights = jsonObject.get("sourceAccessRights").getAsString();
738
                logger.info("sourceAccessRights " + sourceAccessRights);
739
                String sourceEmbargoEndDate = jsonObject.get("sourceEmbargoEndDate").getAsString();
740
                sourceEmbargoEndDate = (sourceEmbargoEndDate != null && sourceEmbargoEndDate.equals("")) ? null : sourceEmbargoEndDate;
741
                logger.info("sourceEmbargoEndDate " + sourceEmbargoEndDate);
742

  
743
                String targetId = jsonObject.get("targetId").getAsString();
744
                logger.info("targetId " + targetId);
745
                String targetType = jsonObject.get("targetType").getAsString();
746
                logger.info("targetType " + targetType);
747
                String targetCollectedFrom = jsonObject.get("targetCollectedFrom").getAsString();
748
                logger.info("targetCollectedFrom " + targetCollectedFrom);
749
                String targetAccessRights = jsonObject.get("targetAccessRights").getAsString();
750
                logger.info("targetAccessRights " + targetAccessRights);
751
                String targetEmbargoEndDate = jsonObject.get("targetEmbargoEndDate").getAsString();
752
                targetEmbargoEndDate = (targetEmbargoEndDate != null && targetEmbargoEndDate.equals("")) ? null : targetEmbargoEndDate;
753
                logger.info("targetEmbargoEndDate " + targetEmbargoEndDate);
754

  
755
                EmailValidator emailValidator = EmailValidator.getInstance();
756
                if (!emailValidator.isValid(claimedBy)) {
757
                    jsonObject.addProperty("error", "user");
758
                    //                return Response.status(Response.Status.BAD_REQUEST).entity(compose400Message("User e-mail is invalid."))
759
                    //                        .type(MediaType.APPLICATION_JSON).build();
760
                    code400++;
761
                    errorInClaims.add(jsonObject);
762
                }
763

  
764

  
765
                try {
766
                    String claimId = claimHandler.buildAndInsertClaim(claimedBy, sourceType, sourceId, sourceCollectedFrom, sourceAccessRights, sourceEmbargoEndDate, targetType, targetId, targetCollectedFrom, targetAccessRights, targetEmbargoEndDate);
767
                    insertedIds.add(claimId);
768
                    code200++;
769
                    //                return Response.status(200).entity(compose201PostMessage(request, claimId)).type(MediaType.APPLICATION_JSON).build();
770

  
771
                } catch (ClaimValidationException ve) {
772
                    //                return Response.status(Response.Status.BAD_REQUEST).entity(compose400Message("The given ids are wrong.", ve))
773
                    //                        .type(MediaType.APPLICATION_JSON).build();
774
                    jsonObject.addProperty("error", "validation");
775
                    errorInClaims.add(jsonObject);
776
                    code400++;
777

  
778
                } catch (SQLStoreException|Exception e) {
779
                    //                logger.error("Fail to add new claim.", e);
780
                    //                return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500Message("Fail to add new claim.", e))
781
                    //                        .type(MediaType.APPLICATION_JSON).build();
782
                    jsonObject.addProperty("error", "insertion");
783
                    errorInClaims.add(jsonObject);
784
                    code500++;
785
                }
786
            }
787
            if (jsonArray.size() == code500) {
788
                return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500BulkInsertMessage("Fail to add new claim.", insertedIds, errorInClaims))
789
                        .type(MediaType.APPLICATION_JSON).build();
790
            } else if (code200 > 0) {
791
                return Response.status(200).entity(compose201BulkInsertMessage(insertedIds, errorInClaims)).type(MediaType.APPLICATION_JSON).build();
792
            } else {
793
                return Response.status(Response.Status.BAD_REQUEST).entity(compose400BulkInsertMessage("The given ids are wrong.", insertedIds, errorInClaims))
794
                        .type(MediaType.APPLICATION_JSON).build();
795
            }
796
        }
797
        return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. You are not registered."))
798
                .type(MediaType.APPLICATION_JSON)
799
                .build();
800

  
801
    }
802
    @POST
803
    @Path("/curate/bulk")
804
    @Produces(MediaType.APPLICATION_JSON)
805
    @Consumes(MediaType.APPLICATION_JSON)
806
    public Response curateBulkClaims(String input, @Context HttpServletRequest request,
807
                                     @HeaderParam("X-XSRF-TOKEN") String token,
808
                                     @HeaderParam("Origin") String origin,
809
                                     @CookieParam("AccessToken") String  cookie) {
810
        logger.debug("header \"X-XSRF-TOKEN\" has value " + token);
811
        logger.debug("cookie  \"AccessToken\" has value  " + cookie);
812

  
813
        if(token == null || token.isEmpty() || cookie == null || cookie.isEmpty() || !cookie.equals(token)|| !authorization.hasValidOrigin(origin)){
814
            return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. Maybe you are not registered."))
815
                    .type(MediaType.APPLICATION_JSON)
816
                    .build();
817
        }
818

  
819
        if (authorization.isRegistered(token)) {
820
            ArrayList<String> insertedIds = new ArrayList<String>();
821
            JsonArray errorInClaims = new JsonArray();
822
            int code200 = 0;
823
            int code400 = 0;
824
            int code500 = 0;
825
            JsonArray jsonArray = new JsonParser().parse(input).getAsJsonArray();
826
            String curatedBy = authorization.getUserHandler().getMail(token);
827

  
828
            for (JsonElement je : jsonArray) {
829
                JsonObject jsonObject = je.getAsJsonObject();
830

  
831
                 String id = jsonObject.get("id").getAsString();
832
                logger.info("id " + id);
833

  
834
                Boolean approved = jsonObject.get("approved").getAsBoolean();
835
                logger.info("approved " + approved);
836
                EmailValidator emailValidator = EmailValidator.getInstance();
837
                if (!emailValidator.isValid(curatedBy)) {
838
                    jsonObject.addProperty("error", "user");
839
                    //                return Response.status(Response.Status.BAD_REQUEST).entity(compose400Message("User e-mail is invalid."))
840
                    //                        .type(MediaType.APPLICATION_JSON).build();
841
                    code400++;
842
                    errorInClaims.add(jsonObject);
843
                }
844

  
845
                try {
846
                    claimHandler.updateClaimCurationInfo(curatedBy,id, approved);
847
                    insertedIds.add(id);
848
                    code200++;
849

  
850
                } catch (SQLStoreException|Exception e) {
851
                    jsonObject.addProperty("error", "insertion");
852
                    errorInClaims.add(jsonObject);
853
                    code500++;
854
                }
855
            }
856
            if (jsonArray.size() == code500) {
857
                return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500BulkInsertMessage("Fail to update claims.", insertedIds, errorInClaims))
858
                        .type(MediaType.APPLICATION_JSON).build();
859
            } else if (code200 > 0) {
860
                return Response.status(200).entity(compose201BulkInsertMessage(insertedIds, errorInClaims)).type(MediaType.APPLICATION_JSON).build();
861
            } else {
862
                return Response.status(Response.Status.BAD_REQUEST).entity(compose400BulkInsertMessage("The given ids are wrong.", insertedIds, errorInClaims))
863
                        .type(MediaType.APPLICATION_JSON).build();
864
            }
865
        }
866
        return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. You are not registered."))
867
                .type(MediaType.APPLICATION_JSON)
868
                .build();
869

  
870
    }
871
    @POST
872
    @Path("/feed/bulk")
873
    @Produces(MediaType.APPLICATION_JSON)
874
    @Consumes(MediaType.APPLICATION_JSON)
875
    public Response feedBulkRecords(String input, @Context HttpServletRequest request,
876
                                    @HeaderParam("X-XSRF-TOKEN") String token,
877
                                    @HeaderParam("Origin") String origin,
878
                                    @CookieParam("AccessToken") String  cookie) {
879
        logger.debug("header \"X-XSRF-TOKEN\" has value " + token);
880
        logger.debug("cookie  \"AccessToken\" has value  " + cookie);
881

  
882
        if(token == null || token.isEmpty() || cookie == null || cookie.isEmpty() || !cookie.equals(token)|| !authorization.hasValidOrigin(origin)){
883
            return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. Maybe you are not registered."))
884
                    .type(MediaType.APPLICATION_JSON)
885
                    .build();
886
        }
887

  
888
        if (authorization.isRegistered(token)) {
889
            ArrayList<String> insertedIds = new ArrayList<String>();
890
            JsonArray errorInClaims = new JsonArray();
891
            int code200 = 0;
892
            int code400 = 0;
893
            int code500 = 0;
894
            JsonArray jsonArray = new JsonParser().parse(input).getAsJsonArray();
895
            for (JsonElement je : jsonArray) {
896
                JsonObject jsonObject = je.getAsJsonObject();
897
                Boolean inserted = directIndexHandler.insertRecord(new Gson().toJson(jsonObject.get("record")));
898
                if (inserted) {
899
                    insertedIds.add(jsonObject.get("id").getAsString());
900
                    code200++;
901
                } else {
902
                    errorInClaims.add(jsonObject.get("id").getAsString());
903
                    code400++;
904
                }
905

  
906

  
907
            }
908
            if (jsonArray.size() == code500) {
909
                return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500BulkInsertMessage("Fail to add new claim.", insertedIds, errorInClaims))
910
                        .type(MediaType.APPLICATION_JSON).build();
911
            } else if (code200 > 0) {
912
                return Response.status(200).entity(compose201BulkInsertMessage(insertedIds, errorInClaims)).type(MediaType.APPLICATION_JSON).build();
913
            } else {
914
                return Response.status(Response.Status.BAD_REQUEST).entity(compose400BulkInsertMessage("The given ids are wrong.", insertedIds, errorInClaims))
915
                        .type(MediaType.APPLICATION_JSON).build();
916
            }
917
        }
918
        return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. You are not registered."))
919
                .type(MediaType.APPLICATION_JSON)
920
                .build();
921

  
922
    }
923

  
924
    @Path("/communities")
925
    @GET
926
    @Produces(MediaType.APPLICATION_JSON)
927
    public Response fetchCommunities(@HeaderParam("X-XSRF-TOKEN") String token,
928
                                     @CookieParam("AccessToken") String  cookie) throws ISLookUpServiceException {
929
        logger.debug("header \"X-XSRF-TOKEN\" has value " + token);
930
        logger.debug("cookie  \"AccessToken\" has value  " + cookie);
931

  
932
        if(token == null || token.isEmpty() || cookie == null || cookie.isEmpty() || !cookie.equals(token)){
933
            return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. Maybe you are not registered."))
934
                    .type(MediaType.APPLICATION_JSON)
935
                    .build();
936
        }
937

  
938
        if (authorization.isRegistered(token)) {
939
            //it needs to have at lease one category with @claim=true
940
            List<String> communities = lookupServiceLocator.getService().quickSearchProfile
941
                    ("for $x in collection('/db/DRIVER/ContextDSResources/ContextDSResourceType')  \n" +
942
                            "                where $x//context[@type='community']//category[@claim='true'] \n" +
943
                            "            return <communities>{$x//context/@id}{$x//context/@label}</communities>");
944

  
945
            return Response.status(200).entity(composeDataResponse(xml2Json(communities))).type(MediaType.APPLICATION_JSON).build();
946
        }
947
        return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. You are not registered."))
948
                .type(MediaType.APPLICATION_JSON)
949
                .build();
950
    }
951

  
952
    @Path("/communities/{communityid}/categories")
953
    @GET
954
    @Produces(MediaType.APPLICATION_JSON)
955
    public Response fetchCommunityCategories(@PathParam("communityid") String communityid,
956
                                             @HeaderParam("X-XSRF-TOKEN") String token,
957
                                             @CookieParam("AccessToken") String  cookie) throws ISLookUpServiceException {
958
        logger.debug("header \"X-XSRF-TOKEN\" has value " + token);
959
        logger.debug("cookie  \"AccessToken\" has value  " + cookie);
960

  
961
        if(token == null || token.isEmpty() || cookie == null || cookie.isEmpty() || !cookie.equals(token)){
962
            return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. Maybe you are not registered."))
963
                    .type(MediaType.APPLICATION_JSON)
964
                    .build();
965
        }
966

  
967
        if (authorization.isRegistered(token)) {
968
            List<String> categories = lookupServiceLocator.getService().quickSearchProfile
969
                    ("for $x in collection('/db/DRIVER/ContextDSResources/ContextDSResourceType')//context[@id='" + communityid + "']//category[@claim=\'true\']\n" +
970
                            "return <category>{$x/@id}{$x/@label}</category>");
971

  
972
            logger.info("for $x in collection('/db/DRIVER/ContextDSResources/ContextDSResourceType')//context[@id='" + communityid + "']//category[@claim=\'true\']\n" +
973
                    "return <category>{$x/@id}{$x/@label}</category>");
974

  
975
            if (categories == null || categories.isEmpty()) {
976
                return Response.status(404).entity(compose404Message("There are no categories for community with id " + communityid)).type(MediaType.APPLICATION_JSON).build();
977
            }
978

  
979
            xml2Json(categories);
980

  
981
            return Response.status(200).entity(composeDataResponse(xml2Json(categories))).type(MediaType.APPLICATION_JSON).build();
982
        }
983
        return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. You are not registered."))
984
                .type(MediaType.APPLICATION_JSON)
985
                .build();
986
    }
987

  
988
    @Path("/categories/{categoryid}/concepts")
989
    @GET
990
    @Produces(MediaType.APPLICATION_JSON)
991
    public Response fetchCategoryConcepts(@PathParam("categoryid") String categoryid,
992
                                          @HeaderParam("X-XSRF-TOKEN") String token,
993
                                          @CookieParam("AccessToken") String  cookie) throws ISLookUpServiceException {
994
        logger.debug("header \"X-XSRF-TOKEN\" has value " + token);
995
        logger.debug("cookie  \"AccessToken\" has value  " + cookie);
996

  
997
        if(token == null || token.isEmpty() || cookie == null || cookie.isEmpty() || !cookie.equals(token)){
998
            return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. Maybe you are not registered."))
999
                    .type(MediaType.APPLICATION_JSON)
1000
                    .build();
1001
        }
1002

  
1003
        if (authorization.isRegistered(token)) {
1004
            List<String> concepts = lookupServiceLocator.getService().quickSearchProfile
1005
                    ("for $x in collection('/db/DRIVER/ContextDSResources/ContextDSResourceType') return $x//category[@id='" + categoryid + "']//concept");
1006

  
1007
            if (concepts == null || concepts.isEmpty()) {
1008
                return Response.status(404).entity(compose404Message("There are no concepts for category with id " + categoryid)).type(MediaType.APPLICATION_JSON).build();
1009
            }
1010

  
1011
            return Response.status(200).entity(composeDataResponse(xml2Json(concepts))).type(MediaType.APPLICATION_JSON).build();
1012
        }
1013
        return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. You are not registered."))
1014
                .type(MediaType.APPLICATION_JSON)
1015
                .build();
1016
    }
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff