Search in sources :

Example 1 with MessageSender

use of org.hzero.boot.message.entity.MessageSender in project choerodon-asgard by open-hand.

the class NoticeServiceImpl method sendSagaFailNotice.

@Override
@Async("notify-executor")
public void sendSagaFailNotice(SagaInstanceDTO instance) {
    // 捕获异常,以免影响saga一致性
    try {
        // 构建消息对象
        MessageSender messageSender = new MessageSender();
        // 消息code
        messageSender.setMessageCode(BusinessTypeCode.SAGA_INSTANCE_FAIL.value());
        // 默认为0L,都填0L,可不填写
        messageSender.setTenantId(0L);
        // 消息参数 消息模板中${projectName}
        Map<String, String> argsMap = new HashMap<>();
        argsMap.put("sagaInstanceId", instance.getId().toString());
        argsMap.put("sagaCode", instance.getSagaCode());
        argsMap.put("level", instance.getLevel());
        User user = iamFeignClient.queryInfo(instance.getCreatedBy()).getBody();
        // 接收者
        List<Receiver> receiverList = new ArrayList<>();
        Receiver receiver = new Receiver();
        receiver.setUserId(user.getId());
        // 发送邮件消息时 必填
        receiver.setEmail(user.getEmail());
        // 发送短信消息 必填
        receiver.setPhone(user.getPhone());
        // 必填
        receiver.setTargetUserTenantId(user.getOrganizationId());
        argsMap.put("userName", user.getRealName());
        receiverList.add(receiver);
        messageSender.setReceiverAddressList(receiverList);
        messageSender.setArgs(argsMap);
        Map<String, Object> objectMap = new HashMap<>();
        // 发送组织层和项目层消息时必填 当前组织id
        addSourceId(objectMap, instance.getLevel(), instance.getSourceId());
        messageSender.setAdditionalInformation(objectMap);
        messageClient.async().sendMessage(messageSender);
    } catch (Exception e) {
        LOGGER.error("saga instance fail send notice fail", e);
    }
}
Also used : MessageSender(org.hzero.boot.message.entity.MessageSender) Receiver(org.hzero.boot.message.entity.Receiver) CommonException(io.choerodon.core.exception.CommonException) Async(org.springframework.scheduling.annotation.Async)

Example 2 with MessageSender

use of org.hzero.boot.message.entity.MessageSender in project choerodon-asgard by open-hand.

the class NoticeServiceImpl method getBaseMessageSender.

private MessageSender getBaseMessageSender(String jobName, String level, Long sourceId, String jobStatus, QuartzTaskDTO quartzTaskDTO) {
    MessageSender messageSender = new MessageSender();
    // 消息code
    messageSender.setMessageCode(BusinessTypeCode.getValueByLevel(level.toUpperCase()).value());
    // 默认为0L,都填0L,可不填写
    messageSender.setTenantId(0L);
    // 消息参数 消息模板中${projectName}
    Map<String, String> argsMap = new HashMap<>();
    argsMap.put("JOB_NAME", jobName);
    argsMap.put("JOB_STATUS", jobStatus);
    argsMap.put("objectKind", BusinessTypeCode.getValueByLevel(level.toUpperCase()).value());
    argsMap.put("organizationId", sourceId.toString());
    argsMap.put("jobName", jobName);
    argsMap.put("jobStatus", jobStatus);
    argsMap.put("startedAt", String.valueOf(quartzTaskDTO.getStartTime()));
    argsMap.put("finishedAt", String.valueOf(quartzTaskDTO.getLastUpdateDate()));
    if (JOB_STATUS_ORGANIZATION.equals(BusinessTypeCode.getValueByLevel(level.toUpperCase()).value())) {
        argsMap.put("eventName", EVENT_NAME);
    }
    if (JOB_STATUS_SITE.equals(BusinessTypeCode.getValueByLevel(level.toUpperCase()).value())) {
        argsMap.put("eventName", EVENT_NAME_SITE);
    }
    messageSender.setArgs(argsMap);
    return messageSender;
}
Also used : MessageSender(org.hzero.boot.message.entity.MessageSender)

Example 3 with MessageSender

use of org.hzero.boot.message.entity.MessageSender in project choerodon-asgard by open-hand.

the class NoticeServiceImpl method sendSagaFailNoticeForVindicator.

@Override
@Async("notify-executor")
public void sendSagaFailNoticeForVindicator(SagaInstanceDTO instance) {
    try {
        if (mapEvent.containsKey(instance.getSagaCode())) {
            List<User> userList = baseServiceClientOperator.listVindicators();
            if (!CollectionUtils.isEmpty(userList)) {
                Map<String, String> argsMap = new HashMap<>();
                argsMap.put("instanceId", instance.getId().toString());
                switch(instance.getSagaCode()) {
                    case IAM_CREATE_ORG_USER:
                    case IAM_CREATE_USER:
                    case IAM_CREATE_PROJECT:
                        Organization organization = baseServiceClientOperator.queryTenantById(instance.getSourceId());
                        argsMap.put("organizationName", organization.getTenantName());
                        break;
                    default:
                }
                MessageSender messageSender = new MessageSender();
                messageSender.setArgs(argsMap);
                messageSender.setMessageCode(mapEvent.get(instance.getSagaCode()));
                messageSender.setTenantId(0L);
                List<Receiver> receiverList = userList.stream().map(t -> {
                    Receiver receiver = new Receiver();
                    receiver.setUserId(t.getId());
                    receiver.setEmail(t.getEmail());
                    receiver.setPhone(t.getPhone());
                    receiver.setTargetUserTenantId(Objects.requireNonNull(t.getOrganizationId(), "receiver tenant id can't be null"));
                    return receiver;
                }).collect(Collectors.toList());
                Map<String, Object> objectMap = new HashMap<>();
                // 发送组织层和项目层消息时必填 当前组织id
                addSourceId(objectMap, instance.getLevel(), instance.getSourceId());
                messageSender.setAdditionalInformation(objectMap);
                messageSender.setReceiverAddressList(receiverList);
                messageClient.async().sendMessage(messageSender);
            }
        }
    } catch (Exception e) {
        LOGGER.error("saga instance fail send notice fail for vindicator create event", e);
    }
}
Also used : BusinessTypeCode(io.choerodon.asgard.infra.enums.BusinessTypeCode) Async(org.springframework.scheduling.annotation.Async) java.util(java.util) MessageAdditionalType(io.choerodon.core.enums.MessageAdditionalType) NoticeService(io.choerodon.asgard.app.service.NoticeService) LoggerFactory(org.slf4j.LoggerFactory) Autowired(org.springframework.beans.factory.annotation.Autowired) io.choerodon.asgard.api.vo(io.choerodon.asgard.api.vo) QuartzTaskMemberDTO(io.choerodon.asgard.infra.dto.QuartzTaskMemberDTO) Service(org.springframework.stereotype.Service) MessageClient(org.hzero.boot.message.MessageClient) CommonException(io.choerodon.core.exception.CommonException) MessageSender(org.hzero.boot.message.entity.MessageSender) Logger(org.slf4j.Logger) BaseServiceClientOperator(io.choerodon.asgard.infra.feign.operator.BaseServiceClientOperator) QuartzTaskDTO(io.choerodon.asgard.infra.dto.QuartzTaskDTO) Collectors(java.util.stream.Collectors) SagaInstanceDTO(io.choerodon.asgard.infra.dto.SagaInstanceDTO) Receiver(org.hzero.boot.message.entity.Receiver) CollectionUtils(org.springframework.util.CollectionUtils) MemberType(io.choerodon.asgard.infra.enums.MemberType) SagaTaskInstanceDTO(io.choerodon.asgard.infra.dto.SagaTaskInstanceDTO) IamFeignClient(io.choerodon.asgard.infra.feign.IamFeignClient) BeanUtils(org.springframework.beans.BeanUtils) ResourceLevel(io.choerodon.core.iam.ResourceLevel) MessageSender(org.hzero.boot.message.entity.MessageSender) Receiver(org.hzero.boot.message.entity.Receiver) CommonException(io.choerodon.core.exception.CommonException) Async(org.springframework.scheduling.annotation.Async)

Example 4 with MessageSender

use of org.hzero.boot.message.entity.MessageSender in project choerodon-message by open-hand.

the class RelSendMessageController method sendAllMessageWithReceipt.

@ApiOperation(value = "关联发送消息,邮件/短信/站内信/微信/钉钉(返回发送结果,若服务端开启了异步发送则不返回)")
@Permission(level = ResourceLevel.ORGANIZATION)
@PostMapping("/all/with-receipt")
public ResponseEntity<List<Message>> sendAllMessageWithReceipt(@PathVariable("organizationId") Long organizationId, @RequestBody @Encrypt AllSender sender) {
    List<Message> result = new ArrayList<>();
    MessageSender messageSender = sender.getMessageSender();
    WeChatSender weChatSender = sender.getWeChatSender();
    DingTalkSender dingTalkSender = sender.getDingTalkSender();
    if (messageSender != null) {
        messageSender.setTenantId(organizationId);
        validObject(messageSender);
        result.addAll(relSendMessageService.relSendMessageReceipt(messageSender, organizationId));
    }
    if (weChatSender != null) {
        weChatSender.setTenantId(organizationId);
        validObject(weChatSender);
        weChatSender.setLang(StringUtils.hasText(weChatSender.getLang()) ? weChatSender.getLang() : messageClientProperties.getDefaultLang());
        result.addAll(relSendMessageService.relSendMessageReceipt(weChatSender));
    }
    if (dingTalkSender != null) {
        dingTalkSender.setTenantId(organizationId);
        validObject(dingTalkSender);
        dingTalkSender.setLang(StringUtils.hasText(dingTalkSender.getLang()) ? dingTalkSender.getLang() : messageClientProperties.getDefaultLang());
        result.addAll(relSendMessageService.relSendMessageReceipt(dingTalkSender));
    }
    return Results.success(result);
}
Also used : WeChatSender(org.hzero.boot.message.entity.WeChatSender) Message(org.hzero.message.domain.entity.Message) MessageSender(org.hzero.boot.message.entity.MessageSender) ArrayList(java.util.ArrayList) DingTalkSender(org.hzero.boot.message.entity.DingTalkSender) ApiOperation(io.swagger.annotations.ApiOperation) Permission(io.choerodon.swagger.annotation.Permission)

Example 5 with MessageSender

use of org.hzero.boot.message.entity.MessageSender in project agile-service by open-hand.

the class IssueDelaySendMessageTask method run.

@JobTask(maxRetryCount = 3, code = "issueDelaySendMessage", description = "问题延期,发送消息给指定人")
@TimedTask(name = "issueDelaySendMessage", description = "问题延期,发送消息给指定人", oneExecution = false, params = {}, triggerType = TriggerTypeEnum.CRON_TRIGGER, cronExpression = "0 30 2 * * ? ")
public void run(Map<String, Object> map) {
    LOGGER.info("===> 开始执行问题延期发送消息定时任务");
    Map<Long, ProjectMessageVO> projectMap = delayTaskService.listEnabledMsgProjects(ISSUE_DELAY);
    if (ObjectUtils.isEmpty(projectMap)) {
        LOGGER.info("===> 没有配置发送消息的项目,问题延期发送消息定时任务完成");
        return;
    }
    Set<Long> projectIds = projectMap.keySet();
    // key1 projectId, key2 userId, value Set<IssueDelayCarrierVO>
    MultiKeyMap multiKeyMap = new MultiKeyMap();
    Map<Long, UserDTO> userMap = new HashMap<>();
    Map<Long, PriorityVO> priorityMap = new HashMap<>();
    Map<Long, StatusVO> statusMap = new HashMap<>();
    if (!projectIds.isEmpty()) {
        Date now = new Date();
        List<IssueDTO> issues = issueMapper.selectDelayIssues(projectIds, now);
        Map<Long, List<IssueDTO>> issueGroupByProject = issues.stream().collect(Collectors.groupingBy(IssueDTO::getProjectId));
        Set<Long> userIds = new HashSet<>();
        Set<Long> projectIdForProjectOwner = new HashSet<>();
        LocalDateTime localDateTime = now.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
        processIssueToMultiKeyMap(projectMap, multiKeyMap, localDateTime, issueGroupByProject, userIds, projectIdForProjectOwner, priorityMap, statusMap);
        processProjectOwner(projectMap, multiKeyMap, issueGroupByProject, userIds, projectIdForProjectOwner, localDateTime);
        if (!userIds.isEmpty()) {
            userMap.putAll(baseFeignClient.listUsersByIds(userIds.toArray(new Long[userIds.size()]), true).getBody().stream().collect(Collectors.toMap(UserDTO::getId, Function.identity())));
        }
    }
    List<MessageSender> messageSenders = new ArrayList<>();
    MapIterator mapIterator = multiKeyMap.mapIterator();
    while (mapIterator.hasNext()) {
        MultiKey multiKey = (MultiKey) mapIterator.next();
        Long projectId = (Long) multiKey.getKey(0);
        Long userId = (Long) multiKey.getKey(1);
        Set<IssueDelayCarrierVO> set = (Set<IssueDelayCarrierVO>) mapIterator.getValue();
        if (!ObjectUtils.isEmpty(set)) {
            List<IssueDelayCarrierVO> list = new ArrayList<>(set);
            list.sort(Comparator.comparing(IssueDelayCarrierVO::getIssueId));
            UserDTO user = userMap.get(userId);
            if (user == null) {
                continue;
            }
            Map<String, String> paramMap = buildParamMap(list, projectMap.get(projectId), priorityMap, statusMap, userMap);
            MessageSender messageSender = delayTaskService.buildSender(0L, ISSUE_DELAY, paramMap, Arrays.asList(user));
            Map<String, Object> additionalInformationMap = new HashMap<>();
            additionalInformationMap.put(MessageAdditionalType.PARAM_PROJECT_ID.getTypeName(), projectId);
            messageSender.setAdditionalInformation(additionalInformationMap);
            messageSenders.add(messageSender);
        }
    }
    // 批量发送通知
    delayTaskService.batchSendMessage(messageSenders, 100);
    LOGGER.info("===> 问题延期发送消息定时任务完成");
}
Also used : MultiKeyMap(org.apache.commons.collections.map.MultiKeyMap) MessageSender(org.hzero.boot.message.entity.MessageSender) UserDTO(io.choerodon.agile.infra.dto.UserDTO) MultiKey(org.apache.commons.collections.keyvalue.MultiKey) IssueDTO(io.choerodon.agile.infra.dto.business.IssueDTO) MapIterator(org.apache.commons.collections.MapIterator) JobTask(io.choerodon.asgard.schedule.annotation.JobTask) TimedTask(io.choerodon.asgard.schedule.annotation.TimedTask)

Aggregations

MessageSender (org.hzero.boot.message.entity.MessageSender)32 Receiver (org.hzero.boot.message.entity.Receiver)11 ProjectVO (io.choerodon.agile.api.vo.ProjectVO)6 CommonException (io.choerodon.core.exception.CommonException)6 Async (org.springframework.scheduling.annotation.Async)6 UserDTO (io.choerodon.agile.infra.dto.UserDTO)4 SprintDTO (io.choerodon.agile.infra.dto.SprintDTO)2 JobTask (io.choerodon.asgard.schedule.annotation.JobTask)2 TimedTask (io.choerodon.asgard.schedule.annotation.TimedTask)2 Permission (io.choerodon.swagger.annotation.Permission)2 ApiOperation (io.swagger.annotations.ApiOperation)2 java.util (java.util)2 Collectors (java.util.stream.Collectors)2 DingTalkSender (org.hzero.boot.message.entity.DingTalkSender)2 ThreadFactoryBuilder (com.google.common.util.concurrent.ThreadFactoryBuilder)1 ProjectMessageVO (io.choerodon.agile.api.vo.ProjectMessageVO)1 SprintDelayCarrierVO (io.choerodon.agile.api.vo.SprintDelayCarrierVO)1 IssueDTO (io.choerodon.agile.infra.dto.business.IssueDTO)1 io.choerodon.asgard.api.vo (io.choerodon.asgard.api.vo)1 NoticeService (io.choerodon.asgard.app.service.NoticeService)1