Advertisement
vangop

Untitled

Mar 2nd, 2012
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 16.19 KB | None | 0 0
  1. /*
  2.  * This software is produced by EDB B&F. Unauthorized redistribution,
  3.  * reproduction or usage of this software in whole or in part without
  4.  * the express written consent of EDB B&F is strictly prohibited.
  5.  * Copyright © 2011 EDB.  ALL RIGHTS RESERVED
  6.  */
  7.  
  8. package com.edb.esign.service.notification;
  9.  
  10. import java.util.*;
  11.  
  12. import org.apache.axis2.databinding.types.xsd.DateTime;
  13. import org.apache.commons.codec.binary.Base64;
  14. import org.hibernate.LockMode;
  15. import org.hibernate.exception.LockAcquisitionException;
  16. import org.slf4j.Logger;
  17. import org.slf4j.LoggerFactory;
  18. import org.springframework.transaction.annotation.Propagation;
  19. import org.springframework.transaction.annotation.Transactional;
  20.  
  21. import com.edb.esign.ConfigProperties;
  22. import com.edb.esign.EsignException;
  23. import com.edb.esign.dao.NotificationDao;
  24. import com.edb.esign.domain.*;
  25. import com.edb.esign.providers.ISignatureProvider;
  26. import com.edb.esign.vo.NotificationTemplateParams;
  27.  
  28. /**
  29.  * @author Volodymyr Kulishov
  30.  *
  31.  */
  32. public class NotificationProcessorService {
  33.     private final static Logger logger = LoggerFactory.getLogger(NotificationProcessorService.class);
  34.  
  35.     private NotificationDao notificationDao;
  36.     private Map<String, NotificationSenderService> notificators = new HashMap<String, NotificationSenderService>();
  37.     private Map<String, ISignatureProvider> providers = new HashMap<String, ISignatureProvider>();
  38.  
  39.     private Calendar calendar = Calendar.getInstance();
  40.  
  41.     public void setCalendar(Calendar calendar) {
  42.         this.calendar = calendar;
  43.     }
  44.  
  45.     public void setNotificationDao(NotificationDao notificationDao) {
  46.         this.notificationDao = notificationDao;
  47.     }
  48.  
  49.     public void setNotificators(Map<String, NotificationSenderService> notificators) {
  50.         this.notificators = notificators;
  51.     }
  52.  
  53.     public void setProviders(Map<String, ISignatureProvider> providers) {
  54.         this.providers = providers;
  55.     }
  56.  
  57.     /**
  58.      * This method makes necessary checks and makes decision about uploading
  59.      * offline document to signing provider and actual sms/email sending
  60.      *
  61.      * @param logContext
  62.      * @param record
  63.      * @throws ManualTransacationRollbackException
  64.      */
  65.     @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class, readOnly = true)
  66.     public void processNotification(Long signOrderHibId, Long stepHibId) throws EsignException {
  67.  
  68.         // obtain NO WAIT lock on SignOrder as ROOT entity
  69.         SignOrder signOrder = null;
  70.         try {
  71.             signOrder = (SignOrder) notificationDao.load(SignOrderImpl.class, signOrderHibId, LockMode.UPGRADE_NOWAIT);
  72.         } catch (LockAcquisitionException e) {
  73.             logger.warn("Unable to obtain UPGRADE_NOWAIT lock for SignOrder HibId:{}. Skipping notification sending for Step HibId: {}", signOrderHibId,
  74.                     stepHibId);
  75.             throw new EsignException(EsignException.INTERNAL_PROBLEM);
  76.         }
  77.  
  78.         // reload Step
  79.         Step currentStep = (Step) notificationDao.load(StepImpl.class, stepHibId);
  80.         Participant participant = (Participant) notificationDao.load(ParticipantImpl.class, currentStep.getParticipant().getId());
  81.         Issuer issuer = (Issuer) notificationDao.load(IssuerImpl.class, signOrder.getIssuer().getId());
  82.  
  83.         // check if there correct notification element exist for this record
  84.         Notification correctNotification = null;
  85.         try {
  86.             correctNotification = notificationDao.getCorrectNotification(currentStep);
  87.         } catch (EsignException e1) {
  88.             logger.error("Error getting correct notification for Step HibId: {} and Participant HibId: {}", currentStep.getId(), participant.getId());
  89.             throw e1;
  90.         } catch (Exception e2) {
  91.             logger.error("Error getting correct notification for Step HibId: {} and Participant HibId: {}", currentStep.getId(), participant.getId());
  92.             logger.error("error:", e2);
  93.             throw new EsignException(EsignException.INTERNAL_PROBLEM);
  94.         }
  95.         if (correctNotification == null) {
  96.             logger.info("There is no correct notification for stepHibId:{} and participantHibId:{} ", currentStep.getId(), participant.getId());
  97.             throw new EsignException(EsignException.INTERNAL_PROBLEM);
  98.         }
  99.  
  100.         if (isNotificationAllowedAtCurrentTime(correctNotification, issuer.getName(), calendar)) {
  101.  
  102.             // check if there were notifications before
  103.             if (currentStep.getNotificationExpireDate() != null) {
  104.                 // check if last notification already timed out
  105.                 Calendar currentDate = Calendar.getInstance();
  106.                 if (currentStep.getNotificationExpireDate().after(currentDate.getTime())) {
  107.                     // do not send notifications for records with expire date in future
  108.                     throw new EsignException(EsignException.INTERNAL_PROBLEM);
  109.                 }
  110.             }
  111.  
  112.             // get required notification template
  113.             // if template element is null then try to use messageText element
  114.             Template template = null;
  115.             String gssDirectURL = null;
  116.             if (correctNotification.getTemplate() == null || correctNotification.getTemplate().length() == 0) {
  117.                 if (correctNotification.getMessageText() != null && correctNotification.getMessageText().length() > 0) {
  118.                     if (correctNotification.getType().equals(NotificationMethod.EMAIL)) {
  119.                         EMailTemplate emailTemplate = new EMailTemplateImpl();
  120.                         emailTemplate.setMailSubject(ConfigProperties.getValue(ConfigProperties.GSS_EMAIL_SUBJECT_KEY, issuer.getName()));
  121.                         emailTemplate.setMailSenderAddress(ConfigProperties.getValue(ConfigProperties.GSS_EMAIL_SENDER_ADDRESS_KEY, issuer.getName()));
  122.                         emailTemplate.setMailReplyToAddress(ConfigProperties.getValue(ConfigProperties.GSS_EMAIL_REPLY_TO_KEY, issuer.getName()));
  123.                         emailTemplate.setValue(correctNotification.getMessageText());
  124.                         template = emailTemplate;
  125.                     } else { // if (correctNotification.getType().equals(NotificationMethod.SMS))
  126.                         SMSTemplate smsTemplate = new SMSTemplateImpl();
  127.                         smsTemplate.setValue(correctNotification.getMessageText());
  128.                         template = smsTemplate;
  129.                     }
  130.                     // initialize gssRedirectURL, this URL points to gss DIRECT signing page
  131.                     String stepDocUID = null;
  132.                     for (StepDocument stDoc : currentStep.getStepDocuments()) {
  133.                         if (StepDocumentSignedStatus.UNSIGNED.equals(stDoc.getSignedStatus())) {
  134.                             stepDocUID = stDoc.getStepDocumentUID();
  135.                         }
  136.                     }
  137.                     StringBuilder configUrl = new StringBuilder();
  138.                     configUrl.append(ConfigProperties.getValue(ConfigProperties.GSS_DIRECT_SIGNING_URL));
  139.                     configUrl.append("?");
  140.                     configUrl.append(ConfigProperties.TASK_ID_PARAM);
  141.                     configUrl.append("=");
  142.                     configUrl.append(stepDocUID);
  143.                     gssDirectURL = configUrl.toString();
  144.  
  145.                 } else {
  146.                     logger.error("Error in notification element HibId: {}. The template and messageText attributes are EMPTY.", correctNotification.getId());
  147.                     throw new EsignException(EsignException.INTERNAL_PROBLEM);
  148.                 }
  149.             } else {
  150.                 // retrieve template from TEMPLATE table
  151.                 try {
  152.                     template = notificationDao.getTemplateObjectForId(correctNotification.getTemplate());
  153.                 } catch (EsignException e1) {
  154.                     logger.error("Error getting correct notification tempalte for key: {}", correctNotification.getTemplate());
  155.                     throw e1;
  156.                 } catch (Exception e2) {
  157.                     logger.error("Error getting correct notification tempalte for key: {}", correctNotification.getTemplate(), e2);
  158.                     throw new EsignException(EsignException.INTERNAL_PROBLEM);
  159.                 }
  160.             }
  161.  
  162.             // prepare notification parameters for creation of messages from
  163.             // templates
  164.             Map<String, String> params = new HashMap<String, String>();
  165.             String signOrderId = signOrder.getOrderId();
  166.             params.put(NotificationTemplateParams.SIGN_ORDER_ID, signOrderId);
  167.             params.put(NotificationTemplateParams.PARTICIPANT_FULL_NAME, participant.getFullName());
  168.             params.put(NotificationTemplateParams.ISSUER_NAME, issuer.getName());
  169.             params.put(NotificationTemplateParams.PARTICIPANT_SSN, participant.getSocialSecurityNumber());
  170.             params.put(NotificationTemplateParams.GSS_DIRECT_SIGNING_URL, gssDirectURL);
  171.  
  172.             //MergeTextParser
  173.             if (correctNotification.getMergeText() != null) {
  174.                 Base64 base64 = new Base64();
  175.                 byte[] decodedMegreText = base64.decode(correctNotification.getMergeText().getBytes());
  176.                 StringTokenizer nameValue = new StringTokenizer(new String(decodedMegreText), ";");
  177.                 while (nameValue.hasMoreTokens()) {
  178.                     StringTokenizer splitedNameValue = new StringTokenizer(nameValue.nextToken(), "=");
  179.                     String name = splitedNameValue.nextToken().substring(1);
  180.                     String value = splitedNameValue.nextToken();
  181.  
  182.                     params.put(name, value);
  183.                 }
  184.             }
  185.  
  186.             // get correct notificator for message sending
  187.             NotificationSenderService notificator;
  188.             try {
  189.                 notificator = getNotificator(issuer.getName());
  190.             } catch (Exception e1) {
  191.                 logger.error("Error obtaining correct notificator for issuer: {}", issuer.getName(), e1);
  192.                 throw new EsignException(EsignException.INTERNAL_PROBLEM);
  193.             }
  194.  
  195.             // upload required StepDocuments to providers that support "off line" mode
  196.             String signproviderId = issuer.getSignprovider();
  197.             ISignatureProvider provider = providers.get(signproviderId);
  198.             if (provider == null) {
  199.                 logger.error("The StepDocument upload error. There is no signing provider {} for SignOrder HibId: {}", signproviderId, signOrderHibId);
  200.                 throw new EsignException(EsignException.INTERNAL_PROBLEM);
  201.             }
  202.             try {
  203.                 for (StepDocument stDoc : currentStep.getStepDocuments()) {
  204.                     StepDocument stDocReloaded = (StepDocument) notificationDao.load(StepDocumentImpl.class, stDoc.getId());
  205.                     // register only unsigned documents
  206.                     if (stDocReloaded.getSignedStatus().equals(StepDocumentSignedStatus.UNSIGNED)) {
  207.                         notificationDao.registerOfflineDocument(provider, stDocReloaded);
  208.                     }
  209.                 }
  210.             } catch (EsignException e1) {
  211.                 logger.error("Error uploading StepDocuments for StepId: {}", currentStep.getStepId());
  212.                 throw e1;
  213.             } catch (Exception e2) {
  214.                 logger.error("Error uploading StepDocuments for StepId: {}", currentStep.getStepId(), e2);
  215.                 throw new EsignException(EsignException.INTERNAL_PROBLEM, new String[] { e2.getMessage() });
  216.             }
  217.  
  218.             // send notification for the current step
  219.             try {
  220.                 notificationDao.sendNotifications(signOrder, currentStep, correctNotification, notificator, template, params);
  221.  
  222.             } catch (Exception e) {
  223.                 logger.error("Error in \"sendNotifications\". StepHibId:{} NotificationHibId:{}", currentStep.getId(), correctNotification.getId());
  224.                 throw new EsignException(EsignException.INTERNAL_PROBLEM, new String[] { "Notification sending error" });
  225.             }
  226.         }
  227.  
  228.     }
  229.  
  230.     /**
  231.      * This method says is it allowed to send notification at this point in time
  232.      * or not according to the database column AllowedSendingPeriod or
  233.      * configuration
  234.      *
  235.      * @param notification - notification for sending
  236.      * @param issuerName - issuer name
  237.      * @param now
  238.      * @return
  239.      * @throws EsignException
  240.      */
  241.     private boolean isNotificationAllowedAtCurrentTime(Notification notification, String issuerName, Calendar now) throws EsignException {
  242.         logger.debug("Checking time period for Notification with id={}, issuer={}", notification.getId(), issuerName);
  243.         String allowedPeriodForSending = notification.getAllowedSendingPeriod();
  244.         if (allowedPeriodForSending != null) {
  245.             return isCurrentTimeInAllowedSendingPeriod(allowedPeriodForSending, now);
  246.         } else {
  247.             if (notification.getType().equals(NotificationMethod.EMAIL)) {
  248.                 return isCurrentTimeInAllowedSendingPeriod(ConfigProperties.getValue(ConfigProperties.NOTIFICATION_EMAIL_ALLOWED_SENDING_INTERVAL, issuerName),
  249.                         now);
  250.             } else {
  251.                 return isCurrentTimeInAllowedSendingPeriod(ConfigProperties.getValue(ConfigProperties.NOTIFICATION_SMS_ALLOWED_SENDING_INTERVAL, issuerName),
  252.                         now);
  253.             }
  254.         }
  255.  
  256.     }
  257.  
  258.     /**
  259.      * This method says is current time in allowed period for sending or not
  260.      *
  261.      * allowedPeriodForSending looks like "7:24-19:28 CET"
  262.      *
  263.      * @param allowedPeriodForSending
  264.      * @return
  265.      * @throws EsignException if format of allowedPeriodForSending is invalid
  266.      */
  267.     private boolean isCurrentTimeInAllowedSendingPeriod(String allowedPeriodForSending, Calendar now) throws EsignException {
  268.         int currentMinutes = now.get(Calendar.MINUTE);
  269.         int currentHours = now.get(Calendar.HOUR_OF_DAY);
  270.         String[] tokens = allowedPeriodForSending.split(" ");
  271.         if ((tokens.length < 3) && (tokens[1].equals("CET"))) {
  272.             String[] timePoints = tokens[0].split("-");
  273.             int fromMinutes = Integer.valueOf(timePoints[0].split(":")[1]);
  274.             int fromHours = Integer.valueOf(timePoints[0].split(":")[0]);
  275.             int toMinutes = Integer.valueOf(timePoints[1].split(":")[1]);
  276.             int toHours = Integer.valueOf(timePoints[1].split(":")[0]);
  277.             if ((fromHours < currentHours) && (currentHours < toHours)) {
  278.                 return true;
  279.             } else if (fromHours == currentHours) {
  280.                 if (fromMinutes <= currentMinutes) {
  281.                     return true;
  282.                 } else {
  283.                     return false;
  284.                 }
  285.             } else if (toHours == currentHours) {
  286.                 if (currentMinutes <= toMinutes) {
  287.                     return true;
  288.                 } else {
  289.                     return false;
  290.                 }
  291.             } else {
  292.                 return false;
  293.             }
  294.         } else {
  295.             logger.error("Invalid format of field allowedSendingPeriod. allowedSendingPeriod={}", allowedPeriodForSending);
  296.             throw new EsignException(EsignException.INVALID_FORMAT_OF_FIELD, new Object[] { "allowedSendingPeriod" });
  297.         }
  298.     }
  299.  
  300.     /**
  301.      * similar to providers there is different notificators in system, this
  302.      * method return notificator configured in transigo.properties, there is one
  303.      * default notificator and one more notificator per each issuer
  304.      *
  305.      * @param issuerName
  306.      * @return
  307.      * @throws EsignException
  308.      */
  309.     private NotificationSenderService getNotificator(String issuerName) throws EsignException {
  310.         String notifServiceName = ConfigProperties.getValue(ConfigProperties.NOTIFICATOR_KEY, issuerName);
  311.         NotificationSenderService notifService = notificators.get(notifServiceName);
  312.         if (notifService == null) {
  313.             logger.error("Notificator service {} not found", notifServiceName);
  314.             throw new EsignException(EsignException.INTERNAL_PROBLEM, new String[] { "Notificator service " + notifServiceName + " not found" });
  315.         }
  316.         return notifService;
  317.     }
  318. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement