Search in sources :

Example 1 with PoolMessage

use of cz.metacentrum.perun.notif.dto.PoolMessage in project perun by CESNET.

the class PerunNotifEmailGroupSender method send.

@Override
public Set<Integer> send(List<PerunNotifMessageDto> dtosToSend) {
    Set<Integer> usedPoolIds = new HashSet<Integer>();
    List<PerunNotifEmailMessageToSendDto> messagesToSend = new ArrayList<PerunNotifEmailMessageToSendDto>();
    for (PerunNotifMessageDto messageDto : dtosToSend) {
        PoolMessage dto = messageDto.getPoolMessage();
        PerunNotifTemplate template = messageDto.getTemplate();
        PerunNotifReceiver receiver = messageDto.getReceiver();
        try {
            String groupSender = dto.getKeyAttributes().get(template.getSender());
            if (groupSender == null || groupSender.isEmpty()) {
                groupSender = template.getSender();
            }
            logger.debug("Calculated sender : {}", groupSender);
            Integer groupId = Integer.valueOf(receiver.getTarget());
            Group group = perun.getGroupsManagerBl().getGroupById(session, groupId);
            List<Member> groupMembers = perun.getGroupsManagerBl().getGroupMembers(session, group);
            if (groupMembers != null) {
                for (Member member : groupMembers) {
                    try {
                        PerunNotifEmailMessageToSendDto memberEmailDto = new PerunNotifEmailMessageToSendDto();
                        memberEmailDto.setMessage(messageDto.getMessageToSend());
                        memberEmailDto.setSubject(messageDto.getSubject());
                        memberEmailDto.setReceiver((String) perun.getAttributesManagerBl().getAttribute(session, perun.getUsersManager().getUserByMember(session, member), "urn:perun:user:attribute-def:def:preferredMail").getValue());
                        memberEmailDto.setSender(groupSender);
                        messagesToSend.add(memberEmailDto);
                    } catch (Exception ex) {
                        logger.error("PreferredEmail cannot be retrieved, userId: {}", member.getUserId(), ex);
                    }
                }
            }
            usedPoolIds.addAll(messageDto.getUsedPoolIds());
        } catch (NumberFormatException ex) {
            logger.error("GroupId cannot be parsed: {}", receiver.getTarget());
        } catch (GroupNotExistsException ex) {
            logger.error("Group with id: {} does not exists.", receiver.getTarget());
        } catch (InternalErrorException ex) {
            logger.error("Error during processing messageDto.", ex);
        }
    }
    perunNotifEmailManager.sendMessages(messagesToSend);
    return usedPoolIds;
}
Also used : PerunNotifTemplate(cz.metacentrum.perun.notif.entities.PerunNotifTemplate) GroupNotExistsException(cz.metacentrum.perun.core.api.exceptions.GroupNotExistsException) ArrayList(java.util.ArrayList) PerunNotifReceiver(cz.metacentrum.perun.notif.entities.PerunNotifReceiver) InternalErrorException(cz.metacentrum.perun.core.api.exceptions.InternalErrorException) PerunNotifMessageDto(cz.metacentrum.perun.notif.dto.PerunNotifMessageDto) InternalErrorException(cz.metacentrum.perun.core.api.exceptions.InternalErrorException) GroupNotExistsException(cz.metacentrum.perun.core.api.exceptions.GroupNotExistsException) PoolMessage(cz.metacentrum.perun.notif.dto.PoolMessage) PerunNotifEmailMessageToSendDto(cz.metacentrum.perun.notif.dto.PerunNotifEmailMessageToSendDto) HashSet(java.util.HashSet)

Example 2 with PoolMessage

use of cz.metacentrum.perun.notif.dto.PoolMessage in project perun by CESNET.

the class PerunNotifJabberSender method send.

@Override
public Set<Integer> send(List<PerunNotifMessageDto> dtosToSend) {
    Set<Integer> usedPools = new HashSet<Integer>();
    try {
        ConnectionConfiguration config = new ConnectionConfiguration(jabberServer, port, serviceName);
        XMPPConnection connection = new XMPPConnection(config);
        connection.connect();
        SASLAuthentication.supportSASLMechanism("PLAIN", 0);
        connection.login(username, password);
        for (PerunNotifMessageDto messageDto : dtosToSend) {
            PerunNotifReceiver receiver = messageDto.getReceiver();
            PoolMessage dto = messageDto.getPoolMessage();
            Message message = new Message();
            message.setSubject(messageDto.getSubject());
            message.setBody(messageDto.getMessageToSend());
            message.setType(Message.Type.headline);
            String myReceiverId = dto.getKeyAttributes().get(receiver.getTarget());
            if (myReceiverId == null || myReceiverId.isEmpty()) {
                //Can be set one static account
                message.setTo(receiver.getTarget());
            } else {
                //We try to resolve id
                Integer id = null;
                try {
                    id = Integer.valueOf(myReceiverId);
                } catch (NumberFormatException ex) {
                    logger.error("Cannot resolve id: {}, error: {}", Arrays.asList(id, ex.getMessage()));
                    logger.debug("ST:", ex);
                }
                if (id != null) {
                    try {
                        User user = perun.getUsersManagerBl().getUserById(session, id);
                        Attribute emailAttribute = perun.getAttributesManagerBl().getAttribute(session, user, "urn:perun:user:attribute-def:def:jabber");
                        if (emailAttribute != null && StringUtils.hasText(emailAttribute.toString())) {
                            message.setTo((String) emailAttribute.getValue());
                        }
                    } catch (UserNotExistsException ex) {
                        logger.error("Cannot found user with id: {}, ex: {}", Arrays.asList(id, ex.getMessage()));
                        logger.debug("ST:", ex);
                    } catch (AttributeNotExistsException ex) {
                        logger.warn("Cannot found email for user with id: {}, ex: {}", Arrays.asList(id, ex.getMessage()));
                        logger.debug("ST:", ex);
                    } catch (Exception ex) {
                        logger.error("Error during user email recognition, ex: {}", ex.getMessage());
                        logger.debug("ST:", ex);
                    }
                }
            }
            connection.sendPacket(message);
            usedPools.addAll(messageDto.getUsedPoolIds());
        }
        connection.disconnect();
    } catch (XMPPException ex) {
        logger.error("Error during jabber establish connection.", ex);
    }
    return null;
}
Also used : PoolMessage(cz.metacentrum.perun.notif.dto.PoolMessage) Message(org.jivesoftware.smack.packet.Message) UserNotExistsException(cz.metacentrum.perun.core.api.exceptions.UserNotExistsException) AttributeNotExistsException(cz.metacentrum.perun.core.api.exceptions.AttributeNotExistsException) PerunNotifReceiver(cz.metacentrum.perun.notif.entities.PerunNotifReceiver) XMPPConnection(org.jivesoftware.smack.XMPPConnection) PerunNotifMessageDto(cz.metacentrum.perun.notif.dto.PerunNotifMessageDto) AttributeNotExistsException(cz.metacentrum.perun.core.api.exceptions.AttributeNotExistsException) UserNotExistsException(cz.metacentrum.perun.core.api.exceptions.UserNotExistsException) XMPPException(org.jivesoftware.smack.XMPPException) ConnectionConfiguration(org.jivesoftware.smack.ConnectionConfiguration) PoolMessage(cz.metacentrum.perun.notif.dto.PoolMessage) XMPPException(org.jivesoftware.smack.XMPPException)

Example 3 with PoolMessage

use of cz.metacentrum.perun.notif.dto.PoolMessage in project perun by CESNET.

the class PerunNotifTemplateManagerImpl method processPoolMessages.

@Override
public Set<Integer> processPoolMessages(Integer templateId, List<PoolMessage> notifMessages) {
    if (notifMessages == null || notifMessages.isEmpty() || templateId == null) {
        return null;
    }
    List<PerunNotifMessageDto> messageDtoList = new ArrayList<PerunNotifMessageDto>();
    logger.info("Starting to process messages for template with id:" + templateId);
    PerunNotifTemplate template = allTemplatesById.get(templateId);
    switch(template.getNotifyTrigger()) {
        case ALL_REGEX_IDS:
            for (PoolMessage dto : notifMessages) {
                // Test for all regexIds present
                logger.info("Starting to process dto for templateId: " + templateId + " and keyAttributes: " + dto.getKeyAttributes());
                Set<Integer> foundRegexIds = new HashSet<Integer>();
                for (PerunNotifPoolMessage poolMessage : dto.getList()) {
                    foundRegexIds.add(poolMessage.getRegexId());
                }
                boolean allRegexes = true;
                for (PerunNotifRegex regex : template.getMatchingRegexs()) {
                    if (!foundRegexIds.contains(regex.getId())) {
                        logger.info("Not all regexes found for templateId: " + templateId + ", and keyAttributes: " + dto.getKeyAttributes() + " missing:" + regex.getId());
                        allRegexes = false;
                    }
                }
                if (allRegexes) {
                    logger.info("All regexes found for templateId: " + templateId + " and keyAttribute: " + dto.getKeyAttributes() + " starting to create message.");
                    try {
                        messageDtoList.addAll(createMessageToSend(template, dto));
                    } catch (Exception ex) {
                        logger.error("Error during creating message to send.", ex);
                    }
                }
            }
            break;
        //      - need to ensure delivery of all the msgs required by the template message
        case STREAM:
            DateTime now = new DateTime();
            DateTime oldestTime = new DateTime(now.getMillis() - template.getOldestMessageTime());
            DateTime youngestTime = new DateTime(now.getMillis() - template.getYoungestMessageTime());
            for (PoolMessage parentDto : notifMessages) {
                List<PerunNotifPoolMessage> poolMessages = parentDto.getList();
                if (poolMessages != null) {
                    // Test for oldest message first message in list is oldest,
                    // messages
                    // are sorted from sql query
                    PerunNotifPoolMessage oldestPoolMessage = poolMessages.get(0);
                    if (oldestPoolMessage.getCreated().compareTo(oldestTime) < 0) {
                        // we have and send it
                        try {
                            logger.debug("Oldest message is older than oldest time for template id " + template.getId() + " message will be sent.");
                            messageDtoList.addAll(createMessageToSend(template, parentDto));
                        } catch (Exception ex) {
                            logger.error("Error during creating of messages to send.", ex);
                        }
                    } else {
                        // We test youngest message so we now nothing new will
                        // propably come in close future
                        PerunNotifPoolMessage youngestPoolMessage = poolMessages.get(poolMessages.size() - 1);
                        if (youngestPoolMessage.getCreated().compareTo(youngestTime) < 0) {
                            // Youngest message is older
                            try {
                                logger.debug("Youngest message is older than youngest time for template id " + template.getId() + " message will be sent.");
                                messageDtoList.addAll(createMessageToSend(template, parentDto));
                            } catch (Exception ex) {
                                logger.error("Error during creating of messages to send.", ex);
                            }
                        } else {
                            Period oldestPeriod = new Period(oldestPoolMessage.getCreated().getMillis() - oldestTime.getMillis());
                            Period youngestPeriod = new Period(youngestPoolMessage.getCreated().getMillis() - youngestTime.getMillis());
                            Period period = oldestPeriod.getMillis() < youngestPeriod.getMillis() ? oldestPeriod : youngestPeriod;
                            String remainingTime = "";
                            if (period.getDays() > 0) {
                                remainingTime += period.getDays() + " days ";
                            }
                            if (period.getHours() > 0) {
                                remainingTime += period.getHours() + " hours ";
                            }
                            if (period.getMinutes() > 0) {
                                remainingTime += period.getMinutes() + " minutes ";
                            }
                            if (period.getSeconds() > 0) {
                                remainingTime += period.getSeconds() + " sec.";
                            }
                            logger.debug("The time limits for messages are greater that messages creation time for template id " + template.getId() + ", the message will not be sent yet. " + "Provided no messages is created, the notification will be sent in " + remainingTime);
                        }
                    }
                }
            }
            break;
    }
    Map<PerunNotifTypeOfReceiver, List<PerunNotifMessageDto>> messagesToSend = new HashMap<PerunNotifTypeOfReceiver, List<PerunNotifMessageDto>>();
    Set<Integer> processedIds = new HashSet<Integer>();
    for (PerunNotifMessageDto messageToSend : messageDtoList) {
        List<PerunNotifMessageDto> list = messagesToSend.get(messageToSend.getReceiver().getTypeOfReceiver());
        if (list == null) {
            list = new ArrayList<PerunNotifMessageDto>();
            list.add(messageToSend);
            messagesToSend.put(messageToSend.getReceiver().getTypeOfReceiver(), list);
        } else {
            list.add(messageToSend);
        }
    }
    for (PerunNotifTypeOfReceiver typeOfReceiver : messagesToSend.keySet()) {
        PerunNotifSender handlingSender = null;
        for (PerunNotifSender sender : notifSenders) {
            if (sender.canHandle(typeOfReceiver)) {
                handlingSender = sender;
            }
        }
        if (handlingSender != null) {
            logger.debug("Found handling sender: {}", handlingSender.toString());
            processedIds.addAll(handlingSender.send(messagesToSend.get(typeOfReceiver)));
            logger.debug("Messages send by sender: {}", handlingSender.toString());
        } else {
            logger.error("No handling sender found for: {}", typeOfReceiver);
        }
    }
    return processedIds;
}
Also used : ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Period(org.joda.time.Period) PerunNotifSender(cz.metacentrum.perun.notif.senders.PerunNotifSender) PerunNotifMessageDto(cz.metacentrum.perun.notif.dto.PerunNotifMessageDto) NotifReceiverAlreadyExistsException(cz.metacentrum.perun.notif.exceptions.NotifReceiverAlreadyExistsException) InternalErrorException(cz.metacentrum.perun.core.api.exceptions.InternalErrorException) TemplateException(freemarker.template.TemplateException) NotifTemplateMessageAlreadyExistsException(cz.metacentrum.perun.notif.exceptions.NotifTemplateMessageAlreadyExistsException) TemplateMessageSyntaxErrorException(cz.metacentrum.perun.notif.exceptions.TemplateMessageSyntaxErrorException) InvalidReferenceException(freemarker.core.InvalidReferenceException) NotExistsException(cz.metacentrum.perun.notif.exceptions.NotExistsException) IOException(java.io.IOException) AttributeNotExistsException(cz.metacentrum.perun.core.api.exceptions.AttributeNotExistsException) FileNotFoundException(java.io.FileNotFoundException) ParseException(freemarker.core.ParseException) UserNotExistsException(cz.metacentrum.perun.core.api.exceptions.UserNotExistsException) PerunException(cz.metacentrum.perun.core.api.exceptions.PerunException) DateTime(org.joda.time.DateTime) PoolMessage(cz.metacentrum.perun.notif.dto.PoolMessage) PerunNotifTypeOfReceiver(cz.metacentrum.perun.notif.enums.PerunNotifTypeOfReceiver)

Example 4 with PoolMessage

use of cz.metacentrum.perun.notif.dto.PoolMessage in project perun by CESNET.

the class PerunNotifEmailUserSender method send.

@Override
public Set<Integer> send(List<PerunNotifMessageDto> dtosToSend) {
    Set<Integer> usedPools = new HashSet<Integer>();
    List<PerunNotifEmailMessageToSendDto> messagesToSend = new ArrayList<PerunNotifEmailMessageToSendDto>();
    for (PerunNotifMessageDto messageDto : dtosToSend) {
        PerunNotifReceiver receiver = messageDto.getReceiver();
        PoolMessage dto = messageDto.getPoolMessage();
        logger.debug("Creating email for user, receiver: {}", receiver.getId());
        PerunNotifEmailMessageToSendDto emailDto = new PerunNotifEmailMessageToSendDto();
        emailDto.setMessage(messageDto.getMessageToSend());
        emailDto.setSubject(messageDto.getSubject());
        usedPools.addAll(messageDto.getUsedPoolIds());
        String sender = messageDto.getSender();
        emailDto.setSender(sender);
        logger.debug("Calculated sender for receiver: {}, sender: {}", Arrays.asList(receiver.getId(), sender));
        String myReceiverId = dto.getKeyAttributes().get(receiver.getTarget());
        if (myReceiverId == null || myReceiverId.isEmpty()) {
            //Can be set one static account
            emailDto.setReceiver(receiver.getTarget());
        } else {
            //We try to resolve id
            Integer id = null;
            try {
                id = Integer.valueOf(myReceiverId);
            } catch (NumberFormatException ex) {
                logger.error("Cannot resolve id: {}, error: {}", Arrays.asList(id, ex.getMessage()));
                logger.debug("ST:", ex);
            }
            if (id != null) {
                try {
                    User user = perun.getUsersManagerBl().getUserById(session, id);
                    Attribute emailAttribute = perun.getAttributesManagerBl().getAttribute(session, user, "urn:perun:user:attribute-def:def:preferredMail");
                    if (emailAttribute != null && StringUtils.hasText(emailAttribute.toString())) {
                        emailDto.setReceiver((String) emailAttribute.getValue());
                    }
                } catch (UserNotExistsException ex) {
                    logger.error("Cannot found user with id: {}, ex: {}", Arrays.asList(id, ex.getMessage()));
                    logger.debug("ST:", ex);
                } catch (AttributeNotExistsException ex) {
                    logger.warn("Cannot found email for user with id: {}, ex: {}", Arrays.asList(id, ex.getMessage()));
                    logger.debug("ST:", ex);
                } catch (Exception ex) {
                    logger.error("Error during user email recognition, ex: {}", ex.getMessage());
                    logger.debug("ST:", ex);
                }
            }
        }
        messagesToSend.add(emailDto);
    }
    perunNotifEmailManager.sendMessages(messagesToSend);
    return usedPools;
}
Also used : UserNotExistsException(cz.metacentrum.perun.core.api.exceptions.UserNotExistsException) AttributeNotExistsException(cz.metacentrum.perun.core.api.exceptions.AttributeNotExistsException) PerunNotifReceiver(cz.metacentrum.perun.notif.entities.PerunNotifReceiver) PerunNotifMessageDto(cz.metacentrum.perun.notif.dto.PerunNotifMessageDto) AttributeNotExistsException(cz.metacentrum.perun.core.api.exceptions.AttributeNotExistsException) UserNotExistsException(cz.metacentrum.perun.core.api.exceptions.UserNotExistsException) PoolMessage(cz.metacentrum.perun.notif.dto.PoolMessage) PerunNotifEmailMessageToSendDto(cz.metacentrum.perun.notif.dto.PerunNotifEmailMessageToSendDto)

Aggregations

PerunNotifMessageDto (cz.metacentrum.perun.notif.dto.PerunNotifMessageDto)4 PoolMessage (cz.metacentrum.perun.notif.dto.PoolMessage)4 AttributeNotExistsException (cz.metacentrum.perun.core.api.exceptions.AttributeNotExistsException)3 UserNotExistsException (cz.metacentrum.perun.core.api.exceptions.UserNotExistsException)3 PerunNotifReceiver (cz.metacentrum.perun.notif.entities.PerunNotifReceiver)3 InternalErrorException (cz.metacentrum.perun.core.api.exceptions.InternalErrorException)2 PerunNotifEmailMessageToSendDto (cz.metacentrum.perun.notif.dto.PerunNotifEmailMessageToSendDto)2 GroupNotExistsException (cz.metacentrum.perun.core.api.exceptions.GroupNotExistsException)1 PerunException (cz.metacentrum.perun.core.api.exceptions.PerunException)1 PerunNotifTemplate (cz.metacentrum.perun.notif.entities.PerunNotifTemplate)1 PerunNotifTypeOfReceiver (cz.metacentrum.perun.notif.enums.PerunNotifTypeOfReceiver)1 NotExistsException (cz.metacentrum.perun.notif.exceptions.NotExistsException)1 NotifReceiverAlreadyExistsException (cz.metacentrum.perun.notif.exceptions.NotifReceiverAlreadyExistsException)1 NotifTemplateMessageAlreadyExistsException (cz.metacentrum.perun.notif.exceptions.NotifTemplateMessageAlreadyExistsException)1 TemplateMessageSyntaxErrorException (cz.metacentrum.perun.notif.exceptions.TemplateMessageSyntaxErrorException)1 PerunNotifSender (cz.metacentrum.perun.notif.senders.PerunNotifSender)1 InvalidReferenceException (freemarker.core.InvalidReferenceException)1 ParseException (freemarker.core.ParseException)1 TemplateException (freemarker.template.TemplateException)1 FileNotFoundException (java.io.FileNotFoundException)1