Project

General

Profile

« Previous | Next » 

Revision 53619

1. HelloWorldService.java:
a. replace method 'project/claims', with method 'projects/{projectId}/all_claims' (no token but projectId)
b. add method '/users/notification' to get user email preferences from 'notification' table
c. add method '/users/notification/save' to insert a new notification entry or update an existing in 'notification' table
d. add 'compose204Message(String message)' and 'composeDataResponse(List<Notification> notifications)' functions
2. pom.xml: Add dependency with groupId: eu.dnetlib - artifactId: uoa-claims - version: 2.0.1-SNAPSHOT

View differences:

HelloWorldService.java
5 5
import eu.dnetlib.api.enabling.ISLookUpServiceException;
6 6
import eu.dnetlib.data.claims.migration.ClaimValidationException;
7 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;
8
import eu.dnetlib.data.claims.migration.entity.Notification;
9
import eu.dnetlib.data.claims.migration.entity.Project;
10
import eu.dnetlib.data.claims.migration.handler.*;
11
import eu.dnetlib.data.claimsDemo.CommunityUtils;
12 12
import eu.dnetlib.data.claimsDemo.SQLStoreException;
13 13
import gr.uoa.di.driver.util.ServiceLocator;
14
import net.sf.ehcache.search.expression.Not;
14 15
import org.apache.commons.validator.EmailValidator;
15 16
import org.apache.log4j.Logger;
16 17
import org.json.XML;
......
24 25
import javax.ws.rs.core.MediaType;
25 26
import javax.ws.rs.core.Response;
26 27
import java.util.ArrayList;
28
import java.util.HashMap;
27 29
import java.util.List;
30
import java.util.Map;
28 31

  
29 32
/**
30 33
 * Created by kiatrop on 15/4/2016.
......
41 44
    @Autowired
42 45
    private FetchProjectHandler fetchProjectHandler= null;
43 46

  
47
    @Autowired
48
    private FetchNotificationHandler fetchNotificationHandler = null;
49

  
50
    @Autowired
51
    private NotificationHandler notificationHandler = null;
52

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

  
......
53 62
    @Autowired
54 63
    public Authorization authorization = null;
55 64

  
65
    @Autowired
66
    private String defaultFrequencyInHours;
56 67

  
57 68
    @GET
58 69
    @Path("projects/{projectId}/claims")
......
105 116
    }
106 117

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

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

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

  
143
        int total = -1;
144

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

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

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

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

  
179
        } catch (SQLStoreException|Exception e) {
180
            logger.error("Could not fetch claims for project with id " + projectId, e);
181
            return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500Message("Fail to fetch claims" +
182
                    " for projects with id " + projectId + ".", e)).type(MediaType.APPLICATION_JSON).build();
183
        }
184
    }
185
/*
186
    @GET
108 187
    @Path("project/claims")
109 188
    @Produces(MediaType.APPLICATION_JSON)
110 189
    public Response getProjectClaimsByToken(@QueryParam("projectToken") String projectToken,
......
173 252
//                .type(MediaType.APPLICATION_JSON)
174 253
//                .build();
175 254
    }
255
*/
256

  
176 257
    @GET
177 258
    @Path("/contexts/{contextId}/claims")
178 259
    @Produces(MediaType.APPLICATION_JSON)
......
967 1048
                .build();
968 1049
    }
969 1050

  
1051
    @GET
1052
    @Path("/users/notification")
1053
    @Produces(MediaType.APPLICATION_JSON)
1054
    public Response getUserEmailNotificationPreferences(@QueryParam("communityId") String openaireId,
1055
                                  @HeaderParam("X-XSRF-TOKEN") String token,
1056
                                  @CookieParam("AccessToken") String  cookie,
1057
                                  @Context HttpServletRequest request) {
1058
        
1059
        if(token == null || token.isEmpty() || cookie == null || cookie.isEmpty() || !cookie.equals(token)){
1060
            return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. Maybe you are not registered."))
1061
                    .type(MediaType.APPLICATION_JSON)
1062
                    .build();
1063
        }
1064

  
1065
        UserInfo userInfo = authorization.getUserHandler().getUserInfo(token);
1066
        if(authorization.isRegistered(userInfo)) {
1067
            String userMail = userInfo.getEmail();
1068
            logger.debug("User is registerd "  );
1069

  
1070
            EmailValidator emailValidator = EmailValidator.getInstance();
1071

  
1072
            if (userMail == null || userMail.isEmpty()) {
1073
                return Response.status(Response.Status.BAD_REQUEST).entity(compose400Message("User e-mail cannot be empty."))
1074
                        .type(MediaType.APPLICATION_JSON).build();
1075
            }
1076

  
1077
            if (!emailValidator.isValid(userMail)) {
1078
                return Response.status(Response.Status.BAD_REQUEST).entity(compose400Message("User e-mail is not valid."))
1079
                        .type(MediaType.APPLICATION_JSON).build();
1080
            }
1081

  
1082
            List<Notification> notifications = null;
1083
            try {
1084
                if(openaireId != null) {
1085
                    CommunityUtils communityInfo = CommunityUtils.getCommunityInfo(openaireId);
1086
                    if(communityInfo.getManagers().contains(userMail)) {
1087

  
1088
                        Notification notification = null;
1089
                        logger.debug("About to fetch notification");
1090
                        notification = fetchNotificationHandler.fetchNotification(openaireId, userMail);
1091

  
1092
                        if (notifications == null) {
1093
                            notifications = new ArrayList<Notification>();
1094
                        }
1095
                        if (notification == null) {
1096
                            notification = new Notification(openaireId, communityInfo.getName(), userMail, Integer.parseInt(defaultFrequencyInHours), true);
1097
                        } else {
1098
                            notification.setOpenaireName(communityInfo.getName());
1099
                        }
1100
                        notifications.add(notification);
1101
                    }
1102
                } else {
1103
                    Map<String, String> projectIdsAndNames = fetchProjectHandler.fetchProjectIdsAndNamesByProjectManagerMail(userMail);
1104
                    if(projectIdsAndNames != null) {
1105
                        for (Map.Entry<String, String> projectIdAndName : projectIdsAndNames.entrySet()) {
1106
                            Notification notification = null;
1107
                            logger.debug("About to fetch notification");
1108
                            notification = fetchNotificationHandler.fetchNotification(projectIdAndName.getKey(), userMail);
1109

  
1110
                            if (notifications == null) {
1111
                                notifications = new ArrayList<Notification>();
1112
                            }
1113
                            if(notification == null) {
1114
                                notification = new Notification(projectIdAndName.getKey(), projectIdAndName.getValue(), userMail, Integer.parseInt(defaultFrequencyInHours), true);
1115
                            } else {
1116
                                notification.setOpenaireName(projectIdAndName.getValue());
1117
                            }
1118
                            notifications.add(notification);
1119
                            logger.debug(notification);
1120
                            logger.debug("notification openaireId:"+notification.getOpenaireId());
1121
                            logger.debug(notifications.size());
1122
                        }
1123
                    }
1124
                }
1125

  
1126
            } catch (SQLStoreException|Exception e) {
1127
                logger.error("Could not fetch notification preferences for user with mail " + userMail, e);
1128
                return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500Message("Fail to fetch notification preferences" +
1129
                        " for user with e-mail " + userMail + ".", e)).type(MediaType.APPLICATION_JSON).build();
1130
            }
1131

  
1132
            if (notifications == null || notifications.isEmpty()) {
1133
                return Response.status(204).entity(compose204Message("There are no notifications for user with mail " + userMail)).type(MediaType.APPLICATION_JSON).build();
1134
            }
1135

  
1136
            return Response.status(200).entity(composeDataResponse(notifications)).build();
1137

  
1138
        }
1139
        logger.debug("User is *NOT* registerd "  );
1140
        return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. You are not registered."))
1141
                .type(MediaType.APPLICATION_JSON)
1142
                .build();
1143
    }
1144

  
1145
    @POST
1146
    @Path("/users/notification/save")
1147
    @Produces(MediaType.APPLICATION_JSON)
1148
    @Consumes(MediaType.APPLICATION_JSON)
1149
    public Response saveOrUpdateUserEmailNotificationPreferences(String input, @Context HttpServletRequest request,
1150
                                     @HeaderParam("X-XSRF-TOKEN") String token,
1151
                                     @HeaderParam("Origin") String origin,
1152
                                     @CookieParam("AccessToken") String  cookie) {
1153

  
1154

  
1155
        if(token == null || token.isEmpty() || cookie == null || cookie.isEmpty() || !cookie.equals(token)|| !authorization.hasValidOrigin(origin)){
1156
            return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. Maybe you are not registered."))
1157
                    .type(MediaType.APPLICATION_JSON)
1158
                    .build();
1159
        }
1160
        UserInfo userInfo = authorization.getUserHandler().getUserInfo(token);
1161
        if (authorization.isRegistered(userInfo)) {
1162
            ArrayList<String> insertedIds = new ArrayList<String>();
1163
            JsonArray errorInClaims = new JsonArray();
1164
            int code200 = 0;
1165
            int code400 = 0;
1166
            int code500 = 0;
1167
            JsonObject jsonObject = new JsonParser().parse(input).getAsJsonObject();
1168

  
1169
            String userMail =userInfo.getEmail();
1170

  
1171
            String openaireId = jsonObject.get("openaireId").getAsString();
1172
            logger.info("openaireId " + openaireId);
1173

  
1174
            boolean notify = jsonObject.get("notify").getAsBoolean();
1175
            logger.info("notify "+notify);
1176

  
1177
            int frequency = jsonObject.get("frequency").getAsInt();
1178
            logger.info("frequency " + frequency);
1179

  
1180
            EmailValidator emailValidator = EmailValidator.getInstance();
1181
            if (!emailValidator.isValid(userMail)) {
1182
                jsonObject.addProperty("error", "user");
1183
                                return Response.status(Response.Status.BAD_REQUEST).entity(compose400Message("User e-mail is invalid."))
1184
                                        .type(MediaType.APPLICATION_JSON).build();
1185
            }
1186

  
1187
            try {
1188
                boolean continueProcedure = false;
1189
                List<String> managers = null;
1190
                try {
1191
                    managers = fetchProjectHandler.fetchContactEmailsByProjectId(openaireId);
1192
                } catch (Exception e) {
1193
                    e.printStackTrace();
1194
                } catch (SQLStoreException e) {
1195
                    e.printStackTrace();
1196
                }
1197
                if(managers != null && managers.contains(userMail)) {
1198
                    continueProcedure = true;
1199
                } else {
1200
                    CommunityUtils communityInfo = CommunityUtils.getCommunityInfo(openaireId);
1201
                    if(communityInfo.getManagers().contains(userMail)) {
1202
                        continueProcedure = true;
1203
                    }
1204
                }
1205

  
1206
                if(continueProcedure) {
1207
                    Notification notification = null;
1208
                    logger.debug("About to fetch notification");
1209
                    notification = fetchNotificationHandler.fetchNotification(openaireId, userMail);
1210

  
1211
                    if (notification == null) {
1212
                        logger.debug("About to insert notification");
1213
                        notificationHandler.buildAndInsertNotification(openaireId, userMail, frequency, notify);
1214
                    } else {
1215
                        logger.debug("About to update notification");
1216
                        notificationHandler.updateNotificationPreferences(openaireId, userMail, frequency, notify);
1217
                    }
1218
                } else {
1219
                    Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. You are not registered."))
1220
                            .type(MediaType.APPLICATION_JSON)
1221
                            .build();
1222
                }
1223
            } catch (SQLStoreException|Exception e) {
1224
                logger.error("Could not save or update notification preferences for user with mail " + userMail, e);
1225
                return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500Message("Fail to fetch notification preferences" +
1226
                        " for user with e-mail " + userMail + ".", e)).type(MediaType.APPLICATION_JSON).build();
1227
            }
1228

  
1229
            return Response.status(200).entity(compose204Message("Save or Update for notification successful")).type(MediaType.APPLICATION_JSON).build();
1230
        }
1231
        return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. You are not registered."))
1232
                .type(MediaType.APPLICATION_JSON)
1233
                .build();
1234
    }
1235

  
970 1236
    private String xml2Json(List<String> input) {
971 1237
        StringBuilder builder = new StringBuilder();
972 1238
        for(String category: input) {
......
975 1241
        return builder.toString();
976 1242
    }
977 1243

  
1244
    private String compose204Message(String message) {
1245
        return  "{ \"status\" : \"error\", \"code\" : \"204\", \"message\" : \"  " + message +" \" }";
1246
    }
1247

  
978 1248
    private String compose400Message(String message) {
979 1249
        return  "{ \"status\" : \"error\", \"code\" : \"400\", \"message\" : \"  " + message +" \" }";
980 1250
    }
......
1063 1333
        return " { \"status\" : \"success\", \"code\": \"200\", " + "\"data\" : " + new Gson().toJson(claim) + " }";
1064 1334
    }
1065 1335

  
1336
    private String composeDataResponse(List<Notification> notifications) {
1337
        return " { \"status\" : \"success\", \"code\": \"200\", " + "\"data\" : " + new Gson().toJson(notifications) + " }";
1338
    }
1339

  
1066 1340
    private static String composePaging(HttpServletRequest request, int total, int currentOffset, int limit) {
1067 1341
        logger.info("total " + total);
1068 1342
        logger.info("currentOffset " + currentOffset);

Also available in: Unified diff