瀏覽代碼

修改消息推送服务

wangyc 7 年之前
父節點
當前提交
c729edb6a7

+ 5 - 0
pom.xml

@@ -93,6 +93,11 @@
             <artifactId>mysql-connector-java</artifactId>
             <scope>runtime</scope>
         </dependency>
+        <dependency>
+            <groupId>com.uas.account</groupId>
+            <artifactId>account-common</artifactId>
+            <version>0.0.1-SNAPSHOT</version>
+        </dependency>
     </dependencies>
 
     <build>

+ 62 - 0
src/main/java/com/uas/ps/message/Application.java

@@ -1,14 +1,23 @@
 package com.uas.ps.message;
 
+import com.uas.account.web.AccountConfigurer;
 import com.uas.ps.core.util.ContextUtils;
+import com.uas.sso.web.SSOConfigurer;
 import java.io.File;
 import java.io.FileNotFoundException;
 import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
 import java.io.PrintStream;
+import java.util.Properties;
+import java.util.logging.Logger;
 import org.springframework.boot.SpringApplication;
 import org.springframework.boot.autoconfigure.SpringBootApplication;
 import org.springframework.boot.context.event.ApplicationPreparedEvent;
+import org.springframework.context.ApplicationContext;
 import org.springframework.context.ApplicationListener;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Profile;
 import org.springframework.web.servlet.config.annotation.EnableWebMvc;
 
 
@@ -21,6 +30,59 @@ import org.springframework.web.servlet.config.annotation.EnableWebMvc;
 @SpringBootApplication
 @EnableWebMvc
 public class Application {
+
+    private static final Logger logger = Logger.getLogger(SSOConfigurer.class.getName());
+
+    @Bean(name = "accountConfigurer")
+    @Profile(value = {"dev"})
+    public AccountConfigurer devAccountConfigurer(ApplicationContext applicationContext) {
+
+        AccountConfigurer configurer = new AccountConfigurer();
+//        configurer.setConfigPath("account-dev.properties");
+
+        // 解决Spring Boot应用不支持Resource.getFile方式读取配置文件的问题
+        Properties prop = getProperties(applicationContext, "classpath:config/account-dev.properties");
+
+        if (prop != null) {
+            configurer.initProperties(prop);
+        } else {
+            logger.severe("Initializing is not available AccountConfigLocation on the classpath");
+        }
+
+        return configurer;
+    }
+
+    @Bean(name = "accountConfigurer")
+    @Profile(value = {"test", "prod"})
+    public AccountConfigurer prodAccountConfigurer(ApplicationContext applicationContext) {
+
+        AccountConfigurer configurer = new AccountConfigurer();
+//        configurer.setConfigPath("account-dev.properties");
+
+        // 解决Spring Boot应用不支持Resource.getFile方式读取配置文件的问题
+        Properties prop = getProperties(applicationContext, "classpath:account-prod.properties");
+
+        if (prop != null) {
+            configurer.initProperties(prop);
+        } else {
+            logger.severe("Initializing is not available AccountConfigLocation on the classpath");
+        }
+
+        return configurer;
+    }
+
+    private Properties getProperties(ApplicationContext applicationContext, String location) {
+        Properties prop = null;
+        try (InputStream stream = applicationContext.getResource(location).getInputStream()) {
+            prop = new Properties();
+            prop.load(stream);
+        } catch (IOException e) {
+            e.printStackTrace();
+            logger.severe(" account read config file error. \n" + e.toString());
+        }
+        return prop;
+    }
+
     public static void main(String[] args) throws FileNotFoundException {
         File logFile = new File("logs/log.log");
         if (!logFile.getParentFile().exists()) {

+ 3 - 3
src/main/java/com/uas/ps/message/dao/MessageDao.java

@@ -28,12 +28,12 @@ public interface MessageDao extends JpaRepository<Message, Long>, JpaSpecificati
         Long consumerAppId);
 
     /**
-     * 通过接收应用id、阅读状态、发送状获取消息
+     * 通过接收应用id、阅读状态、发送状获取需要推送消息
      * @param consumerAppId 接收应用id
      * @param isRead 阅读状态
      * @param isSent 发送状态
      * @return
      */
-    @Query(nativeQuery = true, value = "select * from messages e where e.ms_isread = :isRead and e.ms_issent = :isSent and e.ms_id in (select ms_id from message$consumeapp a where a.app_id = :consumerAppId)")
-    List<Message> findByConsumerAppIdAndIsReadAndIsSent(@Param("consumerAppId") Long consumerAppId, @Param("isRead") Short isRead, @Param("isSent") Short isSent);
+    @Query(nativeQuery = true, value = "select * from messages e where e.ms_smsType <> 'DONT_SEND' and e.ms_isread = :isRead and e.ms_issent = :isSent and e.ms_id in (select ms_id from message$consumeapp a where a.app_id = :consumerAppId)")
+    List<Message> findByConsumerAppIdAndIsReadAndIsSentNeedToSend(@Param("consumerAppId") Long consumerAppId, @Param("isRead") Short isRead, @Param("isSent") Short isSent);
 }

+ 84 - 59
src/main/java/com/uas/ps/message/service/impl/MessageServiceImpl.java

@@ -2,14 +2,15 @@ package com.uas.ps.message.service.impl;
 
 
 import com.alibaba.fastjson.JSONObject;
+import com.uas.account.entity.User;
+import com.uas.account.util.AccountUtils;
+import com.uas.account.util.FlexJsonUtil;
 import com.uas.message.mail.domain.MailLog;
 import com.uas.ps.message.dao.AppDao;
 import com.uas.ps.message.dao.MessageDao;
 import com.uas.ps.message.domain.App;
-import com.uas.ps.message.domain.Enterprise;
 import com.uas.ps.message.domain.Message;
 import com.uas.ps.message.domain.SmsMessage;
-import com.uas.ps.message.domain.User;
 import com.uas.ps.message.exception.IllegalOperatorException;
 import com.uas.ps.message.exception.ParameterMissingException;
 import com.uas.ps.message.service.MessageService;
@@ -28,10 +29,8 @@ import java.util.List;
 import java.util.Map;
 import java.util.Set;
 import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.http.HttpEntity;
 import org.springframework.http.HttpHeaders;
 import org.springframework.http.MediaType;
-import org.springframework.http.ResponseEntity;
 import org.springframework.stereotype.Service;
 import org.springframework.util.CollectionUtils;
 import org.springframework.util.StringUtils;
@@ -107,13 +106,20 @@ public class MessageServiceImpl implements MessageService {
 
     @Override
     public Map<String, Object> sendMessage(String consumerApp) {
-        App consumerAppExists = appDao.findByName(consumerApp);
-        if (consumerApp == null) {
-            throw new IllegalOperatorException("接收应用不存在");
+        JSONObject consumer = FastjsonUtils.parseObject(consumerApp);
+        Object consumerAppObj = consumer.get("consumerApp");
+        App consumerAppExists = new App();
+        if (consumerAppObj != null && !StringUtils.isEmpty(String.valueOf(consumerAppObj))) {
+            consumerAppExists = appDao.findByName(String.valueOf(consumerAppObj));
+            if (consumerAppExists.getId() == null) {
+                throw new IllegalOperatorException("接收应用不存在");
+            }
+        } else {
+            throw new ParameterMissingException("接收应用信息为空");
         }
 
-        // 获取改应用应接收的未读、未发送消息
-        List<Message> messages = messageDao.findByConsumerAppIdAndIsReadAndIsSent(consumerAppExists.getId(),
+        // 获取改应用应接收的未读、未发送的需要推送的消息
+        List<Message> messages = messageDao.findByConsumerAppIdAndIsReadAndIsSentNeedToSend(consumerAppExists.getId(),
             Constant.NO, Constant.NO);
 
         Map<String, Object> resultMap = sendMessageByAPI(messages, consumerApp);
@@ -247,21 +253,26 @@ public class MessageServiceImpl implements MessageService {
 
         if (!CollectionUtils.isEmpty(messages)) {
             for (Message message : messages) {
-                // 发送邮件
-                if (message.getSmsType().contains(SMSType.MAIL)) {
-                    sendMail(message);
-                }
+                try {
+                    User receiver = AccountUtils.getImUserByUserUU(message.getReceiverUu());
+                    // 发送邮件
+                    if (message.getSmsType().contains(SMSType.MAIL)) {
+                        sendMail(message, receiver);
+                    }
 
-                // 发送短息
-                if (message.getSmsType().contains(SMSType.SM)) {
-                    sendSM(message);
-                }
+                    // 发送短息
+                    if (message.getSmsType().contains(SMSType.SM)) {
+                        sendSM(message, receiver);
+                    }
 
-                // 发送IM
-                if (message.getSmsType().contains(SMSType.IM)) {
-                    sendIM(message, consumerApp);
+                    // 发送IM
+                    if (message.getSmsType().contains(SMSType.IM)) {
+                        sendIM(message, receiver, consumerApp);
+                    }
+                    message.setIsSent(Constant.YES);
+                } catch (Exception e) {
+                    System.err.println(e.getMessage());
                 }
-                message.setIsSent(Constant.YES);
             }
             messageDao.save(messages);
         }
@@ -271,63 +282,77 @@ public class MessageServiceImpl implements MessageService {
     /**
      * 发送邮件
      * @param message 消息
+     * @param receiver 接收人
      */
-    private void sendMail(Message message) {
-        HttpHeaders headers = new HttpHeaders();
-        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
-        headers.setContentType(type);
-        headers.add("Accept", MediaType.APPLICATION_JSON.toString());
-
-        JSONObject object = new JSONObject();
-        object.put("templateId", message.getMailTemplate());
-        object.put("receiver", message.getReceiver());
-        object.put("params", message.getContent());
-
-        HttpEntity<String> formEntity = new HttpEntity<String>(object.toJSONString(), headers);
-        ResponseEntity<MailLog> responseEntity = restTemplate.postForEntity(MAIL_CONSOLE_HOST + MAIL_SEND_URL,
-            formEntity, MailLog.class);
+    private void sendMail(Message message, User receiver) {
+        if (receiver.getSecondUID() != null) {
+            HttpHeaders headers = new HttpHeaders();
+            MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
+            headers.setContentType(type);
+            headers.add("Accept", MediaType.APPLICATION_JSON.toString());
+
+            JSONObject object = new JSONObject();
+            object.put("templateId", message.getMailTemplate());
+            object.put("receiver", receiver.getSecondUID());
+            object.put("params", message.getContent());
+
+//            HttpEntity<String> formEntity = new HttpEntity<String>(, headers);
+            try {
+                ResponseWrap responseWrap = HttpUtil.doPost(MAIL_CONSOLE_HOST + MAIL_SEND_URL,
+                    FlexJsonUtil.toJson(object));
+            } catch (Exception e) {
+                e.printStackTrace();
+            }
+        }
     }
 
     /**
      * 发送短信
      * @param message 消息
+     * @param receiver 接收人
      */
-    private void sendSM(Message message) {
-        // TODO 账户中心获取用户手机号
-        if (message.getSmTemplate() != null) {
-            String templetId = message.getSmTemplate();
-            User user = FastjsonUtils.fromJson(message.getReceiver(), User.class);
-            if (user.getUserTel() != null) {
-                try {
-                    SmsMessage sms = new SmsMessage();
-                    List<Object> obj = new ArrayList<Object>();
-                    sms.setParams(obj);
-                    sms.setReceiver(user.getUserTel());
-                    sms.setTemplateId(templetId);
-                    com.uas.ps.message.util.HttpUtil.sendPost(messageUrl, FastjsonUtils.toJson(sms));
-                } catch (Exception e) {
-                    e.printStackTrace();
+    private void sendSM(Message message, User receiver) {
+        try {
+            if (!StringUtils.isEmpty(message.getSmTemplate()) && !StringUtils.isEmpty(receiver.getUid())) {
+                if (receiver.getUid() != null) {
+                    try {
+                        SmsMessage sms = new SmsMessage();
+                        List<Object> obj = new ArrayList<Object>();
+                        obj.add(receiver.getName());
+                        obj.add(receiver.getName());
+
+                        User sender = AccountUtils.getUserByImId(message.getSenderUu());
+                        obj.add(sender.getName() + "("
+                            + sender.getName() + ")");
+                        sms.setParams(obj);
+                        sms.setReceiver(receiver.getUid());
+                        sms.setTemplateId(message.getSmTemplate());
+                        com.uas.ps.message.util.HttpUtil.sendPost(messageUrl, FastjsonUtils.toJson(sms));
+                    } catch (Exception e) {
+                        e.printStackTrace();
+                    }
                 }
             }
+        } catch (Exception e) {
+
         }
     }
 
     /**
      * 发送IM
      * @param message 消息
+     * @param receiver 接收人
      * @param consumerApp 消费app
      */
-    private void sendIM(Message message, String consumerApp) {
+    private void sendIM(Message message, User receiver, String consumerApp) {
         Map<String, Object> params = new HashMap<>();
-        User user = FastjsonUtils.fromJson(message.getReceiver(), User.class);
-        Enterprise enterprise = user.getEnterprise();
-        if (user.getUserIMId() != null) {
-            params.put("master", enterprise.getEnName()); // 账套 公司名称
-            params.put("userid", String.valueOf(user.getUserIMId())); // 推送目标用户
-            String title = "";
-            params.put("title", title); // 推送标题
+        if (!StringUtils.isEmpty(receiver.getDialectUID())) {
+// TODO           params.put("master", enterprise.getEnName()); // 账套 公司名称
+            params.put("userid", receiver.getDialectUID()); // 推送目标用户
+//  TODO          String title = "";
+//            params.put("title", message.getType()); // 推送标题
             params.put("content", message.getContent()); // 正文
-            params.put("enUU", String.valueOf(enterprise.getUu())); // UU号
+            params.put("enUU", message.getReceiverEnuu()); // UU号
             params.put("url", ""); // 跳转链接地址
             // TODO
             params.put("platform", consumerApp); // 系统名称,ERP或

+ 3 - 0
src/main/resources/config/account-dev.properties

@@ -0,0 +1,3 @@
+### account center config, 
+account.us.save.url=http://10.10.100.133/api/userspace
+account.user.save.url=http://10.10.100.133/api/user

+ 3 - 0
src/main/resources/config/account-prod.properties

@@ -0,0 +1,3 @@
+### account center config,
+account.us.save.url=http://10.10.100.133:8080/api/userspace
+account.user.save.url=http://10.10.100.133:8080/api/user

+ 3 - 0
src/main/resources/config/account-test.properties

@@ -0,0 +1,3 @@
+### account center config,
+account.us.save.url=http://10.10.100.133:8080/api/userspace
+account.user.save.url=http://10.10.100.133:8080/api/user

+ 4 - 4
src/main/resources/config/application-test.properties

@@ -1,10 +1,10 @@
-datasource.url=jdbc:mysql://192.168.253.6:3306/public_resources?characterEncoding=utf-8&useSSL=false
+datasource.url=jdbc:mysql://10.10.100.18:3306/public_resources?characterEncoding=utf-8&useSSL=false
 datasource.username=root
-datasource.password=select111***
+datasource.password=select
 datasource.driverClassName=com.mysql.jdbc.Driver
 datasource.initialSize=1
 datasource.minIdle=1
-datasource.maxActive=20
+datasource.maxActive=100
 datasource.maxWait=60000
 datasource.timeBetweenEvictionRunsMillis=60000
 datasource.minEvictableIdleTimeMillis=300000
@@ -13,7 +13,7 @@ datasource.testWhileIdle=true
 datasource.testOnBorrow=true
 datasource.testOnReturn=false
 datasource.poolPreparedStatements=true
-datasource.timeBetweenLogStatsMillis=60000
+datasource.timeBetweenLogStatsMillis=300000
 datasource.maxPoolPreparedStatementPerConnectionSize=20
 datasource.filters=stat,slf4j
 datasource.connectionProperties=druid.stat.mergeSql=false;druid.stat.slowSqlMillis=5000