浏览代码

init commit

wangyc 8 年之前
父节点
当前提交
d7c5752ee2
共有 28 个文件被更改,包括 2242 次插入8 次删除
  1. 43 0
      pom.xml
  2. 2 0
      src/main/java/com/uas/ps/message/Application.java
  3. 127 0
      src/main/java/com/uas/ps/message/DruidDBConfiguration.java
  4. 29 0
      src/main/java/com/uas/ps/message/RepositoryConfiguration.java
  5. 61 0
      src/main/java/com/uas/ps/message/api/MessageController.java
  6. 20 0
      src/main/java/com/uas/ps/message/dao/AppDao.java
  7. 38 0
      src/main/java/com/uas/ps/message/dao/MessageDao.java
  8. 63 0
      src/main/java/com/uas/ps/message/domain/ApiModel/MessageModel.java
  9. 46 0
      src/main/java/com/uas/ps/message/domain/App.java
  10. 52 0
      src/main/java/com/uas/ps/message/domain/Enterprise.java
  11. 290 0
      src/main/java/com/uas/ps/message/domain/Message.java
  12. 47 0
      src/main/java/com/uas/ps/message/domain/SmsMessage.java
  13. 119 0
      src/main/java/com/uas/ps/message/domain/User.java
  14. 26 0
      src/main/java/com/uas/ps/message/exception/IllegalOperatorException.java
  15. 29 0
      src/main/java/com/uas/ps/message/exception/ParameterMissingException.java
  16. 35 0
      src/main/java/com/uas/ps/message/service/MessageService.java
  17. 319 0
      src/main/java/com/uas/ps/message/service/impl/MessageServiceImpl.java
  18. 11 0
      src/main/java/com/uas/ps/message/util/Constant.java
  19. 19 0
      src/main/java/com/uas/ps/message/util/ConsumeType.java
  20. 93 0
      src/main/java/com/uas/ps/message/util/FastjsonUtils.java
  21. 69 0
      src/main/java/com/uas/ps/message/util/HttpUtil.java
  22. 11 0
      src/main/java/com/uas/ps/message/util/ModelConvertUtil.java
  23. 26 0
      src/main/java/com/uas/ps/message/util/SMSType.java
  24. 24 0
      src/main/java/com/uas/ps/message/util/SplitChar.java
  25. 582 0
      src/main/java/com/uas/ps/message/util/account/HttpUtil.java
  26. 23 8
      src/main/resources/application.yml
  27. 19 0
      src/main/resources/config/application-dev.properties
  28. 19 0
      src/main/resources/config/application-test.properties

+ 43 - 0
pom.xml

@@ -34,10 +34,53 @@
             <groupId>org.springframework.boot</groupId>
             <artifactId>spring-boot-starter-security</artifactId>
         </dependency>
+        <!--jpa-->
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-data-jpa</artifactId>
+        </dependency>
         <dependency>
             <groupId>com.alibaba</groupId>
             <artifactId>fastjson</artifactId>
         </dependency>
+        <dependency>
+            <groupId>com.alibaba</groupId>
+            <artifactId>druid</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.hibernate</groupId>
+            <artifactId>hibernate-core</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.hibernate</groupId>
+            <artifactId>hibernate-ehcache</artifactId>
+        </dependency>
+        <!-- 邮件 -->
+        <dependency>
+            <groupId>com.uas.message</groupId>
+            <artifactId>message-mail-api</artifactId>
+            <version>0.0.1</version>
+        </dependency>
+        <!-- httpClient -->
+        <dependency>
+            <groupId>org.apache.httpcomponents</groupId>
+            <artifactId>httpclient</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.httpcomponents</groupId>
+            <artifactId>httpmime</artifactId>
+        </dependency>
+        <!-- 消息-->
+        <dependency>
+            <groupId>com.uas.message</groupId>
+            <artifactId>message-sms-api</artifactId>
+            <version>0.0.1</version>
+        </dependency>
+        <dependency>
+            <groupId>mysql</groupId>
+            <artifactId>mysql-connector-java</artifactId>
+            <scope>runtime</scope>
+        </dependency>
     </dependencies>
 
     <build>

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

@@ -3,8 +3,10 @@ package com.uas.ps.message;
 import com.uas.ps.message.util.ContextUtils;
 import org.springframework.boot.SpringApplication;
 import org.springframework.boot.autoconfigure.SpringBootApplication;
+import org.springframework.boot.autoconfigure.domain.EntityScan;
 import org.springframework.boot.context.event.ApplicationPreparedEvent;
 import org.springframework.context.ApplicationListener;
+import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
 import org.springframework.web.servlet.config.annotation.EnableWebMvc;
 
 import java.io.File;

+ 127 - 0
src/main/java/com/uas/ps/message/DruidDBConfiguration.java

@@ -0,0 +1,127 @@
+package com.uas.ps.message;
+
+import com.alibaba.druid.pool.DruidDataSource;
+import com.alibaba.druid.support.http.StatViewServlet;
+import com.alibaba.druid.support.http.WebStatFilter;
+import java.sql.SQLException;
+import javax.sql.DataSource;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.boot.web.servlet.FilterRegistrationBean;
+import org.springframework.boot.web.servlet.ServletRegistrationBean;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.context.annotation.Primary;
+
+@Configuration
+public class DruidDBConfiguration {
+
+    private Logger logger = LoggerFactory.getLogger(DruidDBConfiguration.class);
+
+    @Value("${datasource.url}")
+    private String url;
+
+    @Value("${datasource.username}")
+    private String username;
+
+    @Value("${datasource.password}")
+    private String password;
+
+    @Value("${datasource.driverClassName}")
+    private String driverClassName;
+
+    @Value("${datasource.initialSize}")
+    private int initialSize;
+
+    @Value("${datasource.minIdle}")
+    private int minIdle;
+
+    @Value("${datasource.maxActive}")
+    private int maxActive;
+
+    @Value("${datasource.maxWait}")
+    private int maxWait;
+
+    @Value("${datasource.timeBetweenEvictionRunsMillis}")
+    private int timeBetweenEvictionRunsMillis;
+
+    @Value("${datasource.minEvictableIdleTimeMillis}")
+    private int minEvictableIdleTimeMillis;
+
+    @Value("${datasource.validationQuery}")
+    private String validationQuery;
+
+    @Value("${datasource.testWhileIdle}")
+    private boolean testWhileIdle;
+
+    @Value("${datasource.testOnBorrow}")
+    private boolean testOnBorrow;
+
+    @Value("${datasource.testOnReturn}")
+    private boolean testOnReturn;
+
+    @Value("${datasource.timeBetweenLogStatsMillis}")
+    private int timeBetweenLogStatsMillis;
+
+    @Value("${datasource.poolPreparedStatements}")
+    private boolean poolPreparedStatements;
+
+    @Value("${datasource.maxPoolPreparedStatementPerConnectionSize}")
+    private int maxPoolPreparedStatementPerConnectionSize;
+
+    @Value("${datasource.filters}")
+    private String filters;
+
+    @Value("${datasource.connectionProperties}")
+    private String connectionProperties;
+
+    @Bean
+    @Primary
+    public DataSource dataSource() {
+        DruidDataSource dataSource = new DruidDataSource();
+
+        dataSource.setUrl(url);
+        dataSource.setUsername(username);
+        dataSource.setPassword(password);
+        dataSource.setDriverClassName(driverClassName);
+
+        // configuration
+        dataSource.setInitialSize(initialSize);
+        dataSource.setMinIdle(minIdle);
+        dataSource.setMaxActive(maxActive);
+        dataSource.setMaxWait(maxWait);
+        dataSource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
+        dataSource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
+        dataSource.setValidationQuery(validationQuery);
+        dataSource.setTestWhileIdle(testWhileIdle);
+        dataSource.setTestOnBorrow(testOnBorrow);
+        dataSource.setTestOnReturn(testOnReturn);
+        dataSource.setTimeBetweenLogStatsMillis(timeBetweenLogStatsMillis);
+        dataSource.setPoolPreparedStatements(poolPreparedStatements);
+        dataSource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);
+        try {
+            dataSource.setFilters(filters);
+        } catch (SQLException e) {
+            logger.error("数据源初始化失败: setFilters", e);
+        }
+        dataSource.setConnectionProperties(connectionProperties);
+        return dataSource;
+    }
+
+    @Bean
+    public ServletRegistrationBean servletRegistrationBean() {
+        return new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
+    }
+
+    @Bean
+    public FilterRegistrationBean filterRegistrationBean() {
+        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
+        filterRegistrationBean.setFilter(new WebStatFilter());
+        filterRegistrationBean.addUrlPatterns("/*");
+        filterRegistrationBean.addInitParameter("exclusions",
+                "*.js,*.gif,*.jpg,*.png,*.bmp,*.css,*.ico,*.html,/druid/*");
+        return filterRegistrationBean;
+    }
+
+}

+ 29 - 0
src/main/java/com/uas/ps/message/RepositoryConfiguration.java

@@ -0,0 +1,29 @@
+package com.uas.ps.message;
+
+import javax.sql.DataSource;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.context.annotation.Primary;
+import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
+import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
+
+/**
+ * @author sunyj
+ * @since 2018/1/13 16:26
+ */
+@Configuration
+@EnableJpaRepositories
+public class RepositoryConfiguration {
+
+    @Autowired
+    private DataSource dataSource;
+
+    @Bean
+    @Primary
+    public LocalContainerEntityManagerFactoryBean entityManagerFactory(EntityManagerFactoryBuilder builder) {
+        return builder.dataSource(dataSource)
+                .packages("com.uas.ps.message.domain").build();
+    }
+}

+ 61 - 0
src/main/java/com/uas/ps/message/api/MessageController.java

@@ -0,0 +1,61 @@
+package com.uas.ps.message.api;
+
+import com.uas.ps.message.domain.Message;
+import com.uas.ps.message.service.MessageService;
+import java.util.List;
+import java.util.Map;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.bind.annotation.RequestParam;
+import org.springframework.web.bind.annotation.RestController;
+
+/**
+ * Created by wangyc on 2018/1/13.
+ *
+ * @version 2018/1/13 15:36 wangyc
+ */
+@RestController
+@RequestMapping(value = "/messages")
+public class MessageController {
+
+    private final MessageService messageService;
+
+    @Autowired
+    private MessageController(MessageService messageService) {
+        this.messageService = messageService;
+    }
+
+    /**
+     * 获取消息
+     * @param receiver 收信人
+     * @param consumerApp 接收app
+     * @return
+     */
+    @RequestMapping(method = RequestMethod.GET, produces = "application/json")
+    public List<Message> getMessages(@RequestParam String receiver, String consumerApp) {
+        return messageService.getMessages(receiver, consumerApp);
+    }
+
+    /**
+     * 保存消息
+     * @param messages 消息
+     * @return
+     */
+    @RequestMapping(method = RequestMethod.POST, produces = "application/json")
+    public List<Message> saveMessages(@RequestBody String messages) {
+        // TODO 日志
+        return messageService.saveMessages(messages);
+    }
+
+    /**
+     * 推送消息
+     * @param consumerApp 接收消息app
+     * @return
+     */
+    @RequestMapping(value = "/send", method = RequestMethod.POST, produces = "application/json")
+    public Map<String, Object> sendMessage(@RequestBody String consumerApp) {
+        return messageService.sendMessage(consumerApp);
+    }
+}

+ 20 - 0
src/main/java/com/uas/ps/message/dao/AppDao.java

@@ -0,0 +1,20 @@
+package com.uas.ps.message.dao;
+
+import com.uas.ps.message.domain.App;
+import org.springframework.data.jpa.repository.JpaRepository;
+import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
+
+/**
+ * Created by wangyc on 2018/1/18.
+ *
+ * @version 2018/1/18 10:48 wangyc
+ */
+public interface AppDao extends JpaRepository<App, Long>, JpaSpecificationExecutor<App> {
+
+    /**
+     * 通过应用名称获取应用
+     * @param name 应用名称
+     * @return
+     */
+    App findByName(String name);
+}

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

@@ -0,0 +1,38 @@
+package com.uas.ps.message.dao;
+
+import com.uas.ps.message.domain.Message;
+import java.util.List;
+import org.springframework.data.jpa.repository.JpaRepository;
+import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
+import org.springframework.data.jpa.repository.Query;
+import org.springframework.stereotype.Repository;
+
+/**
+ * Created by wangyc on 2018/1/13.
+ *
+ * @version 2018/1/13 15:45 wangyc
+ */
+@Repository
+public interface MessageDao extends JpaRepository<Message, Long>, JpaSpecificationExecutor<Message> {
+
+    /**
+     * 通过接收人和接收应用获取消息
+     * @param receiverUu 接收人uu
+     * @param receiverEnuu 接收企业uu
+     * @param consumerAppId 接收应用id
+     * @return
+     */
+    @Query(nativeQuery = true, value = "select * from messages e where e.ms_receiveruu = :receiverUu and e.ms_receiverenuu = :receiverEnuu and e.id in (select ms_id from message$consumeapp a where a.app_id = :consumerAppId)")
+    List<Message> findByReceiverUuAndReceiverEnuuAndConsumerAppId(Long receiverUu, Long receiverEnuu,
+        Long consumerAppId);
+
+    /**
+     * 通过接收应用id、阅读状态、发送状态获取消息
+     * @param consumerAppId 接收应用id
+     * @param isRead 阅读状态
+     * @param isSent 发送状态
+     * @return
+     */
+    @Query(nativeQuery = true, value = "select * from messages e where e.ms_receiveruu = :receiverUu and e.ms_receiverenuu = :receiverEnuu and e.id in (select ms_id from message$consumeapp a where a.app_id = :consumerAppId)")
+    List<Message> findByConsumerAppIdAndIsReadAndIsSent(Long consumerAppId, Short isRead, Short isSent);
+}

+ 63 - 0
src/main/java/com/uas/ps/message/domain/ApiModel/MessageModel.java

@@ -0,0 +1,63 @@
+package com.uas.ps.message.domain.ApiModel;
+
+/**
+ * 消息
+ */
+public class MessageModel{
+    /**
+     * 消息类型
+     */
+    private String type;
+    /**
+     * 消息内容
+     */
+    private String content;
+    /**
+     * 消息接收者uu
+     */
+    private Long receiverUu;
+    /**
+     * 消息接收者企业uu
+     */
+    private Long receiverEnuu;
+    /**
+     * 消息发送者
+     */
+    private Long senderUu;
+    /**
+     * 消息发送者企业uu
+     */
+    private Long senderEnuu;
+    /**
+     * 来源应用
+     */
+    private String producerApp;
+    /**
+     * 消费类型(所有应用共享:"PUBLIC",单个应用独享:"SINGLE",多个应用共享:"MULTI")
+     */
+    private String consumeType;
+    /**
+     * 推送方式类型
+     * 邮件、短信、IM:"MAIL_AND_SM_AND_IM"
+     * 邮件、短信:"MAIL_AND_SM"
+     * 邮件、IM:"MAIL_AND_IM"
+     * 短信、IM:"SM_AND_IM"
+     * 邮件:"MAIL"
+     * 短信:"SM"
+     * IM:"IM"
+     * 不发送:"DONT_SEND"
+     */
+    private String smsType;
+    /**
+     * 邮件模板id
+     */
+    private String mailTemplate;
+    /**
+     * 短息模板id
+     */
+    private String smTemplate;
+    /**
+     * 接收应用(以","拼接应用名称)
+     */
+    private String consumerApp;
+}

+ 46 - 0
src/main/java/com/uas/ps/message/domain/App.java

@@ -0,0 +1,46 @@
+package com.uas.ps.message.domain;
+
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.GenerationType;
+import javax.persistence.Id;
+import javax.persistence.Table;
+
+/**
+ * 应用
+ * Created by wangyc on 2018/1/13.
+ *
+ * @version 2018/1/13 14:59 wangyc
+ */
+@Entity
+@Table(name = "apps")
+public class App {
+
+    @Id
+    @Column(name = "app_id")
+    @GeneratedValue(strategy = GenerationType.AUTO)
+    private Long id;
+
+    /**
+     * 应用名称
+     */
+    @Column(name = "app_name")
+    private String name;
+
+    public Long getId() {
+        return id;
+    }
+
+    public void setId(Long id) {
+        this.id = id;
+    }
+
+    public String getName() {
+        return name;
+    }
+
+    public void setName(String name) {
+        this.name = name;
+    }
+}

+ 52 - 0
src/main/java/com/uas/ps/message/domain/Enterprise.java

@@ -0,0 +1,52 @@
+/*CopyRright (c)2014: <www.usoftchina.com>
+ */
+package com.uas.ps.message.domain;
+
+import java.io.Serializable;
+
+/**
+ * 企业信息
+ * 
+ */
+public class Enterprise implements Serializable {
+
+	/**
+	 * 序列号
+	 */
+	private static final long serialVersionUID = 1L;
+
+	private Long uu;
+
+	/**
+	 * 公司名称
+	 */
+	private String enName;
+	/**
+	 * 简称
+	 */
+	private String enShortname;
+
+	public Long getUu() {
+		return uu;
+	}
+
+	public void setUu(Long uu) {
+		this.uu = uu;
+	}
+
+	public String getEnName() {
+		return enName;
+	}
+
+	public void setEnName(String enName) {
+		this.enName = enName;
+	}
+
+	public String getEnShortname() {
+		return enShortname;
+	}
+
+	public void setEnShortname(String enShortname) {
+		this.enShortname = enShortname;
+	}
+}

+ 290 - 0
src/main/java/com/uas/ps/message/domain/Message.java

@@ -0,0 +1,290 @@
+package com.uas.ps.message.domain;
+
+import java.io.Serializable;
+import java.util.Date;
+import java.util.Set;
+import javax.persistence.CascadeType;
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.FetchType;
+import javax.persistence.GeneratedValue;
+import javax.persistence.GenerationType;
+import javax.persistence.Id;
+import javax.persistence.JoinColumn;
+import javax.persistence.JoinTable;
+import javax.persistence.ManyToMany;
+import javax.persistence.OrderBy;
+import javax.persistence.Table;
+import org.hibernate.annotations.Cache;
+import org.hibernate.annotations.CacheConcurrencyStrategy;
+
+/**
+ * 消息
+ * Created by wangyc on 2018/1/13.
+ *
+ * @version 2018/1/13 11:26 wangyc
+ */
+@Entity
+@Table(name = "messages")
+public class Message implements Serializable {
+
+    private static final long serialVersionUID = -1150575839820149569L;
+
+    @Id
+    @Column(name = "ms_id")
+    @GeneratedValue(strategy = GenerationType.AUTO)
+    private Long id;
+
+    /**
+     * 消息类型
+     */
+    @Column(name = "ms_type")
+    private String type;
+
+    /**
+     * 消息内容
+     */
+    @Column(name = "ms_content")
+    private String content;
+
+    /**
+     * 消息接受者json信息
+     */
+    @Column(name = "ms_receiver", columnDefinition = "TEXT")
+    private String receiver;
+
+    /**
+     * 消息接收者uu
+     */
+    @Column(name = "ms_receiveruu")
+    private Long receiverUu;
+
+    /**
+     * 消息接收者企业uu
+     */
+    @Column(name = "ms_receiverenuu")
+    private Long receiverEnuu;
+
+    /**
+     * 消息发送者json信息
+     */
+    @Column(name = "ms_sender", columnDefinition = "TEXT")
+    private String sender;
+
+    /**
+     * 消息发送者
+     */
+    @Column(name = "ms_senderuu")
+    private Long senderUu;
+
+    /**
+     * 消息发送者企业uu
+     */
+    @Column(name = "ms_senderenuu")
+    private Long senderEnuu;
+
+    /**
+     * 阅读状态
+     * 1 已阅
+     * 0 未读
+     */
+    @Column(name = "ms_isread")
+    private Short isRead;
+
+    /**
+     * 来源应用id
+     */
+    @Column(name = "ms_producerApp")
+    private Long producerApp;
+
+    /**
+     * 消费类型
+     */
+    @Column(name = "ms_consumeType")
+    private String consumeType;
+
+    /**
+     * 生成时间
+     */
+    @Column(name = "ms_createTime")
+    private Date createTime;
+
+    /**
+     * 推送方式类型
+     */
+    @Column(name = "ms_smsType")
+    private String smsType;
+
+    /**
+     * 邮件模板id
+     */
+    @Column(name = "ms_mailtemplate")
+    private String mailTemplate;
+
+    /**
+     * 短息模板id
+     */
+    @Column(name = "ms_smtemplate")
+    private String smTemplate;
+
+    /**
+     * 是否已推送
+     * 1 已阅
+     * 0 未读
+     */
+    @Column(name = "ms_issent")
+    private Short isSent;
+
+    /**
+     * 接收应用
+     */
+    @ManyToMany(cascade = { CascadeType.REFRESH, CascadeType.REMOVE }, fetch = FetchType.EAGER)
+    @JoinTable(name = "message$consumeapp", joinColumns = @JoinColumn(name = "ms_id", referencedColumnName = "ms_id"), inverseJoinColumns = @JoinColumn(name = "app_id", referencedColumnName = "app_id"))
+    @OrderBy("uu")
+    @Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
+    private Set<App> consumerApp;
+
+    public Long getId() {
+        return id;
+    }
+
+    public void setId(Long id) {
+        this.id = id;
+    }
+
+    public String getType() {
+        return type;
+    }
+
+    public void setType(String type) {
+        this.type = type;
+    }
+
+    public String getContent() {
+        return content;
+    }
+
+    public void setContent(String content) {
+        this.content = content;
+    }
+
+    public Long getReceiverUu() {
+        return receiverUu;
+    }
+
+    public void setReceiverUu(Long receiverUu) {
+        this.receiverUu = receiverUu;
+    }
+
+    public Long getReceiverEnuu() {
+        return receiverEnuu;
+    }
+
+    public void setReceiverEnuu(Long receiverEnuu) {
+        this.receiverEnuu = receiverEnuu;
+    }
+
+    public String getReceiver() {
+        return receiver;
+    }
+
+    public void setReceiver(String receiver) {
+        this.receiver = receiver;
+    }
+
+    public Long getSenderUu() {
+        return senderUu;
+    }
+
+    public void setSenderUu(Long senderUu) {
+        this.senderUu = senderUu;
+    }
+
+    public Long getSenderEnuu() {
+        return senderEnuu;
+    }
+
+    public void setSenderEnuu(Long senderEnuu) {
+        this.senderEnuu = senderEnuu;
+    }
+
+    public String getSender() {
+        return sender;
+    }
+
+    public void setSender(String sender) {
+        this.sender = sender;
+    }
+
+    public Short getIsRead() {
+        return isRead;
+    }
+
+    public void setIsRead(Short isRead) {
+        this.isRead = isRead;
+    }
+
+    public Long getProducerApp() {
+        return producerApp;
+    }
+
+    public void setProducerApp(Long producerApp) {
+        this.producerApp = producerApp;
+    }
+
+    public String getConsumeType() {
+        return consumeType;
+    }
+
+    public void setConsumeType(String consumeType) {
+        this.consumeType = consumeType;
+    }
+
+    public Date getCreateTime() {
+        return createTime;
+    }
+
+    public void setCreateTime(Date createTime) {
+        this.createTime = createTime;
+    }
+
+    public String getSmsType() {
+        return smsType;
+    }
+
+    public void setSmsType(String smsType) {
+        this.smsType = smsType;
+    }
+
+    public String getMailTemplate() {
+        return mailTemplate;
+    }
+
+    public void setMailTemplate(String mailTemplate) {
+        this.mailTemplate = mailTemplate;
+    }
+
+    public String getSmTemplate() {
+        return smTemplate;
+    }
+
+    public void setSmTemplate(String smTemplate) {
+        this.smTemplate = smTemplate;
+    }
+
+    public Short getIsSent() {
+        return isSent;
+    }
+
+    public void setIsSent(Short isSent) {
+        this.isSent = isSent;
+    }
+
+    public Set<App> getConsumerApp() {
+        return consumerApp;
+    }
+
+    public void setConsumerApp(Set<App> consumerApp) {
+        this.consumerApp = consumerApp;
+    }
+}

+ 47 - 0
src/main/java/com/uas/ps/message/domain/SmsMessage.java

@@ -0,0 +1,47 @@
+package com.uas.ps.message.domain;
+
+import java.util.List;
+
+public class SmsMessage {
+
+	/**
+	 * 接收方电话
+	 */
+	private String receiver;
+
+	/**
+	 * 参数
+	 */
+	private List<Object> params;
+
+	/**
+	 * 模板id
+	 */
+	private String templateId;
+
+	public String getReceiver() {
+		return receiver;
+	}
+
+	public void setReceiver(String receiver) {
+		this.receiver = receiver;
+	}
+
+	public List<Object> getParams() {
+		return params;
+	}
+
+	public void setParams(List<Object> params) {
+		this.params = params;
+	}
+
+	public String getTemplateId() {
+		return templateId;
+	}
+
+	public void setTemplateId(String templateId) {
+		this.templateId = templateId;
+	}
+
+
+}

+ 119 - 0
src/main/java/com/uas/ps/message/domain/User.java

@@ -0,0 +1,119 @@
+package com.uas.ps.message.domain;
+
+import java.io.Serializable;
+
+/**
+ * 用户信息
+ *
+ */
+public class User implements Serializable {
+
+	/**
+	 * 
+	 */
+	private static final long serialVersionUID = 1L;
+
+	/**
+	 * uu号,ID
+	 */
+	private Long userUU;
+
+	/**
+	 * 用户名
+	 */
+	private String userName;
+
+	/**
+	 * 邮箱
+	 */
+	private String userEmail;
+
+	/**
+	 * 手机号
+	 */
+	private String userTel;
+
+	/**
+	 * 性别
+	 */
+	private String userSex;
+
+	/**
+	 * 是否管理员
+	 */
+	private Short issys;
+
+	/**
+	 * imid
+	 */
+	private Long userIMId;
+
+	/**
+	 * 所属当前登录公司
+	 */
+	private Enterprise enterprise;
+
+	public Long getUserUU() {
+		return userUU;
+	}
+
+	public void setUserUU(Long userUU) {
+		this.userUU = userUU;
+	}
+
+	public String getUserName() {
+		return userName;
+	}
+
+	public void setUserName(String userName) {
+		this.userName = userName;
+	}
+
+	public String getUserEmail() {
+		return userEmail;
+	}
+
+	public void setUserEmail(String userEmail) {
+		this.userEmail = userEmail;
+	}
+
+	public String getUserTel() {
+		return userTel;
+	}
+
+	public void setUserTel(String userTel) {
+		this.userTel = userTel;
+	}
+
+	public String getUserSex() {
+		return userSex;
+	}
+
+	public void setUserSex(String userSex) {
+		this.userSex = userSex;
+	}
+
+	public Short getIssys() {
+		return issys;
+	}
+
+	public void setIssys(Short issys) {
+		this.issys = issys;
+	}
+
+	public Long getUserIMId() {
+		return userIMId;
+	}
+
+	public void setUserIMId(Long userIMId) {
+		this.userIMId = userIMId;
+	}
+
+	public Enterprise getEnterprise() {
+		return enterprise;
+	}
+
+	public void setEnterprise(Enterprise enterprise) {
+		this.enterprise = enterprise;
+	}
+}

+ 26 - 0
src/main/java/com/uas/ps/message/exception/IllegalOperatorException.java

@@ -0,0 +1,26 @@
+package com.uas.ps.message.exception;
+
+/**
+ * Created by wangyc on 2018/1/18.
+ *
+ * @version 2018/1/18 16:12 wangyc
+ */
+public class IllegalOperatorException extends RuntimeException {
+    private static final long serialVersionUID = 3958657497510022539L;
+
+    public IllegalOperatorException() {
+        super("非法操作");
+    }
+
+    public IllegalOperatorException(String paramString) {
+        super(paramString);
+    }
+
+    public IllegalOperatorException(String paramString, Throwable paramThrowable) {
+        super(paramString, paramThrowable);
+    }
+
+    public IllegalOperatorException(Throwable paramThrowable) {
+        super(paramThrowable);
+    }
+}

+ 29 - 0
src/main/java/com/uas/ps/message/exception/ParameterMissingException.java

@@ -0,0 +1,29 @@
+package com.uas.ps.message.exception;
+
+/**
+ * 参数缺失异常
+ * 
+ * @author wangyc
+ * 
+ */
+public class ParameterMissingException extends RuntimeException {
+
+	private static final long serialVersionUID = 8006624439061017634L;
+
+	public ParameterMissingException() {
+		super("参数缺失");
+	}
+
+	public ParameterMissingException(String paramString) {
+		super(paramString);
+	}
+
+	public ParameterMissingException(String paramString, Throwable paramThrowable) {
+		super(paramString, paramThrowable);
+	}
+
+	public ParameterMissingException(Throwable paramThrowable) {
+		super(paramThrowable);
+	}
+
+}

+ 35 - 0
src/main/java/com/uas/ps/message/service/MessageService.java

@@ -0,0 +1,35 @@
+package com.uas.ps.message.service;
+
+import com.uas.ps.message.domain.Message;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Created by wangyc on 2018/1/13.
+ *
+ * @version 2018/1/13 15:44 wangyc
+ */
+public interface MessageService {
+
+    /**
+     * 获取消息
+     * @param receiver 收信人
+     * @param consumerApp 接收app
+     * @return
+     */
+    List<Message> getMessages(String receiver, String consumerApp);
+
+    /**
+     * 保存消息
+     * @param messages 消息
+     * @return
+     */
+    List<Message> saveMessages(String messages);
+
+    /**
+     * 推送消息
+     * @param consumerApp 接收消息app
+     * @return
+     */
+    Map<String, Object> sendMessage(String consumerApp);
+}

+ 319 - 0
src/main/java/com/uas/ps/message/service/impl/MessageServiceImpl.java

@@ -0,0 +1,319 @@
+package com.uas.ps.message.service.impl;
+
+import com.alibaba.fastjson.JSONObject;
+import com.uas.message.mail.service.MailService;
+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;
+import com.uas.ps.message.util.Constant;
+import com.uas.ps.message.util.ConsumeType;
+import com.uas.ps.message.util.FastjsonUtils;
+import com.uas.ps.message.util.SMSType;
+import com.uas.ps.message.util.SplitChar;
+import com.uas.ps.message.util.account.HttpUtil;
+import com.uas.ps.message.util.account.HttpUtil.ResponseWrap;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Service;
+import org.springframework.util.CollectionUtils;
+import org.springframework.util.StringUtils;
+
+/**
+ * Created by wangyc on 2018/1/13.
+ *
+ * @version 2018/1/13 15:44 wangyc
+ */
+@Service
+public class MessageServiceImpl implements MessageService {
+
+    private final MessageDao messageDao;
+
+    private final AppDao appDao;
+
+    private final MailService mailService;
+
+    private static final String EMAIL_REGEX = "\\w[-\\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\\.)+[A-Za-z]{2,14}";
+
+    private static final String TEL_REGEXP = "^((\\(\\d{3}\\))|(\\d{3}\\-))?(13|15|18|17)\\d{9}$";
+
+    private final static String PROD_URL = "http://113.105.74.140:8092/tigase/baiduPush";
+
+    /**
+     * 短信接口
+     */
+    private final String messageUrl = "http://message.ubtob.com/sms/send";
+
+    @Autowired
+    public MessageServiceImpl(MessageDao messageDao, AppDao appDao, MailService mailService) {
+        this.messageDao = messageDao;
+        this.mailService = mailService;
+        this.appDao = appDao;
+    }
+
+    @Override
+    public List<Message> getMessages(String receiver, String consumerApp) {
+        List<Message> messages = new ArrayList<>();
+        User user = FastjsonUtils.fromJson(receiver, User.class);
+        App consumerAppExists = appDao.findByName(consumerApp);
+        if (consumerApp == null) {
+            throw new IllegalOperatorException("接收应用不存在");
+        }
+
+        if (user.getUserUU() != null && user.getEnterprise() != null && user.getEnterprise().getUu() != null) {
+            messages = messageDao.findByReceiverUuAndReceiverEnuuAndConsumerAppId(user.getUserUU(),
+                user.getEnterprise().getUu(), consumerAppExists.getId());
+        }
+        return messages;
+    }
+
+    @Override
+    public List<Message> saveMessages(String messages) {
+        List<JSONObject> jsonObjects = FastjsonUtils.fromJsonArray(messages, JSONObject.class);
+        List<Message> messageList = convertFromJsonObj(jsonObjects);
+        return messageDao.save(messageList);
+    }
+
+    @Override
+    public Map<String, Object> sendMessage(String consumerApp) {
+        App consumerAppExists = appDao.findByName(consumerApp);
+        if (consumerApp == null) {
+            throw new IllegalOperatorException("接收应用不存在");
+        }
+
+        // 获取改应用应接收的未读、未发送消息
+        List<Message> messages = messageDao.findByConsumerAppIdAndIsReadAndIsSent(consumerAppExists.getId(), Constant.NO, Constant.NO);
+
+        Map<String, Object> resultMap = sendMessageByAPI(messages, consumerApp);
+        return resultMap;
+    }
+
+    /**
+     * jsonObject转换为Message
+     * @param jsonObjects jsonObjects
+     * @return messages
+     */
+    private List<Message> convertFromJsonObj(List<JSONObject> jsonObjects) {
+        List<Message> messages = new ArrayList<>();
+        for (JSONObject jsonObject : jsonObjects) {
+            Message message = new Message();
+
+            // 消息内容
+            Object content = jsonObject.get("content");
+            if (StringUtils.isEmpty(content)) {
+                throw new ParameterMissingException("消息内容为空");
+            } else {
+                message.setContent(String.valueOf(content));
+            }
+
+            // 发送人
+            Object sender = jsonObject.get("sender");
+            if (StringUtils.isEmpty(sender)) {
+                throw new ParameterMissingException("发送人为空");
+            } else {
+                User senderUser = FastjsonUtils.fromJson(String.valueOf(sender), User.class);
+                if (senderUser.getUserUU() == null || senderUser.getEnterprise() == null
+                    || senderUser.getEnterprise().getUu() == null) {
+                    throw new ParameterMissingException("发送人为空");
+                } else {
+                    message.setSenderUu(senderUser.getUserUU());
+                    message.setSenderEnuu(senderUser.getEnterprise().getUu());
+                }
+            }
+
+            // 接收人
+            Object receiver = jsonObject.get("receiver");
+            if (StringUtils.isEmpty(receiver)) {
+                throw new ParameterMissingException("接收人为空");
+            } else {
+                User receiverUser = FastjsonUtils.fromJson(String.valueOf(sender), User.class);
+                if (receiverUser.getUserUU() == null || receiverUser.getEnterprise() == null
+                    || receiverUser.getEnterprise().getUu() == null) {
+                    throw new ParameterMissingException("接收人为空");
+                } else {
+                    message.setReceiverUu(receiverUser.getUserUU());
+                    message.setReceiverEnuu(receiverUser.getEnterprise().getUu());
+                }
+            }
+
+            // 发送应用
+            Object produceApp = jsonObject.get("produceApp");
+            if (StringUtils.isEmpty(produceApp)) {
+                throw new ParameterMissingException("发送应用为空");
+            } else {
+                App app = appDao.findByName(String.valueOf(produceApp));
+                if (app == null) {
+                    throw new ParameterMissingException("发送应用为空");
+                }
+                message.setProducerApp(app.getId());
+            }
+
+            // 接收应用
+            Object consumerType = jsonObject.get("consumerType");
+            if (StringUtils.isEmpty(consumerType)) {
+                throw new ParameterMissingException("接收应用类型为空");
+            } else {
+                String type = String.valueOf(consumerType);
+                // 消息接收类型为公共,即所有子应用共享
+                if (ConsumeType.PUBLIC.equals(type)) {
+                    List<App> apps = appDao.findAll();
+                    message.setConsumerApp(new HashSet<>(apps));
+                    message.setConsumeType(type);
+                } else {
+                    Object consumerApp = jsonObject.get("consumerApp");
+                    if (consumerApp == null) {
+                        throw new ParameterMissingException("接收应用为空");
+                    } else {
+                        // 取出通过逗号拼接的接收应用
+                        String[] consumers = StringUtils.split(String.valueOf(consumerApp), SplitChar.COMMA);
+                        if (consumers.length < 1) {
+                            throw new ParameterMissingException("接收应用为空");
+                        }
+
+                        Set<App> consumerApps = new HashSet<>();
+                        for (String consumer : consumers) {
+                            App app = appDao.findByName(consumer);
+                            consumerApps.add(app);
+                        }
+
+                        message.setConsumerApp(consumerApps);
+                        message.setConsumeType(consumers.length > 1 ? ConsumeType.MULTI : ConsumeType.SINGLE);
+                    }
+                }
+            }
+
+            // 消息类型(暂时未定)
+            Object type = jsonObject.get("type");
+            if (type != null && !StringUtils.isEmpty(type)) {
+                message.setType(String.valueOf(type));
+            }
+
+            // 推送类型
+            Object smsType = jsonObject.get("smsType");
+            if (smsType != null && !StringUtils.isEmpty(smsType)) {
+                message.setSmsType(String.valueOf(smsType));
+            } else {
+                message.setSmsType(SMSType.DONT_SEND);
+            }
+
+            message.setIsRead(Constant.NO);
+            message.setCreateTime(new Date());
+            message.setIsSent(Constant.NO);
+
+            messages.add(message);
+        }
+        return messages;
+    }
+
+    /**
+     * 推送消息(调用邮件、短信、IM接口)
+     * @param messages 消息
+     * @param consumerApp 消费app
+     * @return
+     */
+    private Map<String, Object> sendMessageByAPI(List<Message> messages, String consumerApp) {
+        Map<String, Object> resultMap = new HashMap<>();
+
+        if (!CollectionUtils.isEmpty(messages)) {
+            for (Message message : messages) {
+                // 发送邮件
+                if (message.getSmsType().contains(SMSType.MAIL)) {
+                    sendMail(message);
+                }
+
+                // 发送短息
+                if (message.getSmsType().contains(SMSType.SM)) {
+                    sendSM(message);
+                }
+
+                // 发送IM
+                if (message.getSmsType().contains(SMSType.IM)) {
+                    sendIM(message, consumerApp);
+                }
+            }
+        }
+        return resultMap;
+    }
+
+    /**
+     * 发送邮件
+     * @param message 消息
+     */
+    private void sendMail(Message message) {
+        Map<String, Object> model = new HashMap<>();
+        // TODO 账户中心获取用户邮箱
+        String templetId = "";
+        User user = FastjsonUtils.fromJson(message.getReceiver(), User.class);
+        if (user.getUserEmail() != null && user.getUserEmail().matches(EMAIL_REGEX)) {
+            try {
+                mailService.send(templetId, user.getUserEmail(), model);
+            } catch (Exception e) {
+                e.printStackTrace();
+            }
+        }
+    }
+
+    /**
+     * 发送短信
+     * @param message 消息
+     */
+    private void sendSM(Message message) {
+        // TODO 账户中心获取用户手机号
+        String templetId = "";
+        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();
+            }
+        }
+    }
+
+    /**
+     * 发送IM
+     * @param message 消息
+     */
+    private void sendIM(Message message, 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); // 推送标题
+            params.put("content", message.getContent()); // 正文
+            params.put("enUU", String.valueOf(enterprise.getUu())); // UU号
+            params.put("url", ""); // 跳转链接地址
+            // TODO
+            params.put("platform", consumerApp); // 系统名称,ERP或
+            try {
+                ResponseWrap res = HttpUtil.doPost(PROD_URL, params);
+                if (!res.isSuccess()) {
+                    throw new Exception(res.getContent());
+                } else {
+                }
+            } catch (Exception e) {
+                e.printStackTrace();
+            }
+        }
+    }
+}

+ 11 - 0
src/main/java/com/uas/ps/message/util/Constant.java

@@ -0,0 +1,11 @@
+package com.uas.ps.message.util;
+
+/**
+ * Created by wangyc on 2018/1/18.
+ *
+ * @version 2018/1/18 15:54 wangyc
+ */
+public class Constant {
+    public static final Short YES = 1;
+    public static final Short NO = 0;
+}

+ 19 - 0
src/main/java/com/uas/ps/message/util/ConsumeType.java

@@ -0,0 +1,19 @@
+package com.uas.ps.message.util;
+
+/**
+ * 消费应用个数类型
+ * Created by wangyc on 2018/1/18.
+ *
+ * @version 2018/1/18 10:13 wangyc
+ */
+public class ConsumeType {
+
+    // 公共(所有应用)
+    public static final String PUBLIC = "PUBLIC";
+
+    // 单个应用独享
+    public static final String SINGLE = "SINGLE";
+
+    // 多个应用共享
+    public static final String MULTI = "MULTI";
+}

+ 93 - 0
src/main/java/com/uas/ps/message/util/FastjsonUtils.java

@@ -0,0 +1,93 @@
+package com.uas.ps.message.util;
+
+import com.alibaba.fastjson.JSON;
+import com.alibaba.fastjson.JSONArray;
+import com.alibaba.fastjson.JSONObject;
+import com.alibaba.fastjson.parser.Feature;
+import com.alibaba.fastjson.serializer.SerializerFeature;
+import java.util.List;
+
+/**
+ * alibaba fastjson工具类封装
+ * @author yingp
+ * @see JSON
+ *
+ */
+public class FastjsonUtils {
+
+	public static Feature DEFAULT_PARSER_FEATURE = Feature.DisableCircularReferenceDetect;
+	public static SerializerFeature DEFAULT_SERIAL_FEATURE = SerializerFeature.DisableCircularReferenceDetect;
+
+	/**
+	 * 把JSON文本parse为JSONObject或者JSONArray
+	 * 
+	 * @param text text
+	 * @return
+	 */
+	public static Object parse(String text) {
+		return JSON.parse(text, DEFAULT_PARSER_FEATURE);
+	}
+
+	/**
+	 * 把JSON文本parse成JSONObject
+	 * 
+	 * @param text text
+	 * @return
+	 */
+	public static final JSONObject parseObject(String text) {
+		return JSON.parseObject(text, DEFAULT_PARSER_FEATURE);
+	}
+
+	/**
+	 * 把JSON文本parse为JavaBean
+	 * 
+	 * @param text text
+	 * @param clazz clazz
+	 * @return
+	 */
+	public static final <T> T fromJson(String text, Class<T> clazz) {
+		return JSON.parseObject(text, clazz, DEFAULT_PARSER_FEATURE);
+	}
+
+	/**
+	 * 把JSON文本parse成JSONArray
+	 * 
+	 * @param text text
+	 * @return
+	 */
+	public static final JSONArray fromJsonArray(String text) {
+		return JSON.parseArray(text);
+	}
+
+	/**
+	 * 把JSON文本parse成JavaBean集合
+	 * 
+	 * @param  text text
+	 * @param clazz clazz
+	 * @return
+	 */
+	public static final <T> List<T> fromJsonArray(String text, Class<T> clazz) {
+		return JSON.parseArray(text, clazz);
+	}
+
+	/**
+	 * 将JavaBean序列化为JSON文本
+	 * 
+	 * @param object object
+	 * @return
+	 */
+	public static final String toJson(Object object) {
+		return JSON.toJSONString(object, DEFAULT_SERIAL_FEATURE);
+	}
+
+	/**
+	 * 将JavaBean转换为JSONObject或者JSONArray。
+	 * 
+	 * @param javaObject javaObject
+	 * @return
+	 */
+	public static final Object toObject(Object javaObject) {
+		return JSON.toJSON(javaObject);
+	}
+
+}

+ 69 - 0
src/main/java/com/uas/ps/message/util/HttpUtil.java

@@ -0,0 +1,69 @@
+package com.uas.ps.message.util;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.io.PrintWriter;
+import java.net.URL;
+import java.net.URLConnection;
+
+/**
+ * HTTP工具类,封装http请求
+ * 
+ * @author suntg
+ * @date 2015年3月5日14:20:40
+ */
+public class HttpUtil {
+	/**
+	 * 暂时先使用这种方法(短信接口调用)
+	 * @param url url
+	 * @param param param
+	 * @return
+	 */
+	public static String sendPost(String url, String param) {
+		PrintWriter out = null;
+		BufferedReader in = null;
+		String result = "";
+		try {
+			URL realUrl = new URL(url);
+			// 打开和URL之间的连接
+			URLConnection conn = realUrl.openConnection();
+			// 设置通用的请求属性
+			conn.setRequestProperty("content-type", "application/json");
+			conn.setRequestProperty("accept", "*/*");
+			conn.setRequestProperty("connection", "Keep-Alive");
+			conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
+			// 发送POST请求必须设置如下两行
+			conn.setDoOutput(true);
+			conn.setDoInput(true);
+			// 获取URLConnection对象对应的输出流
+			out = new PrintWriter(conn.getOutputStream());
+			// 发送请求参数
+			out.print(param);
+			// flush输出流的缓冲
+			out.flush();
+			// 定义BufferedReader输入流来读取URL的响应
+			in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
+			String line;
+			while ((line = in.readLine()) != null) {
+				result += line;
+			}
+		} catch (Exception e) {
+			e.printStackTrace();
+		}
+		// 使用finally块来关闭输出流、输入流
+		finally {
+			try {
+				if (out != null) {
+					out.close();
+				}
+				if (in != null) {
+					in.close();
+				}
+			} catch (IOException ex) {
+				ex.printStackTrace();
+			}
+		}
+		return result;
+	}
+}

+ 11 - 0
src/main/java/com/uas/ps/message/util/ModelConvertUtil.java

@@ -0,0 +1,11 @@
+package com.uas.ps.message.util;
+
+/**
+ * model转换
+ * Created by wangyc on 2018/1/13.
+ *
+ * @version 2018/1/13 17:00 wangyc
+ */
+public class ModelConvertUtil {
+
+}

+ 26 - 0
src/main/java/com/uas/ps/message/util/SMSType.java

@@ -0,0 +1,26 @@
+package com.uas.ps.message.util;
+
+/**
+ * Created by wangyc on 2018/1/16.
+ * 消息推送类型
+ * @version 2018/1/16 14:02 wangyc
+ */
+public class SMSType {
+
+    // 邮件、短信、IM
+    public static final String MAIL_AND_SM_AND_IM = "MAIL_AND_SM_AND_IM";
+    // 邮件、短信
+    public static final String MAIL_AND_SM = "MAIL_AND_SM";
+    // 邮件、IM
+    public static final String MAIL_AND_IM = "MAIL_AND_IM";
+    // 短信、IM
+    public static final String SM_AND_IM = "SM_AND_IM";
+    // 邮件
+    public static final String MAIL = "MAIL";
+    // 短信
+    public static final String SM = "SM";
+    // IM
+    public static final String IM = "IM";
+    // 不发送
+    public static final String DONT_SEND = "DONT_SEND";
+}

+ 24 - 0
src/main/java/com/uas/ps/message/util/SplitChar.java

@@ -0,0 +1,24 @@
+package com.uas.ps.message.util;
+
+/**
+ * 常用的分割字符
+ */
+public class SplitChar {
+	
+	/**
+	 * 连字符  - 字符串
+	 */
+	public static final String HYPHEN = "-";
+
+	
+	/**
+	 * 逗号 , 字符串
+	 */
+	public static final String COMMA = ",";
+
+	/**
+	 * 与字符  & 字符串
+	 */
+	public static final String AND = "&";
+
+}

+ 582 - 0
src/main/java/com/uas/ps/message/util/account/HttpUtil.java

@@ -0,0 +1,582 @@
+package com.uas.ps.message.util.account;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.OutputStreamWriter;
+import java.io.PrintWriter;
+import java.io.UnsupportedEncodingException;
+import java.net.HttpURLConnection;
+import java.net.URL;
+import java.net.URLDecoder;
+import java.net.URLEncoder;
+import java.security.SecureRandom;
+import java.security.cert.CertificateException;
+import java.security.cert.X509Certificate;
+import java.util.Map;
+import java.util.logging.Logger;
+import javax.net.ssl.HostnameVerifier;
+import javax.net.ssl.HttpsURLConnection;
+import javax.net.ssl.KeyManager;
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.SSLSession;
+import javax.net.ssl.TrustManager;
+import javax.net.ssl.X509TrustManager;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+/**
+ * <p>
+ * HTTP工具类
+ * </p>
+ * 
+ */
+public class HttpUtil {
+
+	private static final Logger logger = Logger.getLogger(HttpUtil.class.getName());
+
+	/**
+	 * 
+	 * 允许 JS 跨域设置
+	 * 
+	 * <p>
+	 * <!-- 使用 nginx 注意在 nginx.conf 中配置 -->
+	 * 
+	 * http { ...... add_header Access-Control-Allow-Origin *; ...... }
+	 * </p>
+	 * 
+	 * <p>
+	 * 非 ngnix 下,如果该方法设置不管用、可以尝试增加下行代码。
+	 * 
+	 * response.setHeader("Access-Control-Allow-Origin", "*");
+	 * </p>
+	 * 
+	 * @param response
+	 *            响应请求
+	 */
+	public static void allowJsCrossDomain(HttpServletResponse response) {
+		response.setHeader("Access-Control-Allow-Credentials", "true");
+		response.setHeader("Access-Control-Allow-Methods", "GET, OPTIONS, POST, PUT, DELETE");
+		response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
+		response.setHeader("Access-Control-Max-Age", "3600");
+	}
+
+	/**
+	 * 
+	 * <p>
+	 * 判断请求是否为 AJAX
+	 * </p>
+	 * 
+	 * @param request
+	 *            当前请求
+	 * @return
+	 */
+	public static boolean isAjax(HttpServletRequest request) {
+		return "XMLHttpRequest".equals(request.getHeader("X-Requested-With")) ? true : false;
+	}
+
+	/**
+	 * 
+	 * <p>
+	 * AJAX 设置 response 返回状态
+	 * </p>
+	 * 
+	 * @param response
+	 * @param status
+	 *            HTTP 状态码
+	 * @param tip
+	 */
+	public static void ajaxStatus(HttpServletResponse response, int status, String tip) {
+		try {
+			response.setContentType("text/html;charset=" + "UTF-8");
+			response.setStatus(status);
+			PrintWriter out = response.getWriter();
+			out.print(tip);
+			out.flush();
+		} catch (IOException e) {
+			logger.severe(e.toString());
+		}
+	}
+
+	/**
+	 * 
+	 * <p>
+	 * 获取当前 URL 包含查询条件
+	 * </p>
+	 * 
+	 * @param request
+	 * @param encode
+	 *            URLEncoder编码格式
+	 * @return
+	 * @throws IOException
+	 */
+	public static String getQueryString(HttpServletRequest request, String encode) throws IOException {
+		StringBuffer sb = new StringBuffer(request.getRequestURL());
+		String query = request.getQueryString();
+		if (query != null && query.length() > 0) {
+			sb.append("?").append(query);
+		}
+		return URLEncoder.encode(sb.toString(), encode);
+	}
+
+	public static String getReferer(HttpServletRequest request, String encode) throws UnsupportedEncodingException {
+		if (null != request.getHeader("Referer")){
+			return URLEncoder.encode(request.getHeader("Referer"), encode);
+		}
+		return null;
+	}
+
+	/**
+	 * 
+	 * <p>
+	 * getRequestURL是否包含在URL之内
+	 * </p>
+	 * 
+	 * @param request
+	 * @param url
+	 *            参数为以';'分割的URL字符串
+	 * @return
+	 */
+	public static boolean inContainURL(HttpServletRequest request, String url) {
+		boolean result = false;
+		if (url != null && !"".equals(url.trim())) {
+			String[] urlArr = url.split(";");
+			StringBuffer reqUrl = new StringBuffer(request.getRequestURL());
+			for (int i = 0; i < urlArr.length; i++) {
+				if (reqUrl.indexOf(urlArr[i]) > 1) {
+					result = true;
+					break;
+				}
+			}
+		}
+		return result;
+	}
+
+	/**
+	 * <p>
+	 * URLEncoder 返回地址
+	 * </p>
+	 * 
+	 * @param url
+	 *            跳转地址
+	 * @param retParam
+	 *            返回地址参数名
+	 * @param retUrl
+	 *            返回地址
+	 * @return
+	 */
+	public static String encodeRetURL(String url, String retParam, String retUrl) {
+		return encodeRetURL(url, retParam, retUrl, null);
+	}
+
+	/**
+	 * <p>
+	 * URLEncoder 返回地址
+	 * </p>
+	 * 
+	 * @param url
+	 *            跳转地址
+	 * @param retParam
+	 *            返回地址参数名
+	 * @param retUrl
+	 *            返回地址
+	 * @param data
+	 *            携带参数
+	 * @return
+	 */
+	public static String encodeRetURL(String url, String retParam, String retUrl, Map<String, String> data) {
+		if (url == null) {
+			return null;
+		}
+
+		StringBuffer retStr = new StringBuffer(url);
+		retStr.append("?");
+		retStr.append(retParam);
+		retStr.append("=");
+		try {
+			retStr.append(URLEncoder.encode(retUrl, "UTF-8"));
+		} catch (UnsupportedEncodingException e) {
+			logger.severe("encodeRetURL error." + url);
+			e.printStackTrace();
+		}
+
+		if (data != null) {
+			for (Map.Entry<String, String> entry : data.entrySet()) {
+				retStr.append("&").append(entry.getKey()).append("=").append(entry.getValue());
+			}
+		}
+
+		return retStr.toString();
+	}
+
+	/**
+	 * <p>
+	 * URLDecoder 解码地址
+	 * </p>
+	 * 
+	 * @param url
+	 *            解码地址
+	 * @return
+	 */
+	public static String decodeURL(String url) {
+		if (url == null) {
+			return null;
+		}
+		String retUrl = "";
+
+		try {
+			retUrl = URLDecoder.decode(url, "UTF-8");
+		} catch (UnsupportedEncodingException e) {
+			logger.severe("encodeRetURL error." + url);
+			e.printStackTrace();
+		}
+
+		return retUrl;
+	}
+
+	/**
+	 * <p>
+	 * GET 请求
+	 * </p>
+	 * 
+	 * @param request
+	 * @return boolean
+	 */
+	public static boolean isGet(HttpServletRequest request) {
+		if ("GET".equalsIgnoreCase(request.getMethod())) {
+			return true;
+		}
+		return false;
+	}
+
+	/**
+	 * <p>
+	 * POST 请求
+	 * </p>
+	 * 
+	 * @param request
+	 * @return boolean
+	 */
+	public static boolean isPost(HttpServletRequest request) {
+		if ("POST".equalsIgnoreCase(request.getMethod())) {
+			return true;
+		}
+		return false;
+	}
+
+	/**
+	 * 
+	 * <p>
+	 * 请求重定向至地址 location
+	 * </p>
+	 * 
+	 * @param response
+	 *            请求响应
+	 * @param location
+	 *            重定向至地址
+	 */
+	public static void sendRedirect(HttpServletResponse response, String location) {
+		try {
+			response.sendRedirect(location);
+		} catch (IOException e) {
+			logger.severe("sendRedirect location:" + location);
+			e.printStackTrace();
+		}
+	}
+
+	/**
+	 * <p>
+	 * 获取Request Playload 内容
+	 * </p>
+	 * 
+	 * @param request
+	 * @return Request Playload 内容
+	 */
+	public static String requestPlayload(HttpServletRequest request) throws IOException {
+		StringBuilder stringBuilder = new StringBuilder();
+		BufferedReader bufferedReader = null;
+		try {
+			InputStream inputStream = request.getInputStream();
+			if (inputStream != null) {
+				bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
+				char[] charBuffer = new char[128];
+				int bytesRead = -1;
+				while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
+					stringBuilder.append(charBuffer, 0, bytesRead);
+				}
+			} else {
+				stringBuilder.append("");
+			}
+		} catch (IOException ex) {
+			throw ex;
+		} finally {
+			if (bufferedReader != null) {
+				try {
+					bufferedReader.close();
+				} catch (IOException ex) {
+					throw ex;
+				}
+			}
+		}
+		return stringBuilder.toString();
+	}
+
+	/**
+	 * <p>
+	 * 获取当前完整请求地址
+	 * </p>
+	 * 
+	 * @param request
+	 * @return 请求地址
+	 */
+	public static String getRequestUrl(HttpServletRequest request) {
+		StringBuffer url = new StringBuffer(request.getScheme());
+		// 请求协议 http,https
+		url.append("://");
+		url.append(request.getHeader("host"));// 请求服务器
+		url.append(request.getRequestURI());// 工程名
+		if (request.getQueryString() != null) {
+			// 请求参数
+			url.append("?").append(request.getQueryString());
+		}
+		return url.toString();
+	}
+
+	public static ResponseWrap doPost(String postUrl, String formData) throws Exception {
+		return doPost(postUrl, formData, 30000);
+	}
+
+	public static ResponseWrap doPost(String postUrl, String formData, int timeout) throws Exception {
+		if (postUrl.startsWith("https")) {
+			return doHttpsPost(postUrl, formData, timeout);
+		}
+		return doHttpPost(postUrl, formData, timeout);
+	}
+
+	public static ResponseWrap doHttpPost(String postUrl, String formData, int timeout) throws Exception {
+		URL url = new URL(postUrl);
+		HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
+		try {
+			urlConn.setDoOutput(true);
+			urlConn.setDoInput(true);
+			urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
+			urlConn.setUseCaches(false);
+			urlConn.setInstanceFollowRedirects(true);
+			urlConn.setRequestMethod("POST");
+			urlConn.setConnectTimeout(timeout);
+			urlConn.setReadTimeout(timeout);
+			if (null != formData) {
+				OutputStreamWriter osw = new OutputStreamWriter(urlConn.getOutputStream(), "UTF-8");
+				osw.write(formData);
+				osw.flush();
+				osw.close();
+			}
+			return new ResponseWrap(urlConn.getResponseCode() == 200, streamToString(urlConn.getInputStream()));
+		} catch (Exception e) {
+			return new ResponseWrap(false, e.getMessage());
+		} finally {
+			if (urlConn != null) {
+				urlConn.disconnect();
+			}
+		}
+	}
+
+	public static ResponseWrap doHttpsPost(String postUrl, String formData, int timeout) throws Exception {
+		URL url = new URL(postUrl);
+		HttpsURLConnection urlConn = null;
+		try {
+			SSLContext ctx = SSLContext.getInstance("TLS");
+			ctx.init(new KeyManager[0], new TrustManager[] { new DefaultTrustManager() }, new SecureRandom());
+			SSLContext.setDefault(ctx);
+			urlConn = (HttpsURLConnection) url.openConnection();
+			urlConn.setDoOutput(true);
+			urlConn.setDoInput(true);
+			urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
+			urlConn.setUseCaches(false);
+			urlConn.setInstanceFollowRedirects(true);
+			urlConn.setRequestMethod("POST");
+			urlConn.setConnectTimeout(timeout);
+			urlConn.setReadTimeout(timeout);
+			urlConn.setHostnameVerifier(new HostnameVerifier() {
+
+				@Override
+				public boolean verify(String hostname, SSLSession session) {
+					return true;
+				}
+			});
+			if (null != formData) {
+				OutputStreamWriter osw = new OutputStreamWriter(urlConn.getOutputStream(), "UTF-8");
+				osw.write(formData);
+				osw.flush();
+				osw.close();
+			}
+			return new ResponseWrap(urlConn.getResponseCode() == 200, streamToString(urlConn.getInputStream()));
+		} catch (Exception e) {
+			return new ResponseWrap(false, e.getMessage());
+		} finally {
+			if (urlConn != null) {
+				urlConn.disconnect();
+			}
+		}
+	}
+
+	public static ResponseWrap doGet(String getUrl) throws Exception {
+		return doGet(getUrl, 30000);
+	}
+
+	public static ResponseWrap doGet(String getUrl, int timeout) throws Exception {
+		if (getUrl.startsWith("https")) {
+			return doHttpsGet(getUrl, timeout);
+		}
+		return doHttpGet(getUrl, timeout);
+	}
+
+	public static ResponseWrap doHttpGet(String getUrl, int timeout) throws Exception {
+		URL url = new URL(getUrl);
+		HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
+		try {
+			urlConn.setDoOutput(true);
+			urlConn.setDoInput(true);
+			urlConn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
+			urlConn.setUseCaches(false);
+			urlConn.setInstanceFollowRedirects(true);
+			urlConn.setRequestMethod("GET");
+			urlConn.setConnectTimeout(timeout);
+			urlConn.setReadTimeout(timeout);
+			return new ResponseWrap(urlConn.getResponseCode() == 200, streamToString(urlConn.getInputStream()));
+		} catch (Exception e) {
+			return new ResponseWrap(false, e.getMessage());
+		} finally {
+			if (urlConn != null) {
+				urlConn.disconnect();
+			}
+		}
+	}
+
+	public static ResponseWrap doHttpsGet(String getUrl, int timeout) throws Exception {
+		URL url = new URL(getUrl);
+		HttpsURLConnection urlConn = null;
+		try {
+			SSLContext ctx = SSLContext.getInstance("TLS");
+			ctx.init(new KeyManager[0], new TrustManager[] { new DefaultTrustManager() }, new SecureRandom());
+			SSLContext.setDefault(ctx);
+			urlConn = (HttpsURLConnection) url.openConnection();
+			urlConn.setDoOutput(true);
+			urlConn.setDoInput(true);
+			urlConn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
+			urlConn.setUseCaches(false);
+			urlConn.setInstanceFollowRedirects(true);
+			urlConn.setRequestMethod("GET");
+			urlConn.setConnectTimeout(timeout);
+			urlConn.setReadTimeout(timeout);
+			urlConn.setHostnameVerifier(new HostnameVerifier() {
+
+				@Override
+				public boolean verify(String hostname, SSLSession session) {
+					return true;
+				}
+			});
+			return new ResponseWrap(urlConn.getResponseCode() == 200, streamToString(urlConn.getInputStream()));
+		} catch (Exception e) {
+			return new ResponseWrap(false, e.getMessage());
+		} finally {
+			if (urlConn != null) {
+				urlConn.disconnect();
+			}
+		}
+	}
+
+	public static String streamToString(InputStream in) throws Exception {
+		BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
+		StringBuilder buf = new StringBuilder();
+
+		try {
+			char[] chars = new char[2048];
+			for (;;) {
+				int len = reader.read(chars, 0, chars.length);
+				if (len < 0) {
+					break;
+				}
+				buf.append(chars, 0, len);
+			}
+		} catch (Exception ex) {
+			throw new Exception("read string from reader error", ex);
+		}
+
+		return buf.toString();
+	}
+
+	public static ResponseWrap doPost(String postUrl, Map<String, Object> data) throws Exception {
+		return doPost(postUrl, getFormData(data));
+	}
+
+	public static ResponseWrap doPost(String postUrl, Map<String, Object> data, int timeout) throws Exception {
+		return doPost(postUrl, getFormData(data), timeout);
+	}
+
+	public static ResponseWrap doGet(String getUrl, Map<String, Object> data) throws Exception {
+		return doGet(getUrl + (getUrl.contains("?") ? "&" : "?") + getFormData(data));
+	}
+
+	public static ResponseWrap doGet(String getUrl, Map<String, Object> data, int timeout) throws Exception {
+		return doGet(getUrl + (getUrl.contains("?") ? "&" : "?") + getFormData(data), timeout);
+	}
+
+	public static ResponseWrap doHttpsPost(String postUrl, Map<String, Object> data, int timeout) throws Exception {
+		return doHttpsPost(postUrl, getFormData(data), timeout);
+	}
+
+	private static String getFormData(Map<String, Object> data) throws Exception {
+		StringBuffer sb = new StringBuffer();
+		for (String key : data.keySet())
+			if (data.get(key) != null)
+				sb.append(URLEncoder.encode(key, "UTF-8")).append("=")
+						.append(URLEncoder.encode(data.get(key).toString(), "UTF-8")).append("&");
+		return sb.substring(0, sb.length() - 1).toString();
+	}
+
+	public static class ResponseWrap {
+		private boolean success;
+		private String content;
+
+		public ResponseWrap(boolean success, String content) {
+			super();
+			this.success = success;
+			this.content = content;
+		}
+
+		public boolean isSuccess() {
+			return success;
+		}
+
+		public void setSuccess(boolean success) {
+			this.success = success;
+		}
+
+		public String getContent() {
+			return content;
+		}
+
+		public void setContent(String content) {
+			this.content = content;
+		}
+	}
+
+	private static class DefaultTrustManager implements X509TrustManager {
+
+		@Override
+		public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
+		}
+
+		@Override
+		public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
+		}
+
+		@Override
+		public X509Certificate[] getAcceptedIssuers() {
+			return null;
+		}
+
+	}
+}

+ 23 - 8
src/main/resources/application.yml

@@ -1,9 +1,24 @@
+spring:
+  profiles:
+      active: dev
+  jpa:
+  database: MYSQL
+  show-sql: false
+  properties:
+   hibernate:
+    dialect: org.hibernate.dialect.MySQL5Dialect
+    cache:
+      region:
+      factory_class: org.hibernate.cache.ehcache.SingletonEhCacheRegionFactory
+    hbm2ddl:
+     auto: update
+
 security:
- basic:
-  enabled: true
-  path: /**
- user:
-  name: message-admin
-  password: select111***
-  role: ADMIN
- ignored: false
+  basic:
+    enabled: true
+    path: /**
+  user:
+    name: message-admin
+    password: select111***
+    role: ADMIN
+  ignored: false

+ 19 - 0
src/main/resources/config/application-dev.properties

@@ -0,0 +1,19 @@
+datasource.url=jdbc:mysql://192.168.253.12:3306/public_resources?characterEncoding=utf-8&useSSL=false
+datasource.username=root
+datasource.password=select111***
+datasource.driverClassName=com.mysql.jdbc.Driver
+datasource.initialSize=1
+datasource.minIdle=1
+datasource.maxActive=20
+datasource.maxWait=60000
+datasource.timeBetweenEvictionRunsMillis=60000
+datasource.minEvictableIdleTimeMillis=300000
+datasource.validationQuery=SELECT 1 FROM DUAL
+datasource.testWhileIdle=true
+datasource.testOnBorrow=true
+datasource.testOnReturn=false
+datasource.poolPreparedStatements=true
+datasource.timeBetweenLogStatsMillis=60000
+datasource.maxPoolPreparedStatementPerConnectionSize=20
+datasource.filters=stat,slf4j
+datasource.connectionProperties=druid.stat.mergeSql=false;druid.stat.slowSqlMillis=5000

+ 19 - 0
src/main/resources/config/application-test.properties

@@ -0,0 +1,19 @@
+datasource.url=jdbc:mysql://192.168.253.12:3306/public_resources?characterEncoding=utf-8&useSSL=false
+datasource.username=root
+datasource.password=select111***
+datasource.driverClassName=com.mysql.jdbc.Driver
+datasource.initialSize=1
+datasource.minIdle=1
+datasource.maxActive=20
+datasource.maxWait=60000
+datasource.timeBetweenEvictionRunsMillis=60000
+datasource.minEvictableIdleTimeMillis=300000
+datasource.validationQuery=SELECT 1 FROM DUAL
+datasource.testWhileIdle=true
+datasource.testOnBorrow=true
+datasource.testOnReturn=false
+datasource.poolPreparedStatements=true
+datasource.timeBetweenLogStatsMillis=60000
+datasource.maxPoolPreparedStatementPerConnectionSize=20
+datasource.filters=stat,slf4j
+datasource.connectionProperties=druid.stat.mergeSql=false;druid.stat.slowSqlMillis=5000