Project

General

Profile

1
package eu.dnetlib.data.emailSender;
2

    
3
import eu.dnetlib.data.claims.migration.entity.Claim;
4
import eu.dnetlib.data.claims.migration.entity.Context;
5
import eu.dnetlib.data.claims.migration.entity.Notification;
6
import eu.dnetlib.data.claims.migration.entity.Project;
7
import eu.dnetlib.data.claims.migration.handler.*;
8
import eu.dnetlib.data.claimsDemo.ClaimUtils;
9
import eu.dnetlib.data.claimsDemo.CommunityUtils;
10
import eu.dnetlib.data.claimsDemo.SQLStoreException;
11
import org.apache.log4j.Logger;
12
import org.springframework.beans.factory.annotation.Autowired;
13

    
14
import javax.mail.*;
15
import javax.mail.internet.AddressException;
16
import javax.mail.internet.InternetAddress;
17
import javax.mail.internet.MimeMessage;
18
import java.text.SimpleDateFormat;
19
import java.util.*;
20

    
21
public class EmailSender implements Runnable {
22

    
23
    private static final Logger logger = Logger.getLogger(EmailSender.class);
24

    
25
    @Autowired
26
    private FetchClaimHandler fetchClaimHandler = null;
27
    @Autowired
28
    private FetchProjectHandler fetchProjectHandler = null;
29
    @Autowired
30
    private FetchNotificationHandler fetchNotificationHandler = null;
31
    @Autowired
32
    private NotificationHandler notificationHandler = null;
33
    @Autowired
34
    private FetchContextHandler fetchContextHandler = null;
35

    
36
    @Autowired
37
    private String defaultFrequencyInHours;
38

    
39
    private static String openaireClaimsPage;
40
    private static String username;
41
    private static String password;
42
    private static String host;
43
    private static String port;
44
    private static String from;
45
    private static String specialRecipients;
46

    
47
    @Override
48
    public void run() {
49
        logger.info("EmailSender thread is running. " + host);
50
        logger.info("Special Recipients  " + specialRecipients);
51

    
52
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
53
        Date date = new Date();
54
        String dateTo = (format.format(date));
55

    
56
        defaultEmails_For_ProjectClaims(dateTo, format);    // daily for managers not in notification table
57
        defaultEmails_For_CommunityClaims(dateTo, format);  // daily for managers not in notification table
58

    
59
        notificationEmails_For_ProjectClaims(dateTo, format);
60
        notificationEmails_For_CommunityClaims(dateTo, format);
61
    }
62

    
63
    public void defaultEmails_For_ProjectClaims(String dateTo, SimpleDateFormat format) {
64
        Map<String, List<String>> managersOfProject = new HashMap<String, List<String>>();
65
        Project project;
66
        List<Claim> claims = null;
67
        List<String> types = new ArrayList<String>();
68

    
69
        types.add(ClaimUtils.PROJECT);
70

    
71
        Calendar calendar = Calendar.getInstance();
72
        calendar.add(Calendar.HOUR_OF_DAY, -(Integer.parseInt(defaultFrequencyInHours)-1));
73
        calendar.add(Calendar.MINUTE, -59);
74
        calendar.add(Calendar.SECOND, -59);
75
        Date date = calendar.getTime();
76
        String dateFrom=(format.format(date));
77

    
78
        logger.debug("Sending emails for project claims between " + dateFrom + " and "+dateTo);
79

    
80
        try {
81
            // Get all claims between dateFrom and dateTo which satisfy source_type == "project" or target_type == "project"
82
            claims = fetchClaimHandler.fetchClaimsByDate(dateFrom, dateTo, null, null, "", "source", true, types, false);
83
        } catch (SQLStoreException|Exception e) {
84
            logger.error("Could not fetch claims by date from "+dateFrom+" to "+dateTo, e);
85
        }
86

    
87
        for (Claim claim: claims) {
88
            if (claim.getSourceType().equals("project")) {
89
                project = (Project)claim.getSource();
90
            } else {
91
                project = (Project)claim.getTarget();
92
            }
93

    
94
            if (!managersOfProject.containsKey(project.getOpenaireId())) {
95

    
96
                // specialRecipients are used currently for testing purposes
97
                List<String> tmpManagers = null;
98
                if (specialRecipients != null && !specialRecipients.isEmpty()) {
99
                    tmpManagers = Arrays.asList(specialRecipients.split("\\s*,\\s*"));
100
                    logger.debug("Special recipients: " + specialRecipients);
101
                    managersOfProject.put(project.getOpenaireId(), tmpManagers);
102
                }
103

    
104
                /*
105
                // Send emails to actual project managers instead of special recipients
106
                List<String> managers = null;
107
                try {
108
                    managers = fetchProjectHandler.fetchContactEmailsByProjectId(project.getOpenaireId());
109
                    if(managers != null) {
110
                        Iterator itr = managers.iterator();
111
                        while (itr.hasNext()) {
112
                            String manager = (String) itr.next();
113
                            Notification notification = fetchNotificationHandler.fetchNotification(project.getOpenaireId(), manager);
114
                            //if (notification != null && (!notification.isNotify() || notification.getFrequency() != 24)) {
115
                            if (notification != null) {
116
                                itr.remove();
117
                            }
118
                        }
119
                    }
120
                } catch (Exception e) {
121
                    e.printStackTrace();
122
                } catch (SQLStoreException e) {
123
                    e.printStackTrace();
124
                }
125

    
126
                logger.debug("Managers of project " + project.getOpenaireId() + ": "+managers);
127
                managersOfProject.put(project.getOpenaireId(), managers);
128
                */
129

    
130
                if (managersOfProject.get(project.getOpenaireId()) != null &&
131
                        !managersOfProject.get(project.getOpenaireId()).isEmpty()) {
132
                    //send(project.getOpenaireId(), project.getName(), "project", managersOfProject.get(project.getOpenaireId()));
133
                }
134
            }
135
        }
136
    }
137

    
138
    public void defaultEmails_For_CommunityClaims(String dateTo, SimpleDateFormat format) {
139
        Map<String, List<String>> managersOfCommunity = new HashMap<String, List<String>>();
140
        Context context;
141
        List<Claim> claims = null;
142
        List<String> types = new ArrayList<String>();
143

    
144
        types.add(ClaimUtils.CONTEXT);
145

    
146
        Calendar calendar = Calendar.getInstance();
147
        calendar.add(Calendar.HOUR_OF_DAY, -(Integer.parseInt(defaultFrequencyInHours)-1));
148
        calendar.add(Calendar.MINUTE, -59);
149
        calendar.add(Calendar.SECOND, -59);
150
        Date date = calendar.getTime();
151
        String dateFrom=(format.format(date));
152

    
153
        logger.debug("Sending emails for community claims between " + dateFrom + " and "+dateTo);
154

    
155
        try {
156
            // Get all claims between dateFrom and dateTo which satisfy source_type == "context" or target_type == "context"
157
            claims = fetchClaimHandler.fetchClaimsByDate(dateFrom, dateTo, null, null, "", "source", true, types, false);
158
        } catch (SQLStoreException|Exception e) {
159
            logger.error("Could not fetch claims by date from "+dateFrom+" to "+dateTo, e);
160
        }
161

    
162
        for (Claim claim: claims) {
163
            if (claim.getSourceType().equals("context")) {
164
                context = (Context)claim.getSource();
165
            } else {
166
                context = (Context)claim.getTarget();
167
            }
168

    
169
            String openaireId = context.getOpenaireId().split("::")[0];
170
            if (!managersOfCommunity.containsKey(openaireId)) {
171

    
172
                /*
173
                // specialRecipients are used currently for testing purposes
174
                List<String> tmpManagers = null;
175
                if (specialRecipients != null && !specialRecipients.isEmpty()) {
176
                    tmpManagers = Arrays.asList(specialRecipients.split("\\s*,\\s*"));
177
                    logger.debug("Special recipients: " + specialRecipients);
178
                    managersOfCommunity.put(openaireId, tmpManagers);
179
                }
180
                */
181

    
182

    
183
                // Send emails to actual project managers instead of special recipients
184
                List<String> managers = null;
185
                try {
186
                    CommunityUtils communityInfo = CommunityUtils.getCommunityInfo(openaireId);
187
                    managers = communityInfo.getManagers();
188
                    if(managers != null) {
189
                        Iterator itr = managers.iterator();
190
                        while (itr.hasNext()) {
191
                            String manager = (String) itr.next();
192
                            Notification notification = fetchNotificationHandler.fetchNotification(openaireId, manager);
193
                            if (notification != null) {
194
                                itr.remove();
195
                            } else {
196
                                logger.debug("Sending email to community manager: "+ manager);
197
                            }
198
                        }
199
                    }
200
                    else {
201
                        logger.debug("Community Managers: null");
202
                    }
203
                } catch (Exception e) {
204
                    e.printStackTrace();
205
                } catch (SQLStoreException e) {
206
                    e.printStackTrace();
207
                }
208

    
209
                logger.debug("Managers of community " + openaireId + ": "+managers);
210
                managersOfCommunity.put(openaireId, managers);
211

    
212

    
213
                if (managersOfCommunity.get(openaireId) != null &&
214
                        !managersOfCommunity.get(openaireId).isEmpty()) {
215
                    //send(openaireId, context.getTitle().split(">")[0], "community", managersOfCommunity.get(openaireId));
216
                }
217
            }
218
        }
219
    }
220

    
221
    public void notificationEmails_For_ProjectClaims(String dateTo, SimpleDateFormat format) {
222
        Project project = null;
223
        List<String> types = new ArrayList<String>();
224

    
225
        types.add(ClaimUtils.PROJECT);
226

    
227
        logger.debug("Sending email for project claims from notification table");
228

    
229
        try {
230
            List<Notification> trueNotifications = fetchNotificationHandler.fetchTrueNotifications();
231
            logger.debug(trueNotifications);
232
            if(trueNotifications != null) {
233
                for(Notification notification : trueNotifications) {
234
                    List<String> managers = fetchProjectHandler.fetchContactEmailsByProjectId(notification.getOpenaireId());
235
                    if(managers != null && managers.contains(notification.getUserMail())) {
236

    
237
                        Date _dateTo = format.parse(dateTo);
238

    
239
                        String last_interaction_date = (format.format(notification.getDate()));
240

    
241
                        long diff = _dateTo.getTime() - notification.getDate().getTime();
242
                        diff = diff / 1000;
243

    
244
                        if (diff >= (notification.getFrequency() * 3600)) {
245
                            if (fetchClaimHandler.fetchNumberOfClaimsByDateAndOpenaireId(last_interaction_date, dateTo, notification.getOpenaireId(), null, null, "", null, true, types, false) > 0) {
246
                                List<String> managersByNotification = new ArrayList<>();
247
                                managersByNotification.add(notification.getUserMail());
248

    
249
                                project = fetchProjectHandler.fetchProjectById(notification.getOpenaireId());
250

    
251
                                logger.debug("Sending email for project claims between " + last_interaction_date + " and " + dateTo + " to " + notification.getUserMail());
252

    
253
                                //send(project.getOpenaireId(), project.getName(), "project", managersByNotification);
254
                            }
255
                            Calendar cal = Calendar.getInstance();
256
                            cal.setTime(_dateTo);
257
                            cal.add(Calendar.SECOND, 1);
258
                            _dateTo = cal.getTime();
259
                            notificationHandler.updateNotificationLastInteractionDate(notification.getOpenaireId(), notification.getUserMail(), _dateTo);
260
                            //update last interaction date (db)
261
                        }
262
                    } else {
263
                        logger.debug("managers do not contain "+notification.getUserMail());
264
                    }
265
                }
266
            } else {
267
                logger.debug("true notifications: null");
268
            }
269
        } catch (Exception e) {
270
            e.printStackTrace();
271
        } catch (SQLStoreException e) {
272
            e.printStackTrace();
273
        }
274
    }
275

    
276
    public void notificationEmails_For_CommunityClaims(String dateTo, SimpleDateFormat format) {
277
        Context context = null;
278
        List<String> types = new ArrayList<String>();
279

    
280
        types.add(ClaimUtils.CONTEXT);
281

    
282
        logger.debug("Sending email for community claims from notification table");
283

    
284
        try {
285
            List<Notification> trueNotifications = fetchNotificationHandler.fetchTrueNotifications();
286

    
287
            if(trueNotifications != null) {
288
                for(Notification notification : trueNotifications) {
289
                    CommunityUtils communityInfo = CommunityUtils.getCommunityInfo(notification.getOpenaireId());
290
                    List<String> managers = null;
291
                    if(communityInfo != null) {
292
                        managers = communityInfo.getManagers();
293
                    }
294

    
295
                    if(managers != null && managers.contains(notification.getUserMail())) {
296
                        Date _dateTo = format.parse(dateTo);
297

    
298
                        String last_interaction_date = (format.format(notification.getDate()));
299
                        long diff = _dateTo.getTime() - notification.getDate().getTime();
300
                        diff = diff / 1000;
301
                        //if dateTo - last_interaction_date >= notification.getFrequency//last_interaction_date.compareTo(dateFrom) == -1 &&
302

    
303
                        if (diff >= (notification.getFrequency() * 3600)) {
304
                            if (fetchClaimHandler.fetchNumberOfClaimsByDateAndOpenaireId(last_interaction_date, dateTo, notification.getOpenaireId(), null, null, "", "source", true, types, false) > 0) {
305
                                List<String> managersByNotification = new ArrayList<>();
306
                                managersByNotification.add(notification.getUserMail());
307

    
308
                                // We need that to get name of community
309
                                context = fetchContextHandler.fetchFirstContextByCommunityId(notification.getOpenaireId());
310

    
311
                                logger.debug("Sending email for community claims between " + last_interaction_date + " and " + dateTo + " to " + notification.getUserMail());
312

    
313
                                //send(context.getOpenaireId().split("::")[0], context.getTitle().split(">")[0], "community", managersByNotification);
314
                            }
315
                            Calendar cal = Calendar.getInstance();
316
                            cal.setTime(_dateTo);
317
                            cal.add(Calendar.SECOND, 1);
318
                            _dateTo = cal.getTime();
319
                            notificationHandler.updateNotificationLastInteractionDate(notification.getOpenaireId(), notification.getUserMail(), _dateTo);
320
                            //update last interaction date (db)
321
                        }
322
                    }
323
                }
324
            }
325
        } catch (Exception e) {
326
            e.printStackTrace();
327
        } catch (SQLStoreException e) {
328
            e.printStackTrace();
329
        }
330
    }
331

    
332
    public void send(String openaire_id, String openaire_name, String type, /*String token,*/ List<String> managers) {
333
        final String openaireClaimsPageUrl = openaireClaimsPage + openaire_id;//token;
334

    
335
        // Get system properties
336
        Properties properties = System.getProperties();
337
        properties.setProperty("mail.smtp.host", host);
338
        properties.put("mail.smtp.port", port);
339
        properties.put("mail.smtp.auth", "true"); //enable authentication
340
        properties.put("mail.smtp.starttls.enable", "true");
341

    
342
        Session session = Session.getInstance(properties,
343
            new javax.mail.Authenticator() {
344
                protected PasswordAuthentication getPasswordAuthentication() {
345
                    return new PasswordAuthentication(username, password);
346
                }
347
            });
348

    
349
        try {
350
            // Create a default MimeMessage object.
351
            MimeMessage message = new MimeMessage(session);
352

    
353
            // Set From: header field of the header.
354
            message.setFrom(new InternetAddress(from));
355

    
356
            // Set To: header field of the header.
357
            for(String to : managers) {
358
                logger.debug(to);
359
                message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
360
            }
361

    
362
            // Set Subject: header field
363
            message.setSubject("Openaire Claims Notification");
364

    
365
            // For simple text setText() can be used instead of setContent()
366

    
367
            // Send the actual HTML message, as big as you like
368
            message.setContent("There are new Claims for the "+type+": '" + openaire_name +"' for which you seem to be a contact person." +
369
                                        "<br>Click <a href=\""+openaireClaimsPageUrl+"\">here</a> to curate these Claims.", "text/html");
370

    
371
            // Send message
372
            Transport.send(message);
373
            logger.debug("Sent message successfully....\n");
374

    
375
        } catch (AddressException ae) {
376
            logger.error("Email could not be send.", ae);
377

    
378
        } catch (MessagingException me) {
379
            logger.error("Email could not be send.", me);
380
        }
381
    }
382

    
383
    public void setFetchClaimHandler(FetchClaimHandler fetchClaimHandler) {
384
        this.fetchClaimHandler = fetchClaimHandler;
385
    }
386

    
387
    public void setFetchProjectHandler(FetchProjectHandler fetchProjectHandler) {
388
        this.fetchProjectHandler = fetchProjectHandler;
389
    }
390

    
391
    public void setFetchNotificationHandler(FetchNotificationHandler fetchNotificationHandler) {
392
        this.fetchNotificationHandler = fetchNotificationHandler;
393
    }
394

    
395
    public void setFetchContextHandler(FetchContextHandler fetchContextHandler) {
396
        this.fetchContextHandler = fetchContextHandler;
397
    }
398

    
399
    public static void setOpenaireClaimsPage(String openaireClaimsPage) {
400
        EmailSender.openaireClaimsPage = openaireClaimsPage;
401
    }
402

    
403
    public static void setUsername(String username) {
404
        EmailSender.username = username;
405
    }
406

    
407
    public static void setPassword(String password) {
408
        EmailSender.password = password;
409
    }
410

    
411
    public static void setHost(String host) {
412
        EmailSender.host = host;
413
    }
414

    
415
    public static void setPort(String port) {
416
        EmailSender.port = port;
417
    }
418

    
419
    public static void setFrom(String from) {
420
        EmailSender.from = from;
421
    }
422

    
423
    public static void setSpecialRecipients(String specialRecipients) {
424
        EmailSender.specialRecipients = specialRecipients;
425
    }
426
}
(2-2/2)