Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * This software is produced by EDB B&F. Unauthorized redistribution,
- * reproduction or usage of this software in whole or in part without
- * the express written consent of EDB B&F is strictly prohibited.
- * Copyright © 2011 EDB. ALL RIGHTS RESERVED
- */
- package com.edb.esign.service.notification;
- import java.util.*;
- import org.apache.axis2.databinding.types.xsd.DateTime;
- import org.apache.commons.codec.binary.Base64;
- import org.hibernate.LockMode;
- import org.hibernate.exception.LockAcquisitionException;
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- import org.springframework.transaction.annotation.Propagation;
- import org.springframework.transaction.annotation.Transactional;
- import com.edb.esign.ConfigProperties;
- import com.edb.esign.EsignException;
- import com.edb.esign.dao.NotificationDao;
- import com.edb.esign.domain.*;
- import com.edb.esign.providers.ISignatureProvider;
- import com.edb.esign.vo.NotificationTemplateParams;
- /**
- * @author Volodymyr Kulishov
- *
- */
- public class NotificationProcessorService {
- private final static Logger logger = LoggerFactory.getLogger(NotificationProcessorService.class);
- private NotificationDao notificationDao;
- private Map<String, NotificationSenderService> notificators = new HashMap<String, NotificationSenderService>();
- private Map<String, ISignatureProvider> providers = new HashMap<String, ISignatureProvider>();
- private Calendar calendar = Calendar.getInstance();
- public void setCalendar(Calendar calendar) {
- this.calendar = calendar;
- }
- public void setNotificationDao(NotificationDao notificationDao) {
- this.notificationDao = notificationDao;
- }
- public void setNotificators(Map<String, NotificationSenderService> notificators) {
- this.notificators = notificators;
- }
- public void setProviders(Map<String, ISignatureProvider> providers) {
- this.providers = providers;
- }
- /**
- * This method makes necessary checks and makes decision about uploading
- * offline document to signing provider and actual sms/email sending
- *
- * @param logContext
- * @param record
- * @throws ManualTransacationRollbackException
- */
- @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class, readOnly = true)
- public void processNotification(Long signOrderHibId, Long stepHibId) throws EsignException {
- // obtain NO WAIT lock on SignOrder as ROOT entity
- SignOrder signOrder = null;
- try {
- signOrder = (SignOrder) notificationDao.load(SignOrderImpl.class, signOrderHibId, LockMode.UPGRADE_NOWAIT);
- } catch (LockAcquisitionException e) {
- logger.warn("Unable to obtain UPGRADE_NOWAIT lock for SignOrder HibId:{}. Skipping notification sending for Step HibId: {}", signOrderHibId,
- stepHibId);
- throw new EsignException(EsignException.INTERNAL_PROBLEM);
- }
- // reload Step
- Step currentStep = (Step) notificationDao.load(StepImpl.class, stepHibId);
- Participant participant = (Participant) notificationDao.load(ParticipantImpl.class, currentStep.getParticipant().getId());
- Issuer issuer = (Issuer) notificationDao.load(IssuerImpl.class, signOrder.getIssuer().getId());
- // check if there correct notification element exist for this record
- Notification correctNotification = null;
- try {
- correctNotification = notificationDao.getCorrectNotification(currentStep);
- } catch (EsignException e1) {
- logger.error("Error getting correct notification for Step HibId: {} and Participant HibId: {}", currentStep.getId(), participant.getId());
- throw e1;
- } catch (Exception e2) {
- logger.error("Error getting correct notification for Step HibId: {} and Participant HibId: {}", currentStep.getId(), participant.getId());
- logger.error("error:", e2);
- throw new EsignException(EsignException.INTERNAL_PROBLEM);
- }
- if (correctNotification == null) {
- logger.info("There is no correct notification for stepHibId:{} and participantHibId:{} ", currentStep.getId(), participant.getId());
- throw new EsignException(EsignException.INTERNAL_PROBLEM);
- }
- if (isNotificationAllowedAtCurrentTime(correctNotification, issuer.getName(), calendar)) {
- // check if there were notifications before
- if (currentStep.getNotificationExpireDate() != null) {
- // check if last notification already timed out
- Calendar currentDate = Calendar.getInstance();
- if (currentStep.getNotificationExpireDate().after(currentDate.getTime())) {
- // do not send notifications for records with expire date in future
- throw new EsignException(EsignException.INTERNAL_PROBLEM);
- }
- }
- // get required notification template
- // if template element is null then try to use messageText element
- Template template = null;
- String gssDirectURL = null;
- if (correctNotification.getTemplate() == null || correctNotification.getTemplate().length() == 0) {
- if (correctNotification.getMessageText() != null && correctNotification.getMessageText().length() > 0) {
- if (correctNotification.getType().equals(NotificationMethod.EMAIL)) {
- EMailTemplate emailTemplate = new EMailTemplateImpl();
- emailTemplate.setMailSubject(ConfigProperties.getValue(ConfigProperties.GSS_EMAIL_SUBJECT_KEY, issuer.getName()));
- emailTemplate.setMailSenderAddress(ConfigProperties.getValue(ConfigProperties.GSS_EMAIL_SENDER_ADDRESS_KEY, issuer.getName()));
- emailTemplate.setMailReplyToAddress(ConfigProperties.getValue(ConfigProperties.GSS_EMAIL_REPLY_TO_KEY, issuer.getName()));
- emailTemplate.setValue(correctNotification.getMessageText());
- template = emailTemplate;
- } else { // if (correctNotification.getType().equals(NotificationMethod.SMS))
- SMSTemplate smsTemplate = new SMSTemplateImpl();
- smsTemplate.setValue(correctNotification.getMessageText());
- template = smsTemplate;
- }
- // initialize gssRedirectURL, this URL points to gss DIRECT signing page
- String stepDocUID = null;
- for (StepDocument stDoc : currentStep.getStepDocuments()) {
- if (StepDocumentSignedStatus.UNSIGNED.equals(stDoc.getSignedStatus())) {
- stepDocUID = stDoc.getStepDocumentUID();
- }
- }
- StringBuilder configUrl = new StringBuilder();
- configUrl.append(ConfigProperties.getValue(ConfigProperties.GSS_DIRECT_SIGNING_URL));
- configUrl.append("?");
- configUrl.append(ConfigProperties.TASK_ID_PARAM);
- configUrl.append("=");
- configUrl.append(stepDocUID);
- gssDirectURL = configUrl.toString();
- } else {
- logger.error("Error in notification element HibId: {}. The template and messageText attributes are EMPTY.", correctNotification.getId());
- throw new EsignException(EsignException.INTERNAL_PROBLEM);
- }
- } else {
- // retrieve template from TEMPLATE table
- try {
- template = notificationDao.getTemplateObjectForId(correctNotification.getTemplate());
- } catch (EsignException e1) {
- logger.error("Error getting correct notification tempalte for key: {}", correctNotification.getTemplate());
- throw e1;
- } catch (Exception e2) {
- logger.error("Error getting correct notification tempalte for key: {}", correctNotification.getTemplate(), e2);
- throw new EsignException(EsignException.INTERNAL_PROBLEM);
- }
- }
- // prepare notification parameters for creation of messages from
- // templates
- Map<String, String> params = new HashMap<String, String>();
- String signOrderId = signOrder.getOrderId();
- params.put(NotificationTemplateParams.SIGN_ORDER_ID, signOrderId);
- params.put(NotificationTemplateParams.PARTICIPANT_FULL_NAME, participant.getFullName());
- params.put(NotificationTemplateParams.ISSUER_NAME, issuer.getName());
- params.put(NotificationTemplateParams.PARTICIPANT_SSN, participant.getSocialSecurityNumber());
- params.put(NotificationTemplateParams.GSS_DIRECT_SIGNING_URL, gssDirectURL);
- //MergeTextParser
- if (correctNotification.getMergeText() != null) {
- Base64 base64 = new Base64();
- byte[] decodedMegreText = base64.decode(correctNotification.getMergeText().getBytes());
- StringTokenizer nameValue = new StringTokenizer(new String(decodedMegreText), ";");
- while (nameValue.hasMoreTokens()) {
- StringTokenizer splitedNameValue = new StringTokenizer(nameValue.nextToken(), "=");
- String name = splitedNameValue.nextToken().substring(1);
- String value = splitedNameValue.nextToken();
- params.put(name, value);
- }
- }
- // get correct notificator for message sending
- NotificationSenderService notificator;
- try {
- notificator = getNotificator(issuer.getName());
- } catch (Exception e1) {
- logger.error("Error obtaining correct notificator for issuer: {}", issuer.getName(), e1);
- throw new EsignException(EsignException.INTERNAL_PROBLEM);
- }
- // upload required StepDocuments to providers that support "off line" mode
- String signproviderId = issuer.getSignprovider();
- ISignatureProvider provider = providers.get(signproviderId);
- if (provider == null) {
- logger.error("The StepDocument upload error. There is no signing provider {} for SignOrder HibId: {}", signproviderId, signOrderHibId);
- throw new EsignException(EsignException.INTERNAL_PROBLEM);
- }
- try {
- for (StepDocument stDoc : currentStep.getStepDocuments()) {
- StepDocument stDocReloaded = (StepDocument) notificationDao.load(StepDocumentImpl.class, stDoc.getId());
- // register only unsigned documents
- if (stDocReloaded.getSignedStatus().equals(StepDocumentSignedStatus.UNSIGNED)) {
- notificationDao.registerOfflineDocument(provider, stDocReloaded);
- }
- }
- } catch (EsignException e1) {
- logger.error("Error uploading StepDocuments for StepId: {}", currentStep.getStepId());
- throw e1;
- } catch (Exception e2) {
- logger.error("Error uploading StepDocuments for StepId: {}", currentStep.getStepId(), e2);
- throw new EsignException(EsignException.INTERNAL_PROBLEM, new String[] { e2.getMessage() });
- }
- // send notification for the current step
- try {
- notificationDao.sendNotifications(signOrder, currentStep, correctNotification, notificator, template, params);
- } catch (Exception e) {
- logger.error("Error in \"sendNotifications\". StepHibId:{} NotificationHibId:{}", currentStep.getId(), correctNotification.getId());
- throw new EsignException(EsignException.INTERNAL_PROBLEM, new String[] { "Notification sending error" });
- }
- }
- }
- /**
- * This method says is it allowed to send notification at this point in time
- * or not according to the database column AllowedSendingPeriod or
- * configuration
- *
- * @param notification - notification for sending
- * @param issuerName - issuer name
- * @param now
- * @return
- * @throws EsignException
- */
- private boolean isNotificationAllowedAtCurrentTime(Notification notification, String issuerName, Calendar now) throws EsignException {
- logger.debug("Checking time period for Notification with id={}, issuer={}", notification.getId(), issuerName);
- String allowedPeriodForSending = notification.getAllowedSendingPeriod();
- if (allowedPeriodForSending != null) {
- return isCurrentTimeInAllowedSendingPeriod(allowedPeriodForSending, now);
- } else {
- if (notification.getType().equals(NotificationMethod.EMAIL)) {
- return isCurrentTimeInAllowedSendingPeriod(ConfigProperties.getValue(ConfigProperties.NOTIFICATION_EMAIL_ALLOWED_SENDING_INTERVAL, issuerName),
- now);
- } else {
- return isCurrentTimeInAllowedSendingPeriod(ConfigProperties.getValue(ConfigProperties.NOTIFICATION_SMS_ALLOWED_SENDING_INTERVAL, issuerName),
- now);
- }
- }
- }
- /**
- * This method says is current time in allowed period for sending or not
- *
- * allowedPeriodForSending looks like "7:24-19:28 CET"
- *
- * @param allowedPeriodForSending
- * @return
- * @throws EsignException if format of allowedPeriodForSending is invalid
- */
- private boolean isCurrentTimeInAllowedSendingPeriod(String allowedPeriodForSending, Calendar now) throws EsignException {
- int currentMinutes = now.get(Calendar.MINUTE);
- int currentHours = now.get(Calendar.HOUR_OF_DAY);
- String[] tokens = allowedPeriodForSending.split(" ");
- if ((tokens.length < 3) && (tokens[1].equals("CET"))) {
- String[] timePoints = tokens[0].split("-");
- int fromMinutes = Integer.valueOf(timePoints[0].split(":")[1]);
- int fromHours = Integer.valueOf(timePoints[0].split(":")[0]);
- int toMinutes = Integer.valueOf(timePoints[1].split(":")[1]);
- int toHours = Integer.valueOf(timePoints[1].split(":")[0]);
- if ((fromHours < currentHours) && (currentHours < toHours)) {
- return true;
- } else if (fromHours == currentHours) {
- if (fromMinutes <= currentMinutes) {
- return true;
- } else {
- return false;
- }
- } else if (toHours == currentHours) {
- if (currentMinutes <= toMinutes) {
- return true;
- } else {
- return false;
- }
- } else {
- return false;
- }
- } else {
- logger.error("Invalid format of field allowedSendingPeriod. allowedSendingPeriod={}", allowedPeriodForSending);
- throw new EsignException(EsignException.INVALID_FORMAT_OF_FIELD, new Object[] { "allowedSendingPeriod" });
- }
- }
- /**
- * similar to providers there is different notificators in system, this
- * method return notificator configured in transigo.properties, there is one
- * default notificator and one more notificator per each issuer
- *
- * @param issuerName
- * @return
- * @throws EsignException
- */
- private NotificationSenderService getNotificator(String issuerName) throws EsignException {
- String notifServiceName = ConfigProperties.getValue(ConfigProperties.NOTIFICATOR_KEY, issuerName);
- NotificationSenderService notifService = notificators.get(notifServiceName);
- if (notifService == null) {
- logger.error("Notificator service {} not found", notifServiceName);
- throw new EsignException(EsignException.INTERNAL_PROBLEM, new String[] { "Notificator service " + notifServiceName + " not found" });
- }
- return notifService;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement