--- /dev/null
+/*****************************************************************************
+ * Copyright Igor Barma, Eric Brun, Alexandre Desoubeaux, Christian Martel,
+ * (2 décembre 2008)
+ *
+ * Ce logiciel est un programme informatique servant à l'évaluation des
+ * compétences.
+ *
+ * Ce logiciel est régi par la licence CeCILL soumise au droit français et
+ * respectant les principes de diffusion des logiciels libres. Vous pouvez
+ * utiliser, modifier et/ou redistribuer ce programme sous les conditions
+ * de la licence CeCILL telle que diffusée par le CEA, le CNRS et l'INRIA
+ * sur le site "http://www.cecill.info".
+ *
+ * En contrepartie de l'accessibilité au code source et des droits de copie,
+ * de modification et de redistribution accordés par cette licence, il n'est
+ * offert aux utilisateurs qu'une garantie limitée. Pour les mêmes raisons,
+ * seule une responsabilité restreinte pèse sur l'auteur du programme, le
+ * titulaire des droits patrimoniaux et les concédants successifs.
+ *
+ * A cet égard l'attention de l'utilisateur est attirée sur les risques
+ * associés au chargement, à l'utilisation, à la modification et/ou au
+ * développement et à la reproduction du logiciel par l'utilisateur étant
+ * donné sa spécificité de logiciel libre, qui peut le rendre complexe à
+ * manipuler et qui le réserve donc à des développeurs et des professionnels
+ * avertis possédant des connaissances informatiques approfondies. Les
+ * utilisateurs sont donc invités à charger et tester l'adéquation du
+ * logiciel à leurs besoins dans des conditions permettant d'assurer la
+ * sécurité de leurs systèmes et ou de leurs données et, plus généralement,
+ * à l'utiliser et l'exploiter dans les mêmes conditions de sécurité.
+ *
+ * Le fait que vous puissiez accéder à cet en-tête signifie que vous avez
+ * pris connaissance de la licence CeCILL, et que vous en avez accepté les
+ * termes.
+ *******************************************************************************/
+package com.pentila.evalcomp.manager;
+
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
+import java.util.Calendar;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+
+import javax.mail.Message;
+import javax.mail.internet.InternetAddress;
+import javax.mail.internet.MimeMessage;
+
+import org.springframework.mail.javamail.JavaMailSender;
+import org.springframework.mail.javamail.MimeMessagePreparator;
+
+import com.pentila.evalcomp.dao.IEntityDAO;
+import com.pentila.evalcomp.dao.INotificationDAO;
+import com.pentila.evalcomp.domain.Notification;
+import com.pentila.evalcomp.domain.Preference;
+import com.pentila.evalcomp.domain.SystemPreference;
+import com.pentila.evalcomp.domain.User;
+import com.pentila.evalcomp.manager.interfacedef.ISystemPreferenceBase;
+import com.pentila.evalcomp.utilities.WorkflowInterceptor;
+
+/**
+ * The Class UnifiedNotificationManager.
+ */
+public class UnifiedNotificationManager implements
+com.pentila.evalcomp.manager.interfacedef.IUnifiedNotificationManager {
+
+ /** The logger. */
+ org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(UnifiedNotificationManager.class);
+
+
+ /** The Constant MESSAGE_TYPE. */
+ public static final Integer MESSAGE_TYPE = 0;
+
+ /** The Constant EVENT_TYPE. */
+ public static final Integer EVENT_TYPE = 1;
+
+ /** The Constant TASK_TYPE. */
+ public static final Integer TASK_TYPE = 2;
+
+ /** The max date minute. */
+ private Integer maxDateMinute;
+
+ /** The entity dao. */
+ private IEntityDAO entityDAO;
+
+ /** The system preference manager. */
+ private ISystemPreferenceBase systemPreferenceManager;
+
+ /** The notification dao. */
+ private INotificationDAO notificationDAO;
+
+ /** The mail sender. */
+ private JavaMailSender mailSender;
+
+ /* (non-Javadoc)
+ * @see com.pentila.evalcomp.manager.interfacedef.IUnifiedNotificationManager#eventSended(java.lang.Long, java.lang.String, java.lang.String)
+ */
+ public void eventSended(Long userId, String subject, String text) {
+
+ User u = entityDAO.getUser(userId);
+
+ Notification n = new Notification();
+ n.setType(EVENT_TYPE);
+ n.setRecipient(u);
+ n.setSubject(subject);
+ n.setText(text);
+
+ boolean ok = computeUserDest(n);
+ if (ok) {
+
+ computeDueDate(n, EVENT_TYPE);
+
+ if (n.getDueDate() != null) {
+
+ notificationDAO.saveOrUpdate(n);
+ }
+ }
+ }
+
+ /* (non-Javadoc)
+ * @see com.pentila.evalcomp.manager.interfacedef.IUnifiedNotificationManager#messageSended(java.lang.Long, java.lang.String, java.lang.String)
+ */
+ public void messageSended(Long userId, String subject, String text) {
+
+ User u = entityDAO.getUser(userId);
+
+ // Session session =
+ // SessionFactoryUtils.getSession(((HibernateTransactionManager)Beans.getApplicationContext().getBean("transactionManager")).getSessionFactory(),
+ // false);
+ // session.lock(userId, LockMode.NONE);
+ Notification n = new Notification();
+ n.setType(MESSAGE_TYPE);
+ n.setRecipient(u);
+ n.setSubject(subject);
+ n.setText(text);
+
+ boolean ok = computeUserDest(n);
+ if (ok) {
+ computeDueDate(n, MESSAGE_TYPE);
+ if (n.getDueDate() != null) {
+
+ notificationDAO.saveOrUpdate(n);
+ }
+ }
+ }
+
+ /* (non-Javadoc)
+ * @see com.pentila.evalcomp.manager.interfacedef.IUnifiedNotificationManager#taskSended(java.lang.String, java.lang.String, java.lang.String)
+ */
+ public void taskSended(String uid, String subject, String text) {
+
+ User u = entityDAO.getUser(uid);
+
+ Notification n = new Notification();
+ n.setType(TASK_TYPE);
+ n.setRecipient(u);
+ n.setSubject(subject);
+ n.setText(text);
+
+ boolean ok = computeUserDest(n);
+
+ if (ok) {
+
+ computeDueDate(n, TASK_TYPE);
+ if (n.getDueDate() != null) {
+
+ notificationDAO.saveOrUpdate(n);
+ }
+ }
+ }
+
+ /**
+ * Compute due date.
+ *
+ * @param n the n
+ * @param type the type
+ */
+ private void computeDueDate(Notification n, Integer type) {
+
+ User u = n.getRecipient();
+
+ Calendar cal = Calendar.getInstance();
+ Date now = new Date();
+ n.setCreationDate(now);
+
+ cal.setTime(now);
+
+ String preferenceName = "";
+
+ switch (type) {
+ case 0:
+ // Message
+ preferenceName = "messages";
+ break;
+ case 1:
+ preferenceName = "alertes";
+ break;
+ case 2:
+ preferenceName = "taches";
+ break;
+ }
+
+ Date dueDate = null;
+
+ Preference p = u.getPreferenceByName(preferenceName);
+
+ if (p != null) {
+ String[] arr = p.getValue().split(";");
+
+ // Instant
+ if (arr[0].equals("1")) {
+ cal.add(Calendar.MINUTE, 15);
+ cal.set(Calendar.SECOND, 0);
+ dueDate = cal.getTime();
+ } else if (!arr[1].equals("-1") && arr[2].equals("0")
+ && arr[3].equals("-1")) {
+ // Hour of day
+
+ Integer hour = Integer.parseInt(arr[1]);
+ cal.set(Calendar.HOUR_OF_DAY, hour);
+ cal.set(Calendar.MINUTE, 0);
+ cal.set(Calendar.SECOND, 0);
+ // pour demain
+ if (cal.getTime().before(now)) {
+ cal.add(Calendar.DATE, 1);
+
+ }
+ dueDate = cal.getTime();
+
+ } else if (!arr[2].equals("0")) {
+ // Day of week
+ Integer dayOfWeek = Integer.parseInt(arr[2]);
+
+ Integer hour = 19;
+
+ if (!arr[1].equals("-1")) {
+ hour = Integer.parseInt(arr[1]);
+ }
+
+ cal.set(Calendar.HOUR_OF_DAY, hour);
+ cal.set(Calendar.MINUTE, 0);
+ cal.set(Calendar.SECOND, 0);
+
+ if (dayOfWeek == 7) {
+ dayOfWeek = 0;
+ }
+
+ // Matching with Calendar.MONDAY .... integer values.
+
+ dayOfWeek++;
+
+ cal.set(Calendar.DAY_OF_WEEK, dayOfWeek);
+
+ if (cal.getTime().before(now)) {
+ cal.add(Calendar.WEEK_OF_YEAR, 1);
+ }
+
+ dueDate = cal.getTime();
+
+ } else if (!arr[3].equals("-1")) {
+ // Day of Month
+
+ Integer dayOfMonth = Integer.parseInt(arr[3]);
+
+ Integer hour = 19;
+
+ if (!arr[1].equals("-1")) {
+ hour = Integer.parseInt(arr[1]);
+ }
+
+ cal.set(Calendar.HOUR_OF_DAY, hour);
+ cal.set(Calendar.MINUTE, 0);
+ cal.set(Calendar.SECOND, 0);
+
+ cal.set(Calendar.DAY_OF_MONTH, dayOfMonth);
+ if (cal.getTime().before(now)) {
+ cal.add(Calendar.WEEK_OF_YEAR, 4);
+ }
+ dueDate = cal.getTime();
+
+ }
+
+ }
+
+ n.setDueDate(dueDate);
+
+ }
+
+ /**
+ * Gets the notification dao.
+ *
+ * @return the notification dao
+ */
+ public INotificationDAO getNotificationDAO() {
+ return notificationDAO;
+ }
+
+ /**
+ * Sets the notification dao.
+ *
+ * @param notificationDAO the new notification dao
+ */
+ public void setNotificationDAO(INotificationDAO notificationDAO) {
+ this.notificationDAO = notificationDAO;
+ }
+
+ /**
+ * Compute user dest.
+ *
+ * @param n the n
+ * @return true, if successful
+ */
+ private boolean computeUserDest(Notification n) {
+
+ boolean asDest = false;
+
+ User u = n.getRecipient();
+
+ Preference pMail1 = u.getPreferenceByName("mail1");
+ if (pMail1 != null) {
+ n.setMail1(pMail1.getValue());
+ asDest = true;
+ }
+
+ Preference pUseMail2 = u.getPreferenceByName("usemail2");
+ if (pUseMail2 != null && !pUseMail2.equals("")) {
+
+ Preference pMail2 = u.getPreferenceByName("mail2");
+ if (pMail2 != null) {
+ n.setMail2(pMail2.getValue());
+ asDest = true;
+ }
+ }
+
+ Preference pPhone = u.getPreferenceByName("phone");
+ if (pPhone != null) {
+ n.setPhone(pPhone.getValue());
+ }
+
+ Date date = new Date();
+
+ n.setCreationDate(date);
+
+ return asDest;
+
+ }
+
+ /**
+ * Gets the entity dao.
+ *
+ * @return the entity dao
+ */
+ public IEntityDAO getEntityDAO() {
+ return entityDAO;
+ }
+
+ /**
+ * Sets the entity dao.
+ *
+ * @param entityDAO the new entity dao
+ */
+ public void setEntityDAO(IEntityDAO entityDAO) {
+ this.entityDAO = entityDAO;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * com.pentila.evalcomp.manager.interfacedef.IUnifiedNotificationManager
+ * #clean()
+ */
+ public void clean() {
+ notificationDAO.clean();
+ }
+
+ /* (non-Javadoc)
+ * @see com.pentila.evalcomp.manager.interfacedef.IUnifiedNotificationManager#performNotify()
+ */
+ public void performNotify() {
+
+
+ logger.debug("Entering performNotify ");
+
+ List<SystemPreference> lsp = systemPreferenceManager
+ .getPreferencesByType(SystemPreference.TYPE_MAIL);
+
+ Map<String, String> systemMap = new HashMap<String, String>();
+
+ for (SystemPreference sp : lsp) {
+ systemMap.put(sp.getName(), sp.getValue());
+ }
+
+ Date now = new Date();
+
+ Calendar cal = Calendar.getInstance();
+ cal.setTime(now);
+
+ cal.add(Calendar.MINUTE, maxDateMinute);
+
+ List<Notification> l = notificationDAO.getNotifications(now,
+ cal.getTime());
+
+ if (logger.isDebugEnabled()){
+ if (l != null){
+ logger.debug("Founded Notification for sending : " + l.size());
+ }else{
+ logger.debug("List of searched Notificatiion is null !!");
+ }
+ }
+
+ Map<String, Map<Integer, List<Notification>>> map = new HashMap<String, Map<Integer, List<Notification>>>();
+
+ for (Notification n : l) {
+
+ String mail1 = n.getMail1();
+ String mail2 = n.getMail2();
+
+ if (mail1 != null && !mail1.equals("")) {
+ if (!map.containsKey(mail1)) {
+ map.put(mail1, new HashMap<Integer, List<Notification>>());
+ }
+
+ if (!map.get(mail1).containsKey(n.getType())) {
+ List<Notification> tmp = new ArrayList<Notification>();
+
+ map.get(mail1).put(n.getType(), tmp);
+ }
+
+ map.get(mail1).get(n.getType()).add(n);
+
+ }
+
+ if (mail2 != null && !mail2.equals("") && !mail2.equals(mail1)) {
+ if (!map.containsKey(mail2)) {
+ map.put(mail2, new HashMap<Integer, List<Notification>>());
+ }
+
+ if (!map.get(mail2).containsKey(n.getType())) {
+ List<Notification> tmp = new ArrayList<Notification>();
+
+ map.get(mail2).put(n.getType(), tmp);
+ }
+
+ map.get(mail2).get(n.getType()).add(n);
+
+ }
+
+ }
+
+ for (Entry<String, Map<Integer, List<Notification>>> u : map.entrySet()) {
+ try {
+
+
+
+ sendMail(u.getKey(), u.getValue(), systemMap);
+ } catch (Exception e) {
+ // e.printStackTrace();
+ }
+ }
+
+ notificationDAO.deleteAll(l);
+ }
+
+ /**
+ * Send mail.
+ *
+ * @param email the email
+ * @param value the value
+ * @param systemMap the system map
+ */
+ private void sendMail(final String email,
+ Map<Integer, List<Notification>> value,
+ Map<String, String> systemMap) {
+
+ String emailS = "EMaEval@admin.fr";
+
+ String subjectS = "Notification programmée EMaEval";
+
+ String headS = "";
+ String footS = "";
+
+ if (systemMap.containsKey("email_system")) {
+ emailS = systemMap.get("email_system");
+ }
+
+ if (systemMap.containsKey("mail_subject")) {
+ subjectS = systemMap.get("mail_subject");
+ }
+
+ if (systemMap.containsKey("mail_header")) {
+ headS = systemMap.get("mail_header");
+ }
+
+ if (systemMap.containsKey("mail_footer")) {
+ footS = systemMap.get("mail_footer");
+ }
+
+ final String email_system = emailS;
+
+ final String subject = subjectS;
+
+ final String header = headS;
+ final String footer = footS;
+
+ String tbody = "";
+
+ SimpleDateFormat sdf = new SimpleDateFormat(
+ "'le' dd/MM/yyyy 'à' HH'h'mm");
+
+ for (Entry<Integer, List<Notification>> t : value.entrySet()) {
+
+ String title = "";
+
+ switch (t.getKey()) {
+ case 0:
+ title = " * Messages";
+ break;
+ case 1:
+ title = " * Alertes";
+ break;
+ case 2:
+ title = " * Tâches";
+ break;
+ }
+
+ List<Notification> l = t.getValue();
+
+ Collections.sort(l, new Comparator<Notification>() {
+ public int compare(Notification n1, Notification n2) {
+ return n1.getCreationDate().compareTo(n2.getCreationDate());
+ }
+ });
+
+ String msg = "";
+
+ for (Notification n : l) {
+ String tmpMsg = String.format(
+ " - %s (date d'envoi %s)\n %s\n",
+ n.getSubject(), sdf.format(n.getCreationDate()),
+ n.getText());
+ msg = msg + tmpMsg;
+ }
+
+ msg = title + "\n" + msg + "\n\n";
+
+ tbody = tbody + msg;
+ }
+
+ if (!header.equals("")) {
+ tbody = header + "\n\n" + tbody;
+ }
+ if (!footer.equals("")) {
+ tbody = tbody + "\n\n" + footer;
+ }
+ final String body = tbody;
+
+ MimeMessagePreparator preparator = new MimeMessagePreparator() {
+
+ public void prepare(MimeMessage mimeMessage) throws Exception {
+ mimeMessage.setRecipient(Message.RecipientType.TO,
+ new InternetAddress(email));
+ mimeMessage.setFrom(new InternetAddress(email_system));
+ mimeMessage.setSubject(subject);
+ mimeMessage.setText(body);
+ }
+
+ };
+
+ mailSender.send(preparator);
+
+ }
+
+ /**
+ * Gets the mail sender.
+ *
+ * @return the mail sender
+ */
+ public JavaMailSender getMailSender() {
+ return mailSender;
+ }
+
+ /**
+ * Sets the mail sender.
+ *
+ * @param mailSender the new mail sender
+ */
+ public void setMailSender(JavaMailSender mailSender) {
+ this.mailSender = mailSender;
+ }
+
+ /**
+ * Gets the max date minute.
+ *
+ * @return the max date minute
+ */
+ public Integer getMaxDateMinute() {
+ return maxDateMinute;
+ }
+
+ /**
+ * Sets the max date minute.
+ *
+ * @param maxDateMinute the new max date minute
+ */
+ public void setMaxDateMinute(Integer maxDateMinute) {
+ this.maxDateMinute = maxDateMinute;
+ }
+
+ /**
+ * Gets the system preference manager.
+ *
+ * @return the system preference manager
+ */
+ public ISystemPreferenceBase getSystemPreferenceManager() {
+ return systemPreferenceManager;
+ }
+
+ /**
+ * Sets the system preference manager.
+ *
+ * @param systemPreferenceManager the new system preference manager
+ */
+ public void setSystemPreferenceManager(
+ ISystemPreferenceBase systemPreferenceManager) {
+ this.systemPreferenceManager = systemPreferenceManager;
+ }
+}