Browse Source

Merge branch 'dev' of http://192.168.1.220:10080/Amoy2/wlyy2.0 into dev

humingfen 4 years ago
parent
commit
5707cb8bb4
39 changed files with 4681 additions and 7 deletions
  1. 246 0
      common/common-entity/src/main/java/com/yihu/jw/entity/iot/platform/IotInterfaceLogDO.java
  2. 1 0
      common/common-request-mapping/src/main/java/com/yihu/jw/rm/base/BaseRequestMapping.java
  3. 12 0
      svr/svr-base/src/main/java/com/yihu/jw/base/endpoint/user/UserEndpoint.java
  4. 102 4
      svr/svr-base/src/main/java/com/yihu/jw/base/service/user/UserService.java
  5. 194 0
      svr/svr-iot-job/pom.xml
  6. 4 0
      svr/svr-iot-job/readme.MD
  7. 15 0
      svr/svr-iot-job/src/log4j.xml
  8. 24 0
      svr/svr-iot-job/src/main/java/com/yihu/IotApplicationJob.java
  9. 54 0
      svr/svr-iot-job/src/main/java/com/yihu/jw/config/async/AsyncConfig.java
  10. 25 0
      svr/svr-iot-job/src/main/java/com/yihu/jw/config/quartz/JobFactory.java
  11. 56 0
      svr/svr-iot-job/src/main/java/com/yihu/jw/config/quartz/SchedulerConfig.java
  12. 61 0
      svr/svr-iot-job/src/main/java/com/yihu/jw/event/ApplicationEvent.java
  13. 124 0
      svr/svr-iot-job/src/main/java/com/yihu/jw/job/QuartzHelper.java
  14. 17 0
      svr/svr-iot-job/src/main/java/com/yihu/jw/repository/job/JobConfigDao.java
  15. 26 0
      svr/svr-iot-job/src/main/java/com/yihu/jw/repository/job/QuartzJobConfigDao.java
  16. 11 0
      svr/svr-iot-job/src/main/java/com/yihu/jw/repository/job/QuartzJobLogDao.java
  17. 11 0
      svr/svr-iot-job/src/main/java/com/yihu/jw/repository/statistics/QuotaDao.java
  18. 13 0
      svr/svr-iot-job/src/main/java/com/yihu/jw/repository/statistics/WlyyQuotaResultDao.java
  19. 2 0
      svr/svr-iot-job/src/main/java/com/yihu/jw/service/channel/SimBalanceService.java
  20. 8 0
      svr/svr-iot-job/src/main/java/com/yihu/jw/service/channel/SimSetMealService.java
  21. 253 0
      svr/svr-iot-job/src/main/java/com/yihu/jw/service/quota/JobService.java
  22. 927 0
      svr/svr-iot-job/src/main/java/com/yihu/jw/util/DateUtil.java
  23. 208 0
      svr/svr-iot-job/src/main/java/com/yihu/jw/util/SystemConf.java
  24. 41 0
      svr/svr-iot-job/src/main/java/com/yihu/jw/util/http/HttpResponse.java
  25. 382 0
      svr/svr-iot-job/src/main/java/com/yihu/jw/util/http/HttpUtils.java
  26. 54 0
      svr/svr-iot-job/src/main/java/com/yihu/jw/util/http/IPInfoUtils.java
  27. 571 0
      svr/svr-iot-job/src/main/java/com/yihu/jw/web/BaseController.java
  28. 326 0
      svr/svr-iot-job/src/main/java/com/yihu/jw/web/quota/JobController.java
  29. 110 0
      svr/svr-iot-job/src/main/java/com/yihu/jw/web/quota/WlyyJobConfigVO.java
  30. 107 0
      svr/svr-iot-job/src/main/java/com/yihu/jw/web/quota/WlyyQuotaVO.java
  31. 287 0
      svr/svr-iot-job/src/main/resources/application.yml
  32. 6 0
      svr/svr-iot-job/src/main/resources/banner.txt
  33. 61 0
      svr/svr-iot-job/src/main/resources/bootstrap.yml
  34. 44 0
      svr/svr-iot-job/src/main/resources/quartz.properties
  35. 23 0
      svr/svr-iot-job/src/main/resources/system.properties
  36. 5 2
      svr/svr-iot/src/main/java/com/yihu/iot/controller/platform/IotInterfaceController.java
  37. 1 1
      svr/svr-iot/src/main/java/com/yihu/iot/dao/device/IotDeviceQualityInspectionPlanDao.java
  38. 14 0
      svr/svr-iot/src/main/java/com/yihu/iot/dao/platform/IotInterfaceLogDao.java
  39. 255 0
      svr/svr-iot/src/main/java/com/yihu/iot/service/platform/IotInterfaceLogService.java

+ 246 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/iot/platform/IotInterfaceLogDO.java

@ -0,0 +1,246 @@
package com.yihu.jw.entity.iot.platform;
import com.yihu.jw.entity.UuidIdentityEntityWithOperator;
import org.hibernate.boot.model.relational.Namespace;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.persistence.Transient;
import java.io.Serializable;
import java.util.Date;
/**接口日志
 * @author HZY
 * @vsrsion 1.0
 * Created at 2020/4/28
 */
@Entity
@Table(name = "iot_interface_log")
public class IotInterfaceLogDO extends UuidIdentityEntityWithOperator implements Serializable {
    @Column(name="company_id")
    private String companyId;//公司ID
    @Column(name="company_name")
    private String companyName;//公司名称
    @Column(name="app_id")
    private String appId;//应用ID
    @Column(name="app_name")
    private String  appName;//应用名称
    @Column(name="work_type_id")
    private String workTypeId;//业务类型ID
    @Column(name="work_type")
    private String workType;//业务类型
    @Column(name="explanation")
    private String explanation;//接口说明
    @Column(name="user_id")
    private String userId;//用户id
    @Column(name="user_name")
    private String userName;//用户名称
    @Column(name="address_ip")
    private String addressIp;//访问ip地址
    @Column(name="source")
    private String source;//请求来源 1:卫健委 2:单位 3:系统管理员
    @Column(name="head")
    private String head;//请求头
    @Column(name="request")
    private String request;//请求参数
    @Column(name="interface_name")
    private String interfaceName;//请求接口名称
    @Column(name="method")
    private String method;//方法名
    @Column(name="type")
    private int type;//请求方式 1:get请求  2:post请求
    @Column(name="url")
    private String url;//请求URL
    @Column(name="response")
    private String  response;//响应参数
    @Column(name="time")
    private Date time;//调用时间
    @Column(name="state")
    private int  state;//调用状态 1:成功   0:失败
    @Transient
    private String count;//调用次数
    @Transient
    private String failureRate;//失败率
    public String getCompanyId() {
        return companyId;
    }
    public void setCompanyId(String companyId) {
        this.companyId = companyId;
    }
    public String getCompanyName() {
        return companyName;
    }
    public void setCompanyName(String companyName) {
        this.companyName = companyName;
    }
    public String getAppId() {
        return appId;
    }
    public void setAppId(String appId) {
        this.appId = appId;
    }
    public String getAppName() {
        return appName;
    }
    public void setAppName(String appName) {
        this.appName = appName;
    }
    public String getWorkTypeId() {
        return workTypeId;
    }
    public void setWorkTypeId(String workTypeId) {
        this.workTypeId = workTypeId;
    }
    public String getUserId() {
        return userId;
    }
    public void setUserId(String userId) {
        this.userId = userId;
    }
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }
    public String getAddressIp() {
        return addressIp;
    }
    public void setAddressIp(String addressIp) {
        this.addressIp = addressIp;
    }
    public String getSource() {
        return source;
    }
    public void setSource(String source) {
        this.source = source;
    }
    public String getHead() {
        return head;
    }
    public void setHead(String head) {
        this.head = head;
    }
    public String getRequest() {
        return request;
    }
    public void setRequest(String request) {
        this.request = request;
    }
    public String getInterfaceName() {
        return interfaceName;
    }
    public void setInterfaceName(String interfaceName) {
        this.interfaceName = interfaceName;
    }
    public String getMethod() {
        return method;
    }
    public void setMethod(String method) {
        this.method = method;
    }
    public int getType() {
        return type;
    }
    public void setType(int type) {
        this.type = type;
    }
    public String getUrl() {
        return url;
    }
    public void setUrl(String url) {
        this.url = url;
    }
    public String getResponse() {
        return response;
    }
    public void setResponse(String response) {
        this.response = response;
    }
    public Date getTime() {
        return time;
    }
    public void setTime(Date time) {
        this.time = time;
    }
    public int getState() {
        return state;
    }
    public void setState(int state) {
        this.state = state;
    }
    public String getWorkType() {
        return workType;
    }
    public void setWorkType(String workType) {
        this.workType = workType;
    }
    public String getExplanation() {
        return explanation;
    }
    public void setExplanation(String explanation) {
        this.explanation = explanation;
    }
    @Transient
    public String getCount() {
        return count;
    }
    public void setCount(String count) {
        this.count = count;
    }
    @Transient
    public String getFailureRate() {
        return failureRate;
    }
    public void setFailureRate(String failureRate) {
        this.failureRate = failureRate;
    }
}

+ 1 - 0
common/common-request-mapping/src/main/java/com/yihu/jw/rm/base/BaseRequestMapping.java

@ -161,6 +161,7 @@ public class BaseRequestMapping {
        public static final String CHECK_MOBILE = "/check_mobile";
        public static final String findUserBaseInfo = "/findUserBaseInfo";
        public static final String resetPwd = "/resetPwd";
        public static final String updatePwd = "/updatePwd";
        public static final String queryOne = "/queryOne";
        public static final String orgTreeInfo = "/orgTreeInfo";
        public static final String userInfoList = "/userInfoList";

+ 12 - 0
svr/svr-base/src/main/java/com/yihu/jw/base/endpoint/user/UserEndpoint.java

@ -11,6 +11,7 @@ import com.yihu.jw.restmodel.web.ObjEnvelop;
import com.yihu.jw.restmodel.web.PageEnvelop;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import com.yihu.jw.rm.base.BaseRequestMapping;
import com.yihu.jw.rm.hospital.BaseHospitalRequestMapping;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
@ -235,4 +236,15 @@ public class UserEndpoint extends EnvelopRestEndpoint {
        }
        return success(jsonObject.getString("msg"));
    }
    
    @PostMapping(value = BaseRequestMapping.User.updatePwd)
    @ApiOperation(value = "修账号密码")
    public Envelop updatePwd(@ApiParam(name = "id", value = "用户ID")
                                  @RequestParam(value = "id", required = true)String id,
                                  @ApiParam(name = "pw", value = "密码")
                                  @RequestParam(value = "pw", required = true)String pw,
                                  @ApiParam(name = "orgPw", value = "原密码")
                                  @RequestParam(value = "orgPw", required = true)String orgPw)throws Exception{
        return success(userService.updatePwd(id,pw,orgPw));
    }
}

+ 102 - 4
svr/svr-base/src/main/java/com/yihu/jw/base/service/user/UserService.java

@ -1,5 +1,6 @@
package com.yihu.jw.base.service.user;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
@ -17,11 +18,15 @@ import com.yihu.jw.entity.base.org.BaseOrgUserDO;
import com.yihu.jw.entity.base.role.RoleDO;
import com.yihu.jw.entity.base.saas.SaasDO;
import com.yihu.jw.entity.base.user.UserDO;
import com.yihu.jw.entity.hospital.consult.WlyyHospitalSysDictDO;
import com.yihu.jw.hospital.dict.WlyyHospitalSysDictDao;
import com.yihu.jw.util.date.DateUtil;
import com.yihu.mysql.query.BaseJpaService;
import com.yihu.utils.security.MD5;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
@ -61,9 +66,15 @@ public class UserService extends BaseJpaService<UserDO, UserDao> {
    @Autowired
    private BaseOrgSaasService baseOrgSaasService;
    
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Value("${configDefault.saasId}")
    private String defaultSaasId;
    
    @Autowired
    private WlyyHospitalSysDictDao wlyyHospitalSysDictDao;
    public UserDO registerWithIdcard(UserDO userDO) {
@ -214,9 +225,44 @@ public class UserService extends BaseJpaService<UserDO, UserDao> {
                    }
            }
        }
    
    
        //密码过期
        userinfo.put("authPw",findDoctorPwlimitDate(id));
        return userinfo;
    }
    
    public com.alibaba.fastjson.JSONObject findDoctorPwlimitDate(String user){
        String key = "base:authPw:iser:" + user;
        String authPw = redisTemplate.opsForValue().get(key);
        com.alibaba.fastjson.JSONObject valueJson = null;
        if(org.apache.commons.lang3.StringUtils.isNotBlank(authPw)){
            
            WlyyHospitalSysDictDO wlyyHospitalSysDictDO = wlyyHospitalSysDictDao.findById("pwOverDue");
            String code[] = wlyyHospitalSysDictDO.getDictCode().split(",");
            Integer maxDateInt = Integer.parseInt(code[0]);
            Integer remainDateInt = Integer.parseInt(code[1]);
            
            valueJson = JSON.parseObject(authPw);
            Long updateTimeLong = valueJson.getLong("updateTime");
            Date updateTime = new Date();
            updateTime.setTime(updateTimeLong);
            Date maxDate = DateUtil.getPreDays(updateTime,maxDateInt);
            
            Long betweenDate = (maxDate.getTime() - new Date().getTime())/(60*60*24*1000);
            valueJson.put("betweenDate",betweenDate);
            if(betweenDate<remainDateInt){
                valueJson.put("remaind",true);
            }else {
                valueJson.put("remaind",false);
            }
        }else {
            valueJson = new com.alibaba.fastjson.JSONObject();
            valueJson.put("isChanged",false);
        }
        return valueJson;
    }
    /**
@ -427,6 +473,58 @@ public class UserService extends BaseJpaService<UserDO, UserDao> {
        return result;
    }
    /**
     * 用户修改密码
     * @param userId
     * @return
     */
    public JSONObject updatePwd(String userId,String pwd,String oldpwd){
        JSONObject result = new JSONObject();
        UserDO user = userDao.findOne(userId);
        if(null == user){
            result.put("response", ConstantUtils.FAIL);
            result.put("msg","user not exist for id : " + userId);
            return result;
        }
    
        String orgPwMd5 = MD5.md5Hex(oldpwd + "{" + user.getSalt() + "}");
        if(!orgPwMd5.equals(user.getPassword())){
            result.put("response", ConstantUtils.FAIL);
            result.put("msg","旧密码不正确!");
            return result;
        }
        if(StringUtils.isEmpty(pwd)){
            result.put("response", ConstantUtils.FAIL);
            result.put("msg","新密码不能为空!");
            return result;
        }
        user.setSalt(randomString(5));
        user.setEnabled(true);
        user.setLocked(false);
        user.setLoginFailureCount(0);
        user.setPassword(MD5.md5Hex(pwd + "{" + user.getSalt() + "}"));
        userDao.save(user);
        result.put("response",ConstantUtils.SUCCESS);
        result.put("msg", "修改成功");
    
        //设置用户密码过期时间
        saveUserPwlimitDate(userId);
        
        return result;
    }
    
    public boolean saveUserPwlimitDate(String user){
        String key = "base:authPw:user:" + user;
        com.alibaba.fastjson.JSONObject valueJson = new com.alibaba.fastjson.JSONObject();
        valueJson.put("updateTime",new Date().getTime());
        valueJson.put("isChanged",true);
        redisTemplate.opsForValue().set(key,valueJson.toJSONString());
        return true;
    }
    
    /**
     * 用户重置密码
     * @param userId
@ -444,26 +542,26 @@ public class UserService extends BaseJpaService<UserDO, UserDao> {
        String idcard = user.getIdcard();
        String mobile = user.getMobile();
        String password = null;
        
        if(!StringUtils.isEmpty(password)&&idcard.length()>10){
            password = idcard.substring(idcard.length()-6,idcard.length());
        }else if(!StringUtils.isEmpty(mobile)&&mobile.length()>=11){
            password = mobile.substring(mobile.length()-6,mobile.length());
        }
        
        if(StringUtils.isEmpty(password)){
            result.put("response", ConstantUtils.FAIL);
            result.put("msg","idcard or moblie not exist : " + userId);
            return result;
        }
        
        user.setSalt(randomString(5));
        user.setEnabled(true);
        user.setLocked(false);
        user.setLoginFailureCount(0);
        user.setPassword(MD5.md5Hex(password + "{" + user.getSalt() + "}"));
        userDao.save(user);
        
        result.put("response",ConstantUtils.SUCCESS);
        result.put("msg", password);
        return result;

+ 194 - 0
svr/svr-iot-job/pom.xml

@ -0,0 +1,194 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>com.yihu.jw</groupId>
        <artifactId>wlyy-parent-pom</artifactId>
        <version>2.0.0</version>
        <relativePath>../../wlyy-parent-pom/pom.xml</relativePath>
    </parent>
    <groupId>com.yihu.jw</groupId>
    <artifactId>svr-iot-job</artifactId>
    <packaging>jar</packaging>
    <version>${parent.version}</version>
    <dependencies>
        <!-- 支持Tomcat启动 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-tomcat</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
        </dependency>
        <!-- 支持Tomcat启动 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
       <!-- <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka</artifactId>
        </dependency>-->
        <!--注释掉就不会读取git的配置,只会读取yml中的配置-->
        <!--<dependency>-->
            <!--<groupId>org.springframework.cloud</groupId>-->
            <!--<artifactId>spring-cloud-starter-config</artifactId>-->
        <!--</dependency>-->
        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
        </dependency>
        <dependency>
            <groupId>net.sf.json-lib</groupId>
            <artifactId>json-lib</artifactId>
            <version>2.4</version>
        </dependency>
        <dependency>
            <groupId>com.yihu.iot</groupId>
            <artifactId>svr-iot</artifactId>
            <version>2.0.0</version>
        </dependency>
        <dependency>
            <groupId>com.yihu.jw</groupId>
            <artifactId>common-entity</artifactId>
        </dependency>
        <dependency>
            <groupId>com.yihu.jw</groupId>
            <artifactId>common-rest-model</artifactId>
        </dependency>
        <dependency>
            <groupId>com.yihu.jw</groupId>
            <artifactId>base-service</artifactId>
            <version>${parent.version}</version>
        </dependency>
        <dependency>
            <groupId>com.yihu.jw</groupId>
            <artifactId>im-service</artifactId>
            <version>2.0.0</version>
        </dependency>
        <dependency>
            <groupId>com.yihu.jw</groupId>
            <artifactId>common-exception</artifactId>
        </dependency>
        <!-- Jzkl Starter -->
        <dependency>
            <groupId>com.yihu</groupId>
            <artifactId>swagger-starter</artifactId>
            <version>2.0.0</version>
        </dependency>
        <dependency>
            <groupId>com.yihu</groupId>
            <artifactId>mysql-starter</artifactId>
            <version>2.0.0</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-core</artifactId>
            <version>RELEASE</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.junit.platform</groupId>
            <artifactId>junit-platform-commons</artifactId>
            <version>1.3.2</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
        </dependency>
        <dependency>
            <groupId>io.github.swagger2markup</groupId>
            <artifactId>swagger2markup</artifactId>
            <version>1.3.2</version>
        </dependency>
        <!-- quartz start  -->
        <dependency>
            <groupId>org.quartz-scheduler</groupId>
            <artifactId>quartz</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>4.2.5.RELEASE</version>
        </dependency>
        <!-- quartz end  -->
        <dependency>
            <groupId>io.searchbox</groupId>
            <artifactId>jest</artifactId>
            <version>2.4.0</version>
        </dependency>
        <dependency>
            <groupId>org.elasticsearch</groupId>
            <artifactId>elasticsearch</artifactId>
            <version>2.4.4</version>
        </dependency>
        <!--oracle驱动-->
        <dependency>
            <groupId>com.oracle</groupId>
            <artifactId>ojdbc6</artifactId>
            <version>11.2.0.3</version>
        </dependency>
    </dependencies>
    <build>
        <finalName>svr-iot-job</finalName>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <mainClass>com.yihu.IotApplicationJob</mainClass>
                </configuration>
            </plugin>
            <plugin>
                <artifactId>maven-war-plugin</artifactId>
                <configuration>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                    <filteringDeploymentDescriptors>true</filteringDeploymentDescriptors>
                </configuration>
            </plugin>
        </plugins>
        <resources>
            <!--指定资源的位置-->
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/**.**</include>
                </includes>
            </resource>
        </resources>
    </build>
</project>

+ 4 - 0
svr/svr-iot-job/readme.MD

@ -0,0 +1,4 @@
基础微服务
    每个模块有自己独立的文件夹,这样做的好处是以后如果哪个模块需要独立成微服务,代码直接剪切到新的微服务即可。
    每个模块下面有独立的Endpoint,service,model和dao
  

+ 15 - 0
svr/svr-iot-job/src/log4j.xml

@ -0,0 +1,15 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/" debug="false">
	<appender name="esb_log" class="org.apache.log4j.DailyRollingFileAppender">        
        <param name="File" value="c:/log/esb_log.log" />        
        <param name="DatePattern" value="'.'yyyy-MM-dd'.log'" />        
        <layout class="org.apache.log4j.PatternLayout">        
            <param name="ConversionPattern" value="[%d{yyyy-MM-dd HH:mm:ss/} %-5p] [%t] (%c:%L) - %m%n" />        
        </layout>        
    </appender>
	<root>
		<level value="DEBUG" />
		<appender-ref ref="esb_log" />
	</root>
</log4j:configuration>

+ 24 - 0
svr/svr-iot-job/src/main/java/com/yihu/IotApplicationJob.java

@ -0,0 +1,24 @@
package com.yihu;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
/**
 * Created by Trick on 2019/5/13.
 */
@SpringBootApplication
@EnableJpaAuditing
public class IotApplicationJob extends SpringBootServletInitializer {
    public static void main(String[] args)  {
        SpringApplication.run(IotApplicationJob.class, args);
    }
    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
        return builder.sources(IotApplicationJob.class);
    }
}

+ 54 - 0
svr/svr-iot-job/src/main/java/com/yihu/jw/config/async/AsyncConfig.java

@ -0,0 +1,54 @@
package com.yihu.jw.config.async;
import org.apache.tomcat.util.threads.ThreadPoolExecutor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.Executor;
/**
 * Created by chenweida on 2016.10.18.
 * 启用多綫程
 */
@Configuration
@EnableAsync
public class AsyncConfig {
    /**
     * 如果池中的实际线程数小于corePoolSize,无论是否其中有空闲的线程,都会给新的任务产生新的线程
     */
    private int corePoolSize = 5;
    /**
     * 如果池中的线程数=maximumPoolSize,则有空闲线程使用空闲线程,否则新任务放入queueCapacity.
     * 设定 比 系统native thread个数要大的话,会优先抛出Java.lang.OutOfMemoryError: unable to create new native thread
     */
    private int maxPoolSize = 10;
    /**
     * 缓冲队列大小
     */
    private int queueCapacity = 100;
    /**
     * 线程池维护线程所允许的空闲时间  秒
     */
    private int keepAliveSeconds = 300;
    @Bean
    public Executor wlyyExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(corePoolSize);
        executor.setMaxPoolSize(maxPoolSize);
        executor.setQueueCapacity(queueCapacity);
        executor.setKeepAliveSeconds(keepAliveSeconds);
        /** Reject策略预定义有四种:
         (1)ThreadPoolExecutor.AbortPolicy策略,是默认的策略,处理程序遭到拒绝将抛出运行时 RejectedExecutionException。
         (2)ThreadPoolExecutor.CallerRunsPolicy策略 ,调用者的线程会执行该任务,如果执行器已关闭,则丢弃.
         (3)ThreadPoolExecutor.DiscardPolicy策略,不能执行的任务将被丢弃.
         (4)ThreadPoolExecutor.DiscardOldestPolicy策略,如果执行程序尚未关闭,则位于工作队列头部的任务将被删除,然后重试执行程序(如果再次失败,则重复此过程).
         */
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();
        return executor;
    }
}

+ 25 - 0
svr/svr-iot-job/src/main/java/com/yihu/jw/config/quartz/JobFactory.java

@ -0,0 +1,25 @@
package com.yihu.jw.config.quartz;
import org.quartz.spi.TriggerFiredBundle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.scheduling.quartz.AdaptableJobFactory;
import org.springframework.stereotype.Component;
/**
 * Created by Administrator on 2016.10.12.
 * 為了讓quartz種可以使用Spring的注入
 */
@Component("jobFactory")
public class JobFactory extends AdaptableJobFactory {
    @Autowired
    private AutowireCapableBeanFactory capableBeanFactory;
    @Override
    protected Object createJobInstance(TriggerFiredBundle bundle) throws Exception {
        // 调用父类的方法
        Object jobInstance = super.createJobInstance(bundle);
       // 进行注入
        capableBeanFactory.autowireBean(jobInstance);
        return jobInstance;
    }
}

+ 56 - 0
svr/svr-iot-job/src/main/java/com/yihu/jw/config/quartz/SchedulerConfig.java

@ -0,0 +1,56 @@
package com.yihu.jw.config.quartz;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.PropertiesFactoryBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import javax.sql.DataSource;
import java.io.IOException;
import java.util.Properties;
/**
 * Created by chenweida on 2016/2/3.
 */
@Configuration
public class SchedulerConfig {
    @Autowired
    private ApplicationContext applicationContext;
    @Autowired
    private JobFactory jobFactory;
    @Autowired
    private DataSource dataSource;
    @Value("${quartz.name}")
    private String schedulerFactoryBeanName;
    @Bean
    SchedulerFactoryBean schedulerFactoryBeanWlyy() throws IOException {
        SchedulerFactoryBean bean = new SchedulerFactoryBean();
        bean.setJobFactory(jobFactory);
        bean.setApplicationContext(this.applicationContext);
        bean.setOverwriteExistingJobs(true);
        bean.setStartupDelay(20);// 延时启动
        bean.setBeanName(schedulerFactoryBeanName);
        bean.setAutoStartup(true);
        bean.setDataSource(dataSource);
        bean.setQuartzProperties(quartzProperties());
        return bean;
    }
    /**
     * quartz配置文件
     * @return
     * @throws IOException
     */
    @Bean
    public Properties quartzProperties() throws IOException {
        PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean();
        propertiesFactoryBean.setLocation(new ClassPathResource("/quartz.properties"));
        propertiesFactoryBean.afterPropertiesSet();
        return propertiesFactoryBean.getObject();
    }
}

+ 61 - 0
svr/svr-iot-job/src/main/java/com/yihu/jw/event/ApplicationEvent.java

@ -0,0 +1,61 @@
package com.yihu.jw.event;
import com.yihu.jw.job.QuartzHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Service;
/**
 * Created by zdm on 2017/3/10.
 */
@Service
public class ApplicationEvent implements ApplicationListener<ContextRefreshedEvent> {
    private Logger logger = LoggerFactory.getLogger(ApplicationEvent.class);
    @Autowired
    QuartzHelper quartzHelper;
    @Override
    public void onApplicationEvent(ContextRefreshedEvent ContextRefreshedEvent) {
        try {
//=================中山医院发布启动======================================================
//            //互联网医院处方状态更新job
//            if (!quartzHelper.isExistJob("prescriptionStatus_update_job")) {
//                String trigger = SystemConf.getInstance().getSystemProperties().getProperty("prescriptionStatus_update_job");
//                quartzHelper.addJob(PrescriptionStatusUpdateJob.class, trigger, "prescriptionStatus_update_job", new HashMap<String, Object>());
//                logger.info("prescriptionStatus_update_job  job success");
//            } else {
//                logger.info("prescriptionStatus_update_job  job exist");
//            }
//
//            //门诊过期
//            if (!quartzHelper.isExistJob("prescription_overdue_job")) {
//                String trigger = SystemConf.getInstance().getSystemProperties().getProperty("prescription_overdue_job");
//                quartzHelper.addJob(PrescriptionOverdueJob.class, trigger, "prescription_overdue_job", new HashMap<String, Object>());
//                logger.info("prescription_overdue_job  job success");
//            } else {
//                logger.info("prescription_overdue_job  job exist");
//            }
//
//
//            //互联网医院 监管平台上报
//            if (!quartzHelper.isExistJob("data_upload_job")) {
//                String trigger = SystemConf.getInstance().getSystemProperties().getProperty("data_upload_job");
//                quartzHelper.addJob(DataUploadJob.class, trigger, "data_upload_job", new HashMap<String, Object>());
//                logger.info("data_upload_job  job success");
//            } else {
//                logger.info("data_upload_job  job exist");
//            }
//=================中山医院发布启动======================================================
        } catch (Exception e) {
            logger.info("followup_plan_remind job start failed");
        }
    }
}

+ 124 - 0
svr/svr-iot-job/src/main/java/com/yihu/jw/job/QuartzHelper.java

@ -0,0 +1,124 @@
package com.yihu.jw.job;
import org.apache.commons.collections.map.HashedMap;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.quartz.SimpleScheduleBuilder.simpleSchedule;
@Component("quartzHelper")
public class QuartzHelper {
    @Autowired
    private SchedulerFactoryBean schedulerFactoryBean;
    private Scheduler scheduler = null;
    @PostConstruct
    public void init() {
        try {
            scheduler = schedulerFactoryBean.getScheduler();
            scheduler.start();
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }
    public Map<String,Object> getCalendar()throws Exception{
        Map<String,Object> rs = new HashedMap();
        rs.put("JobGroupNames ",scheduler.getJobGroupNames());
        rs.put("SchedulerName ",scheduler.getSchedulerName());
        rs.put("TriggerGroups ",scheduler.getPausedTriggerGroups());
        return rs;
    }
    public void addJob(Class jobClass, String cronString, String jobKey,
                       Map<String, Object> params) throws Exception {
        if (!CronExpression.isValidExpression(cronString)) {
            throw new Exception("cronExpression is not a valid Expression");
        }
        try {
            JobDetail job = JobBuilder.newJob(jobClass)
                    .withIdentity("job-id:" + jobKey, "job-group:" + jobKey)
                    .build();
            JobDataMap jobDataMap = job.getJobDataMap();
            jobDataMap.putAll(params);
            CronTrigger trigger = TriggerBuilder
                    .newTrigger()
                    .withIdentity("trigger-name:" + jobKey,
                            "trigger-group:" + jobKey)
                    .withSchedule(CronScheduleBuilder.cronSchedule(cronString))
                    .build();
            scheduler.scheduleJob(job, trigger);
            scheduler.start();
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }
    public void removeJob(String jobKeyString) throws Exception {
        TriggerKey triggerKey = new TriggerKey("trigger-name:" + jobKeyString,
                "trigger-group:" + jobKeyString);
//        JobKey jobName = new JobKey("job-group:" + jobKeyString, "job-id:"
//                + jobKeyString);
        JobKey jobName = new JobKey("job-id:" + jobKeyString, "job-group:"
                + jobKeyString);
        scheduler.pauseTrigger(triggerKey);// 停止触发器
        scheduler.unscheduleJob(triggerKey);// 移除触发器
        scheduler.deleteJob(jobName);// 删除任务
    }
    public boolean isExistJob(String jobKey) throws SchedulerException {
        JobKey jk = new JobKey("job-id:" + jobKey, "job-group:" + jobKey);
        if (scheduler.checkExists(jk)) {
            return true;
        } else {
            return false;
        }
    }
    /**
     * 立即执行任务。
     *
     * @param jobClass
     * @param id
     * @param params
     * @throws Exception
     */
    public void startNow(Class jobClass, String id, Map<String, Object> params) throws Exception {
        startAt(new Date(), jobClass, id, params);
    }
    /**
     * 在指定时间点执行。
     *
     * @param time
     * @param jobClass
     * @param id
     * @param params
     * @throws Exception
     */
    public void startAt(Date time, Class jobClass, String id, Map<String, Object> params) throws Exception {
        JobDetail job = JobBuilder.newJob(jobClass).
                withIdentity("job-id:" + id, "job-group:" + id)
                .build();
        JobDataMap jobDataMap = job.getJobDataMap();
        if(null != params) jobDataMap.putAll(params);
        SimpleTrigger trigger = TriggerBuilder.newTrigger().withIdentity("trigger-id:" + id, "group-group:" + id)
                .startAt(time)
                .withSchedule(simpleSchedule().withIntervalInSeconds(10).withRepeatCount(0))
                .build();
        scheduler.scheduleJob(job, trigger);
        scheduler.start();
    }
}

+ 17 - 0
svr/svr-iot-job/src/main/java/com/yihu/jw/repository/job/JobConfigDao.java

@ -0,0 +1,17 @@
package com.yihu.jw.repository.job;
import com.yihu.jw.entity.job.QuartzJobConfig;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
/**
 * Created by Administrator on 2016/8/16.
 */
public interface JobConfigDao extends PagingAndSortingRepository<QuartzJobConfig, String>,JpaSpecificationExecutor<QuartzJobConfig> {
    @Query(" from QuartzJobConfig p where p.status=?1 and p.del='1'")
    List<QuartzJobConfig> findByStatus(String s);
}

+ 26 - 0
svr/svr-iot-job/src/main/java/com/yihu/jw/repository/job/QuartzJobConfigDao.java

@ -0,0 +1,26 @@
package com.yihu.jw.repository.job;
import com.yihu.jw.entity.job.QuartzJobConfig;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
/**
 * Created by Administrator on 2016/8/17.
 */
public interface QuartzJobConfigDao extends PagingAndSortingRepository<QuartzJobConfig, String>, JpaSpecificationExecutor<QuartzJobConfig> {
    @Query(" FROM QuartzJobConfig a WHERE a.id=?1 and a.status=?2 and a.del='1'")
    QuartzJobConfig findById(String code, String status);
    @Query(" FROM QuartzJobConfig a WHERE a.status=?1 and a.del='1'")
    List<QuartzJobConfig> findByAll(String s);
    @Query(" FROM QuartzJobConfig a WHERE a.id in (1,2,3,4,5,6,7,8,9,10,12,13,14)  and a.del='1' ")
    List<QuartzJobConfig> findByIds();
    @Query(" FROM QuartzJobConfig a WHERE a.id=?1 and a.del='1'")
    QuartzJobConfig findById(String id);
}

+ 11 - 0
svr/svr-iot-job/src/main/java/com/yihu/jw/repository/job/QuartzJobLogDao.java

@ -0,0 +1,11 @@
package com.yihu.jw.repository.job;
import com.yihu.jw.entity.job.QuartzJobLog;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
/**
 * Created by Administrator on 2016/8/16.
 */
public interface QuartzJobLogDao extends PagingAndSortingRepository<QuartzJobLog, String>, JpaSpecificationExecutor<QuartzJobLog> {
}

+ 11 - 0
svr/svr-iot-job/src/main/java/com/yihu/jw/repository/statistics/QuotaDao.java

@ -0,0 +1,11 @@
package com.yihu.jw.repository.statistics;
import com.yihu.jw.entity.quota.WlyyQuota;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
/**
 * Created by Administrator on 2016/8/16.
 */
public interface QuotaDao  extends PagingAndSortingRepository<WlyyQuota, String>, JpaSpecificationExecutor<WlyyQuota> {
}

+ 13 - 0
svr/svr-iot-job/src/main/java/com/yihu/jw/repository/statistics/WlyyQuotaResultDao.java

@ -0,0 +1,13 @@
package com.yihu.jw.repository.statistics;
import com.yihu.jw.entity.quota.WlyyQuotaResult;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
/**
 * Created by Administrator on 2016/8/16.
 */
public interface WlyyQuotaResultDao extends PagingAndSortingRepository<WlyyQuotaResult, String>, JpaSpecificationExecutor<WlyyQuotaResult> {
}

+ 2 - 0
svr/svr-iot-job/src/main/java/com/yihu/jw/service/channel/SimBalanceService.java

@ -52,6 +52,7 @@ public class SimBalanceService {
           iotMessageDao.save(iotMessageDO);
       });
        //欠费提醒
        Integer status = simBalanceRemind.getStatus();
        String simStatus = status + "";
@ -70,6 +71,7 @@ public class SimBalanceService {
            });
        }
        logger.info("autoPush end");
    }

+ 8 - 0
svr/svr-iot-job/src/main/java/com/yihu/jw/service/channel/SimSetMealService.java

@ -31,6 +31,14 @@ public class SimSetMealService {
        List<IotDeviceSimDO> list = iotDeviceSimDao.findAllByDel();
        list.forEach(one->{
            one.setRemainingBalance(one.getRemainingBalance()-one.getPayment());
            //设置SIM的状态
            if (one.getRemainingBalance()<0){
                one.setStatus(0);
            }else {
                one.setStatus(1);
            }
            iotDeviceSimDao.save(one);
        });

+ 253 - 0
svr/svr-iot-job/src/main/java/com/yihu/jw/service/quota/JobService.java

@ -0,0 +1,253 @@
package com.yihu.jw.service.quota;
import com.yihu.jw.entity.job.QuartzJobConfig;
import com.yihu.jw.entity.quota.WlyyQuota;
import com.yihu.jw.job.QuartzHelper;
import com.yihu.jw.repository.job.QuartzJobConfigDao;
import com.yihu.jw.repository.statistics.QuotaDao;
import com.yihu.jw.web.quota.WlyyQuotaVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import java.text.SimpleDateFormat;
import java.util.*;
/**
 * @author chenweida
 */
@Service
public class JobService {
    @Autowired
    private QuartzHelper quartzHelper;
    @Autowired
    private QuartzJobConfigDao wlyyJobConfigDao;
    @Autowired
    private QuotaDao quotaDao;
    @Transactional
    public void stopById(String id) throws Exception {
        QuartzJobConfig quartzJobConfig = wlyyJobConfigDao.findById(id, "1");
        if (quartzJobConfig != null) {
            quartzHelper.removeJob(quartzJobConfig.getId());
            quartzJobConfig.setStatus("0");
        } else {
            throw new Exception("任务已经停止");
        }
    }
    @Transactional
    public void startById(String id) throws Exception {
        QuartzJobConfig quartzJobConfig = wlyyJobConfigDao.findById(id, "0");
        if (quartzJobConfig != null) {
            startOneJob(quartzJobConfig);
        } else {
            throw new Exception("任务已经启动");
        }
    }
    @Transactional
    public void stopAll() throws Exception {
        List<QuartzJobConfig> quartzJobConfigs = wlyyJobConfigDao.findByAll("1");
        if (quartzJobConfigs != null && quartzJobConfigs.size() > 0) {
            for (QuartzJobConfig quartzJobConfig : quartzJobConfigs) {
                quartzHelper.removeJob(quartzJobConfig.getId());
                quartzJobConfig.setStatus("0");
            }
        } else {
            throw new Exception("任务已经全部停止");
        }
    }
    @Transactional
    public void startAll() throws Exception {
        List<QuartzJobConfig> quartzJobConfigs = wlyyJobConfigDao.findByAll("0");
        if (quartzJobConfigs != null && quartzJobConfigs.size() > 0) {
            for (QuartzJobConfig quartzJobConfig : quartzJobConfigs) {
                startOneJob(quartzJobConfig);
            }
        } else {
            throw new Exception("任务已经全部启动");
        }
    }
    /**
     * 启动单个任务
     *
     * @param quartzJobConfig
     * @throws Exception
     */
    private void startOneJob(QuartzJobConfig quartzJobConfig) throws Exception {
        WlyyQuota wlyyQuota = quotaDao.findOne(quartzJobConfig.getQuotaId());
        com.yihu.jw.web.quota.WlyyQuotaVO wlyyQuotaVO = new com.yihu.jw.web.quota.WlyyQuotaVO();
        com.yihu.jw.web.quota.WlyyJobConfigVO wlyyJobConfigVO = new com.yihu.jw.web.quota.WlyyJobConfigVO();
        BeanUtils.copyProperties(wlyyQuota, wlyyQuotaVO);
        BeanUtils.copyProperties(quartzJobConfig, wlyyJobConfigVO);
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("quota", wlyyQuotaVO);
        params.put("jobConfig", wlyyJobConfigVO);
        if (!StringUtils.isEmpty(quartzJobConfig.getJobClass())) {
            //往quartz框架添加任务
            quartzHelper.addJob(Class.forName(quartzJobConfig.getJobClass()), quartzJobConfig.getQuartzCron(), quartzJobConfig.getId(), params);
            quartzJobConfig.setStatus("1");//设置任务状态是启动
        }
    }
    public void startNowById(String id) throws Exception {
        QuartzJobConfig quartzJobConfig = wlyyJobConfigDao.findOne(id);
        WlyyQuota wlyyQuota = quotaDao.findOne(quartzJobConfig.getQuotaId());
        com.yihu.jw.web.quota.WlyyQuotaVO wlyyQuotaVO = new com.yihu.jw.web.quota.WlyyQuotaVO();
        com.yihu.jw.web.quota.WlyyJobConfigVO wlyyJobConfigVO = new com.yihu.jw.web.quota.WlyyJobConfigVO();
        BeanUtils.copyProperties(wlyyQuota, wlyyQuotaVO);
        BeanUtils.copyProperties(quartzJobConfig, wlyyJobConfigVO);
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("quota", wlyyQuotaVO);
        params.put("jobConfig", wlyyJobConfigVO);
        //往quartz框架添加任务
        if (!StringUtils.isEmpty(quartzJobConfig.getJobClass())) {
            quartzHelper.startNow(Class.forName(quartzJobConfig.getJobClass()), quartzJobConfig.getId()+ UUID.randomUUID(), params);
        }
    }
    public void productDataByDay(Integer day) throws Exception {
        List<QuartzJobConfig> quartzJobConfigs = wlyyJobConfigDao.findByIds();
        for (QuartzJobConfig quartzJobConfig : quartzJobConfigs) {
            WlyyQuota wlyyQuota = quotaDao.findOne(quartzJobConfig.getQuotaId());
            com.yihu.jw.web.quota.WlyyQuotaVO wlyyQuotaVO = new com.yihu.jw.web.quota.WlyyQuotaVO();
            com.yihu.jw.web.quota.WlyyJobConfigVO wlyyJobConfigVO = new com.yihu.jw.web.quota.WlyyJobConfigVO();
            BeanUtils.copyProperties(wlyyQuota, wlyyQuotaVO);
            BeanUtils.copyProperties(quartzJobConfig, wlyyJobConfigVO);
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("quota", wlyyQuotaVO);
            params.put("jobConfig", wlyyJobConfigVO);
            for (int i = 1; i <= day; i++) {
                //往quartz框架添加任务
                params.put("now", getYesterday(0 - i + 1));
                params.put("yesterday", getYesterday(0 - i));
                if (!StringUtils.isEmpty(quartzJobConfig.getJobClass())) {
                    quartzHelper.startNow(Class.forName(quartzJobConfig.getJobClass()), quartzJobConfig.getId() + UUID.randomUUID(), params);
                    Thread.sleep(15000L);
                }
            }
        }
    }
    public static String getYesterday(Integer day) {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DATE, day);
        String yesterday = new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime());
        return yesterday;
    }
    public void productDataByOneDay(String yesterday) throws Exception {
        SimpleDateFormat dataSimple = new SimpleDateFormat("yyyy-MM-dd");
        Date date = dataSimple.parse(yesterday);
        if (date == null) {
            throw new Exception("时间格式错误");
        }
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(date);
        calendar.add(calendar.DATE, 1);//把日期往后增加一天.整数往后推,负数往前移动
        Date nowDate = calendar.getTime();   //这个时间就是日期往后推一天的结果
        String now = new SimpleDateFormat("yyyy-MM-dd").format(nowDate.getTime());
        List<QuartzJobConfig> quartzJobConfigs = wlyyJobConfigDao.findByIds();
        for (QuartzJobConfig quartzJobConfig : quartzJobConfigs) {
            WlyyQuota wlyyQuota = quotaDao.findOne(quartzJobConfig.getQuotaId());
            com.yihu.jw.web.quota.WlyyQuotaVO wlyyQuotaVO = new com.yihu.jw.web.quota.WlyyQuotaVO();
            com.yihu.jw.web.quota.WlyyJobConfigVO wlyyJobConfigVO = new com.yihu.jw.web.quota.WlyyJobConfigVO();
            BeanUtils.copyProperties(wlyyQuota, wlyyQuotaVO);
            BeanUtils.copyProperties(quartzJobConfig, wlyyJobConfigVO);
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("quota", wlyyQuotaVO);
            params.put("jobConfig", wlyyJobConfigVO);
            //往quartz框架添加任务
            params.put("now", now);
            params.put("yesterday", yesterday);
            if (!StringUtils.isEmpty(quartzJobConfig.getJobClass())) {
                quartzHelper.startNow(Class.forName(quartzJobConfig.getJobClass()), quartzJobConfig.getId() + UUID.randomUUID(), params);
                Thread.sleep(15000L);
            }
        }
    }
    public void productDataByOneDayWithId(String yesterday, String id) throws Exception {
        SimpleDateFormat dataSimple = new SimpleDateFormat("yyyy-MM-dd");
        Date date = dataSimple.parse(yesterday);
        if (date == null) {
            throw new Exception("时间格式错误");
        }
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(date);
        calendar.add(calendar.DATE, 1);//把日期往后增加一天.整数往后推,负数往前移动
        Date nowDate = calendar.getTime();   //这个时间就是日期往后推一天的结果
        String now = new SimpleDateFormat("yyyy-MM-dd").format(nowDate.getTime());
        QuartzJobConfig quartzJobConfig = wlyyJobConfigDao.findById(id);
        if (quartzJobConfig == null) {
            throw new Exception("id不存在");
        }
        WlyyQuota wlyyQuota = quotaDao.findOne(quartzJobConfig.getQuotaId());
        com.yihu.jw.web.quota.WlyyQuotaVO wlyyQuotaVO = new com.yihu.jw.web.quota.WlyyQuotaVO();
        com.yihu.jw.web.quota.WlyyJobConfigVO wlyyJobConfigVO = new com.yihu.jw.web.quota.WlyyJobConfigVO();
        BeanUtils.copyProperties(wlyyQuota, wlyyQuotaVO);
        BeanUtils.copyProperties(quartzJobConfig, wlyyJobConfigVO);
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("quota", wlyyQuotaVO);
        params.put("jobConfig", wlyyJobConfigVO);
        //往quartz框架添加任务
        params.put("now", now);
        params.put("yesterday", yesterday);
        if (!StringUtils.isEmpty(quartzJobConfig.getJobClass())) {
            quartzHelper.startNow(Class.forName(quartzJobConfig.getJobClass()), quartzJobConfig.getId() + UUID.randomUUID(), params);
            Thread.sleep(15000L);
        }
    }
    public void productDataByDayAndId(Integer day, String id) throws Exception{
        QuartzJobConfig quartzJobConfig = wlyyJobConfigDao.findById(id);
        if(quartzJobConfig==null){
            throw new Exception("id不存在");
        }
            WlyyQuota wlyyQuota = quotaDao.findOne(quartzJobConfig.getQuotaId());
            com.yihu.jw.web.quota.WlyyQuotaVO wlyyQuotaVO = new WlyyQuotaVO();
            com.yihu.jw.web.quota.WlyyJobConfigVO wlyyJobConfigVO = new com.yihu.jw.web.quota.WlyyJobConfigVO();
            BeanUtils.copyProperties(wlyyQuota, wlyyQuotaVO);
            BeanUtils.copyProperties(quartzJobConfig, wlyyJobConfigVO);
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("quota", wlyyQuotaVO);
            params.put("jobConfig", wlyyJobConfigVO);
            for (int i = 1; i <= day; i++) {
                //往quartz框架添加任务
                params.put("now", getYesterday(0 - i + 1));
                params.put("yesterday", getYesterday(0 - i));
                if (!StringUtils.isEmpty(quartzJobConfig.getJobClass())) {
                    quartzHelper.startNow(Class.forName(quartzJobConfig.getJobClass()), quartzJobConfig.getId() + UUID.randomUUID(), params);
                    Thread.sleep(15000L);
                }
            }
    }
}

+ 927 - 0
svr/svr-iot-job/src/main/java/com/yihu/jw/util/DateUtil.java

@ -0,0 +1,927 @@
package com.yihu.jw.util;
import org.apache.commons.lang3.StringUtils;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.*;
public class DateUtil {
	public static final String HH_MM = "HH:mm";
	public static final String HH_MM_SS = "HH:mm:ss";
	public static final String YY = "yy";
	public static final String YYYYMM = "yyyyMM";
	public static final String YYYYMMDD = "yyyyMMdd";
	public static final String YYYY_MM_DD = "yyyy-MM-dd";
	public static final String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";
	public static final String YYYY_MM_DD_HH = "yyyy-MM-dd HH";
	public static final String YYYY_MM_DD_HH_MM = "yyyy-MM-dd HH:mm";
	public static final String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";
	public static final String YYYY_M_D_HH_MM_SS = "yyyy/M/d HH:mm:ss";
	/**
	 * 时间格式转中文格式
	 */
	public static String dateToChinese(Date date) {
		SimpleDateFormat formatter =   new SimpleDateFormat( "yyyy年MM月dd日 EEEEaaaa hh:mm", Locale.CHINA);
		return formatter.format(date);
	}
	/*public static void main(String[] args)
	{
	   System.out.print(dateToChinese(new Date()));
	}*/
	/**
	 * 字符串转时间格式
	 */
	public static Date strToDate(String strDate) {
		if (StringUtils.isEmpty(strDate)) {
			return null;
		}
		else{
			int length = strDate.length();
			if(strDate.contains("/"))
			{
				strDate = strDate.replace("/","-");
			}
			if(strDate.contains("-"))
			{
				if(length == 10)
				{
					 return strToDate(strDate,YYYY_MM_DD);
				}
				else if(length == 19)
				{
					return strToDate(strDate,YYYY_MM_DD_HH_MM_SS);
				}
			}
			else{
				if(length == 8)
				{
					return strToDate(strDate,YYYYMMDD);
				}
				else if(length == 14)
				{
					return strToDate(strDate,YYYYMMDDHHMMSS);
				}
			}
		}
		return null;
	}
	/**
	  * 获取现在时间
	  * 
	  * @return 返回时间类型 yyyy-MM-dd HH:mm:ss
	  */
	public static Date getNowDate() {
		Date currentTime = new Date();
		SimpleDateFormat formatter = new SimpleDateFormat(YYYY_MM_DD_HH_MM_SS);
		String dateString = formatter.format(currentTime);
		ParsePosition pos = new ParsePosition(0);
		return formatter.parse(dateString, pos);
	}
	/**
	 * 获取现在时间
	 * 
	 * @return返回短时间格式 yyyy-MM-dd
	 */
	public static Date getNowDateShort() {
		Date currentTime = new Date();
		SimpleDateFormat formatter = new SimpleDateFormat(YYYY_MM_DD);
		String dateString = formatter.format(currentTime);
		return strToDate(dateString, YYYY_MM_DD);
	}
	/**
	 * 获取现在时间
	 * 
	 * @return返回字符串格式 yyyy-MM-dd HH:mm:ss
	 */
	public static String getStringDate() {
		Date currentTime = new Date();
		SimpleDateFormat formatter = new SimpleDateFormat(YYYY_MM_DD_HH_MM_SS);
		return formatter.format(currentTime);
	}
	/**
	 * 获取现在时间
	 * 
	 * @return返回字符串格式 yyyy-MM-dd HH:mm:ss
	 */
	public static String getStringDate(String format) {
		Date currentTime = new Date();
		SimpleDateFormat formatter = new SimpleDateFormat(format);
		return formatter.format(currentTime);
	}
	/**
	 * 获取现在时间
	 * 
	 * @return 返回短时间字符串格式yyyy-MM-dd
	 */
	public static String getStringDateShort() {
		Date currentTime = new Date();
		SimpleDateFormat formatter = new SimpleDateFormat(YYYY_MM_DD);
		return formatter.format(currentTime);
	}
	/**
	 * 获取时间 小时:分;秒 HH:mm:ss
	 * 
	 * @return
	 */
	public static String getTimeShort() {
		SimpleDateFormat formatter = new SimpleDateFormat(HH_MM_SS);
		Date currentTime = new Date();
		return formatter.format(currentTime);
	}
	/**
	 * 将长时间格式字符串转换为时间 yyyy-MM-dd HH:mm:ss
	 * 
	 * @param strDate
	 * @return
	 */
	public static Date strToDateLong(String strDate) {
		if (StringUtils.isEmpty(strDate)) {
			return null;
		}
		SimpleDateFormat formatter = new SimpleDateFormat(YYYY_MM_DD_HH_MM_SS);
		ParsePosition pos = new ParsePosition(0);
		return formatter.parse(strDate, pos);
	}
	public static Date strToDateShort(String strDate) {
		if (StringUtils.isEmpty(strDate)) {
			return null;
		}
		SimpleDateFormat formatter = new SimpleDateFormat(YYYY_MM_DD);
		ParsePosition pos = new ParsePosition(0);
		return formatter.parse(strDate, pos);
	}
	/**
	 * 将长时间格式时间转换为字符串 yyyy-MM-dd HH:mm:ss
	 * 
	 * @param dateDate
	 * @return
	 */
	public static String dateToStrLong(Date dateDate) {
		if (dateDate == null) {
			return "";
		}
		SimpleDateFormat formatter = new SimpleDateFormat(YYYY_MM_DD_HH_MM_SS);
		return formatter.format(dateDate);
	}
	public static String dateToStrNoSecond(Date dateDate) {
		if (dateDate == null) {
			return "";
		}
		SimpleDateFormat formatter = new SimpleDateFormat(YYYY_MM_DD_HH_MM);
		return formatter.format(dateDate);
	}
	/**
	 * 将长时间格式时间转换为字符串 yyyy-MM-dd
	 *
	 * @param dateDate
	 * @return
	 */
	public static String dateToStrShort(Date dateDate) {
		if (dateDate == null) {
			return "";
		}
		SimpleDateFormat formatter = new SimpleDateFormat(YYYY_MM_DD);
		return formatter.format(dateDate);
	}
	/**
	 * 将短时间格式时间转换为字符串 yyyy-MM-dd
	 */
	public static String dateToStr(Date dateDate, String format) {
		if (dateDate == null) {
			return "";
		}
		SimpleDateFormat formatter = new SimpleDateFormat(format);
		return formatter.format(dateDate);
	}
	/**
	 * 将短时间格式字符串转换为时间
	 *
	 * @param strDate
	 * @return
	 */
	public static Date strToDate(String strDate, String format) {
		if (StringUtils.isEmpty(strDate)) {
			return null;
		}
		SimpleDateFormat formatter = new SimpleDateFormat(format);
		ParsePosition pos = new ParsePosition(0);
		return formatter.parse(strDate, pos);
	}
	public static Date strToDateAppendNowTime(String strDate, String format) {
		if (StringUtils.isEmpty(strDate)) {
			return null;
		}
		strDate += " " + getTimeShort();
		SimpleDateFormat formatter = new SimpleDateFormat(format);
		ParsePosition pos = new ParsePosition(0);
		return formatter.parse(strDate, pos);
	}
	/**
	 * 得到现在时间
	 *
	 * @return
	 */
	public static Date getNow() {
		Date currentTime = new Date();
		return currentTime;
	}
	/**
	 * 提取一个月中的最后一天
	 *
	 * @param day
	 * @return
	 */
	public static Date getLastDate(long day) {
		Date date = new Date();
		long date_3_hm = date.getTime() - 3600000 * 34 * day;
		Date date_3_hm_date = new Date(date_3_hm);
		return date_3_hm_date;
	}
	/**
	 * 得到现在时间
	 *
	 * @return 字符串 yyyyMMdd HHmmss
	 */
	public static String getStringToday() {
		Date currentTime = new Date();
		SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd HHmmss");
		String dateString = formatter.format(currentTime);
		return dateString;
	}
	/**
	 * 得到现在小时
	 */
	public static String getHour() {
		Date currentTime = new Date();
		SimpleDateFormat formatter = new SimpleDateFormat(YYYY_MM_DD_HH_MM_SS);
		String dateString = formatter.format(currentTime);
		String hour;
		hour = dateString.substring(11, 13);
		return hour;
	}
	/**
	 * 得到现在分钟
	 *
	 * @return
	 */
	public static String getTime() {
		Date currentTime = new Date();
		SimpleDateFormat formatter = new SimpleDateFormat(YYYY_MM_DD_HH_MM_SS);
		String dateString = formatter.format(currentTime);
		String min;
		min = dateString.substring(14, 16);
		return min;
	}
	/**
	 * 根据用户传入的时间表示格式,返回当前时间的格式 如果是yyyyMMdd,注意字母y不能大写。
	 *
	 * @param sformat
	 *            yyyyMMddhhmmss
	 * @return
	 */
	public static String getUserDate(String sformat) {
		Date currentTime = new Date();
		SimpleDateFormat formatter = new SimpleDateFormat(sformat);
		String dateString = formatter.format(currentTime);
		return dateString;
	}
	/**
	 * 二个小时时间间的差值,必须保证二个时间都是"HH:MM"的格式,返回字符型的分钟
	 */
	public static String getTwoHour(String st1, String st2) {
		String[] kk = null;
		String[] jj = null;
		kk = st1.split(":");
		jj = st2.split(":");
		if (Integer.parseInt(kk[0]) < Integer.parseInt(jj[0]))
			return "0";
		else {
			double y = Double.parseDouble(kk[0]) + Double.parseDouble(kk[1]) / 60;
			double u = Double.parseDouble(jj[0]) + Double.parseDouble(jj[1]) / 60;
			if ((y - u) > 0)
				return y - u + "";
			else
				return "0";
		}
	}
	/**
	 * 得到二个日期间的间隔天数
	 */
	public static String getTwoDay(String sj1, String sj2) {
		SimpleDateFormat myFormatter = new SimpleDateFormat(YYYY_MM_DD);
		long day = 0;
		try {
			Date date = myFormatter.parse(sj1);
			Date mydate = myFormatter.parse(sj2);
			day = (date.getTime() - mydate.getTime()) / (24 * 60 * 60 * 1000);
		} catch (Exception e) {
			return "";
		}
		return day + "";
	}
	/**
	 * 时间前推或后推分钟,其中JJ表示分钟.
	 */
	public static String getPreTime(String sj1, String jj) {
		SimpleDateFormat format = new SimpleDateFormat(YYYY_MM_DD_HH_MM_SS);
		String mydate1 = "";
		try {
			Date date1 = format.parse(sj1);
			long Time = (date1.getTime() / 1000) + Integer.parseInt(jj) * 60;
			date1.setTime(Time * 1000);
			mydate1 = format.format(date1);
		} catch (Exception e) {
		}
		return mydate1;
	}
	/**
	 * 时间前推或后推天数(负数前推正数后推)
	 * date 基准时间
	 */
	public static Date getPreDays(Date date, int days) {
		Date day = null;
		try {
			Calendar c = Calendar.getInstance();
			c.setTime(date);
			c.add(Calendar.DATE, days);
			day = c.getTime();
		} catch (Exception e) {
		}
		return day;
	}
	/**
	 * 得到一个时间延后或前移几分钟的时间,nowdate为时间,delay为前移或后延的分钟数
	 */
	public static Date getNextMin(Date date, int delay) {
		try {
			Calendar cal = Calendar.getInstance();
			cal.setTime(date);
			cal.add(Calendar.MINUTE, delay);
			return cal.getTime();
		} catch (Exception e) {
			return null;
		}
	}
	/**
	 * 得到一个时间延后或前移几天的时间,nowdate为时间,delay为前移或后延的天数
	 */
	public static String getNextDay(String nowdate, int delay) {
		try {
			SimpleDateFormat format = new SimpleDateFormat(YYYY_MM_DD);
			String mdate = "";
			Date d = strToDate(nowdate, YYYY_MM_DD);
			long myTime = (d.getTime() / 1000) + delay * 24 * 60 * 60;
			d.setTime(myTime * 1000);
			mdate = format.format(d);
			return mdate;
		} catch (Exception e) {
			return "";
		}
	}
	// public static String getNextDay(Date d, int delay) {
	// try {
	// SimpleDateFormat format = new SimpleDateFormat(YYYY_MM_DD);
	// String mdate = "";
	// long myTime = (d.getTime() / 1000) + delay * 24 * 60 * 60;
	// d.setTime(myTime * 1000);
	// mdate = format.format(d);
	// return mdate;
	// } catch (Exception e) {
	// return "";
	// }
	// }
	public static String getNextDay(Date d, int days) {
		Calendar c = Calendar.getInstance();
		c.setTime(d);
		c.add(Calendar.DATE, days);
		return dateToStrShort(c.getTime());
	}
	public static String getNextMonth(Date d, int months) {
		Calendar c = Calendar.getInstance();
		c.setTime(d);
		c.add(Calendar.MONTH, months);
		return dateToStrShort(c.getTime());
	}
	public static String getNextYear(Date d, int year) {
		Calendar c = Calendar.getInstance();
		c.setTime(d);
		c.add(Calendar.YEAR, year);
		return dateToStrShort(c.getTime());
	}
	/**
	 * 获取本月第一天
	 * @return
     */
	public static String getCurMonthFirstDayShort(){
		Calendar c = Calendar.getInstance();
		c.set(Calendar.DAY_OF_MONTH,1);//设置为1号,当前日期既为本月第一天
		return dateToStrShort(c.getTime());
	}
	/**
	 * 判断是否润年
	 *
	 * @param ddate
	 * @return
	 */
	public static boolean isLeapYear(String ddate) {
		/**
		 * 详细设计: 1.被400整除是闰年,否则: 2.不能被4整除则不是闰年 3.能被4整除同时不能被100整除则是闰年
		 * 3.能被4整除同时能被100整除则不是闰年
		 */
		Date d = strToDate(ddate, YYYY_MM_DD);
		GregorianCalendar gc = (GregorianCalendar) Calendar.getInstance();
		gc.setTime(d);
		int year = gc.get(Calendar.YEAR);
		if ((year % 400) == 0)
			return true;
		else if ((year % 4) == 0) {
			if ((year % 100) == 0)
				return false;
			else
				return true;
		} else
			return false;
	}
	/**
	 * 返回美国时间格式 26 Apr 2006
	 *
	 * @param str
	 * @return
	 */
	public static String getEDate(String str) {
		SimpleDateFormat formatter = new SimpleDateFormat(YYYY_MM_DD);
		ParsePosition pos = new ParsePosition(0);
		Date strtodate = formatter.parse(str, pos);
		String j = strtodate.toString();
		String[] k = j.split(" ");
		return k[2] + k[1].toUpperCase() + k[5].substring(2, 4);
	}
	/**
	 * 获取一个月的最后一天
	 *
	 * @param dat
	 * @return
	 */
	public static String getEndDateOfMonth(String dat) {// yyyy-MM-dd
		String str = dat.substring(0, 8);
		String month = dat.substring(5, 7);
		int mon = Integer.parseInt(month);
		if (mon == 1 || mon == 3 || mon == 5 || mon == 7 || mon == 8 || mon == 10 || mon == 12) {
			str += "31";
		} else if (mon == 4 || mon == 6 || mon == 9 || mon == 11) {
			str += "30";
		} else {
			if (isLeapYear(dat)) {
				str += "29";
			} else {
				str += "28";
			}
		}
		return str;
	}
	/**
	 * 判断二个时间是否在同一个周
	 *
	 * @param date1
	 * @param date2
	 * @return
	 */
	public static boolean isSameWeekDates(Date date1, Date date2) {
		Calendar cal1 = Calendar.getInstance();
		Calendar cal2 = Calendar.getInstance();
		cal1.setTime(date1);
		cal2.setTime(date2);
		int subYear = cal1.get(Calendar.YEAR) - cal2.get(Calendar.YEAR);
		if (0 == subYear) {
			if (cal1.get(Calendar.WEEK_OF_YEAR) == cal2.get(Calendar.WEEK_OF_YEAR))
				return true;
		} else if (1 == subYear && 11 == cal2.get(Calendar.MONTH)) {
			// 如果12月的最后一周横跨来年第一周的话则最后一周即算做来年的第一周
			if (cal1.get(Calendar.WEEK_OF_YEAR) == cal2.get(Calendar.WEEK_OF_YEAR))
				return true;
		} else if (-1 == subYear && 11 == cal1.get(Calendar.MONTH)) {
			if (cal1.get(Calendar.WEEK_OF_YEAR) == cal2.get(Calendar.WEEK_OF_YEAR))
				return true;
		}
		return false;
	}
	/**
	 * 产生周序列,即得到当前时间所在的年度是第几周
	 *
	 * @return
	 */
	public static String getSeqWeek() {
		Calendar c = Calendar.getInstance(Locale.CHINA);
		String week = Integer.toString(c.get(Calendar.WEEK_OF_YEAR));
		if (week.length() == 1)
			week = "0" + week;
		String year = Integer.toString(c.get(Calendar.YEAR));
		return year + week;
	}
	/**
	 * 获得一个日期所在的周的星期几的日期,如要找出2002年2月3日所在周的星期一是几号
	 *
	 * @param sdate
	 * @param num
	 * @return
	 */
	public static String getWeek(String sdate, String num) {
		// 再转换为时间
		Date dd = DateUtil.strToDate(sdate, YYYY_MM_DD);
		Calendar c = Calendar.getInstance();
		c.setTime(dd);
		if (num.equals("1")) // 返回星期一所在的日期
			c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
		else if (num.equals("2")) // 返回星期二所在的日期
			c.set(Calendar.DAY_OF_WEEK, Calendar.TUESDAY);
		else if (num.equals("3")) // 返回星期三所在的日期
			c.set(Calendar.DAY_OF_WEEK, Calendar.WEDNESDAY);
		else if (num.equals("4")) // 返回星期四所在的日期
			c.set(Calendar.DAY_OF_WEEK, Calendar.THURSDAY);
		else if (num.equals("5")) // 返回星期五所在的日期
			c.set(Calendar.DAY_OF_WEEK, Calendar.FRIDAY);
		else if (num.equals("6")) // 返回星期六所在的日期
			c.set(Calendar.DAY_OF_WEEK, Calendar.SATURDAY);
		else if (num.equals("0")) // 返回星期日所在的日期
			c.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
		return new SimpleDateFormat("yyyy-MM-dd").format(c.getTime());
	}
	/**
	 * 获取2个时间点的工作日天数
	 * @param startDate 开始时间
	 * @param endDate 结束时间
	 * @return
	 */
	public static int getDutyDays(Date startDate, Date endDate) {
		int result = 0;
        Date  startTime = new Date(startDate.getTime());
		while (startTime.compareTo(endDate) <= 0) {
			if (startTime.getDay() != 6 && startTime.getDay() != 0) {
				result++;
			}
            startTime.setDate(startTime.getDate() + 1);
		}
		return result;
	}
	/**
	 * 根据一个日期,返回是星期几的字符串
	 *
	 * @param sdate
	 * @return
	 */
	public static String getWeek(String sdate) {
		// 再转换为时间
		Date date = DateUtil.strToDate(sdate, YYYY_MM_DD);
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		// int hour=c.get(Calendar.DAY_OF_WEEK);
		// hour中存的就是星期几了,其范围 1~7
		// 1=星期日 7=星期六,其他类推
		return new SimpleDateFormat("EEEE").format(c.getTime());
	}
	public static String getWeekStr(String sdate) {
		String str = "";
		str = DateUtil.getWeek(sdate);
		if ("1".equals(str)) {
			str = "星期日";
		} else if ("2".equals(str)) {
			str = "星期一";
		} else if ("3".equals(str)) {
			str = "星期二";
		} else if ("4".equals(str)) {
			str = "星期三";
		} else if ("5".equals(str)) {
			str = "星期四";
		} else if ("6".equals(str)) {
			str = "星期五";
		} else if ("7".equals(str)) {
			str = "星期六";
		}
		return str;
	}
	/**
	 * 两个时间之间的天数
	 *
	 * @param date1
	 * @param date2
	 * @return
	 */
	public static long getDays(String date1, String date2) {
		if (date1 == null || date1.equals(""))
			return 0;
		if (date2 == null || date2.equals(""))
			return 0;
		// 转换为标准时间
		SimpleDateFormat myFormatter = new SimpleDateFormat(YYYY_MM_DD);
		Date date = null;
		Date mydate = null;
		try {
			date = myFormatter.parse(date1);
			mydate = myFormatter.parse(date2);
		} catch (Exception e) {
		}
		long day = (date.getTime() - mydate.getTime()) / (24 * 60 * 60 * 1000);
		return day;
	}
	/**
	 * 返回两个日期相差的天数
	 * @param date1
	 * @param date2
	 * @return
	 */
	public static long getDays(Date date1, Date date2) {
		if (date1 == null || date2 == null)
			return 0;
		long day = (date1.getTime() - date2.getTime()) / (24 * 60 * 60 * 1000);
		return day;
	}
	/**
	 * 形成如下的日历 , 根据传入的一个时间返回一个结构 星期日 星期一 星期二 星期三 星期四 星期五 星期六 下面是当月的各个时间
	 * 此函数返回该日历第一行星期日所在的日期
	 * 
	 * @param sdate
	 * @return
	 */
	public static String getNowMonth(String sdate) {
		// 取该时间所在月的一号
		sdate = sdate.substring(0, 8) + "01";
		// 得到这个月的1号是星期几
		Date date = DateUtil.strToDate(sdate, YYYY_MM_DD);
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		int u = c.get(Calendar.DAY_OF_WEEK);
		String newday = DateUtil.getNextDay(sdate, 1 - u);
		return newday;
	}
	/**
	 * 取得数据库主键 生成格式为yyyymmddhhmmss+k位随机数
	 * 
	 * @param k 表示是取几位随机数,可以自己定
	 */
	public static String getNo(int k) {
		return getUserDate("yyyyMMddhhmmss") + getRandom(k);
	}
	/**
	 * 返回一个随机数
	 * 
	 * @param i
	 * @return
	 */
	public static String getRandom(int i) {
		Random jjj = new Random();
		if (i == 0)
			return "";
		String jj = "";
		for (int k = 0; k < i; k++) {
			jj = jj + jjj.nextInt(9);
		}
		return jj;
	}
	/**
	 * 根据用户生日计算年龄
	 */
	public static int getAgeByBirthday(Date birthday) {
		try {
			int age = 0;
			if (birthday == null) {
				return age;
			}
			String birth = new SimpleDateFormat("yyyyMMdd").format(birthday);
			int year = Integer.valueOf(birth.substring(0, 4));
			int month = Integer.valueOf(birth.substring(4, 6));
			int day = Integer.valueOf(birth.substring(6));
			Calendar cal = Calendar.getInstance();
			age = cal.get(Calendar.YEAR) - year;
			//周岁计算
			if (cal.get(Calendar.MONTH) < (month - 1) || (cal.get(Calendar.MONTH) == (month - 1) && cal.get(Calendar.DATE) < day)) {
				age--;
			}
			return age;
		} catch (Exception e) {
			return 0;
		}
	}
	/**
	 *  字符串转时间
	 * @param str 时间字符串
	 * @param eg 格式
	 * @return
	 */
	public static Date stringToDate(String str, String eg) {
		DateFormat format = new SimpleDateFormat(eg);
		Date date = null;
		if (str != null && !"".equals(str)) {
			try {
				date = format.parse(str);
			} catch (Exception e) {
				return null;
			}
		}
		return date;
	}
	public static int getNowMonth(){
		Calendar cal = Calendar.getInstance();
		return cal.get(Calendar.MONTH)+1;
	}
	public static int getNowYear(){
		Calendar cal = Calendar.getInstance();
		return cal.get(Calendar.YEAR);
	}
	/**
	 * 获取周一
	 * @return
     */
	public static String getMondayOfThisWeek() {
		SimpleDateFormat df2 = new SimpleDateFormat("yyyy-MM-dd");
		Calendar c = Calendar.getInstance();
		int day_of_week = c.get(Calendar.DAY_OF_WEEK) - 1;
		if (day_of_week == 0)
			day_of_week = 7;
		c.add(Calendar.DATE, -day_of_week + 1);
		return df2.format(c.getTime());
	}
	/**
	 * 得到本周周日
	 *
	 * @return yyyy-MM-dd
	 */
	public static String getSundayOfThisWeek() {
		SimpleDateFormat df2 = new SimpleDateFormat("yyyy-MM-dd");
		Calendar c = Calendar.getInstance();
		int day_of_week = c.get(Calendar.DAY_OF_WEEK) - 1;
		if (day_of_week == 0)
			day_of_week = 7;
		c.add(Calendar.DATE, -day_of_week + 7);
		return df2.format(c.getTime());
	}
	/**
	 * 获取当月第一天
	 * @return
     */
	public static String getFristDayOfMonth() {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		// 获取前月的第一天
		Calendar c = Calendar.getInstance();
		c.add(Calendar.MONTH, 0);
		c.set(Calendar.DAY_OF_MONTH,1);//设置为1号,当前日期既为本月第一天
		String first = format.format(c.getTime());
		return format.format(c.getTime());
	}
	/**
	 * 获取当月最后一天
	 */
	public static String getLastDayOfMonth(){
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		// 获取前月的第一天
		Calendar ca = Calendar.getInstance();
		ca.set(Calendar.DAY_OF_MONTH, ca.getActualMaximum(Calendar.DAY_OF_MONTH));
		return format.format(ca.getTime());
	}
	public static int getSignYear(){
		Calendar ca = Calendar.getInstance();
		if(getNowMonth()>=4){
			return getNowYear();
		}
		return getNowYear()-1;
	}
	/**
	 * 计算预产期
	 * 末次月经开始日期(第一天),月份+9,日期+7
	 * @param date
	 * @return
	 */
	public static Date getDueDate(Date date){
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		cal.add(Calendar.MONTH,9);
		cal.add(Calendar.DAY_OF_YEAR,7);
		return cal.getTime();
	}
	/**
	 * 计算产检时间
	 * @param date
	 * @param day
	 * @return
	 */
	public static Date getPrenatalInspectorDate(Date date,Integer day){
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		cal.add(Calendar.DAY_OF_YEAR,day);
		return cal.getTime();
	}
	
	/**
	 * 转换日期字符串为Timestamp YYYY-MM-DD HH:MM:SS
	 * @return
	 */
	public static Timestamp fomrmatStringToTimeStamp(String dateStr){
		
		Timestamp ts = Timestamp.valueOf(dateStr);
		
		return ts;
	}
	
	/**
	 * 获取当前时间的Timestamp
	 * @return
	 */
	public static Timestamp getNowTimestamp(){
		Date date = new Date();
		Timestamp nousedate = new Timestamp(date.getTime());
		return nousedate;
	}
	/**
	 * 获取周一
	 * @return
	 */
	public static String getSundayOfThisDate(Date date) {
		SimpleDateFormat df2 = new SimpleDateFormat(YYYY_MM_DD_HH_MM_SS);
		return df2.format(getSundayOfThisDateToDate(date));
	}
	/**
	 * 得到本周周日
	 *
	 * @return yyyy-MM-dd
	 */
	public static Date getSundayOfThisDateToDate(Date date) {
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		int day_of_week = c.get(Calendar.DAY_OF_WEEK) - 1;
		if (day_of_week == 0)
			day_of_week = 7;
		c.add(Calendar.DATE, -day_of_week + 7);
		return c.getTime();
	}
}

+ 208 - 0
svr/svr-iot-job/src/main/java/com/yihu/jw/util/SystemConf.java

@ -0,0 +1,208 @@
package com.yihu.jw.util;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
@Component
public class SystemConf {
    // 别处登录
    public static final int LOGIN_OTHER = 999;
    // 登录超时
    public static final int LOGIN_TIMEOUT = 998;
    // 未登录
    public static final int NOT_LOGIN = 997;
    // 文件保存临时路径
    private static final String TEMP_PATH = "upload_temp_path";
    // 血糖餐前最小值
    public static final double HEALTH_STANDARD_ST_MIN_BEFORE = 4;
    // 血糖餐前最大值
    public static final double HEALTH_STANDARD_ST_MAX_BEFORE = 7;
    // 血糖餐后最小值
    public static final double HEALTH_STANDARD_ST_MIN_AFTER = 4;
    // 血糖餐后最大值
    public static final double HEALTH_STANDARD_ST_MAX_AFTER = 11.1;
    // 舒张压最小值
    public static final double HEALTH_STANDARD_SZY_MIN = 60;
    // 舒张压最大值
    public static final double HEALTH_STANDARD_SZY_MAX = 90;
    // 收缩压最小值
    public static final double HEALTH_STANDARD_SSY_MIN = 90;
    // 收缩压最大值
    public static final double HEALTH_STANDARD_SSY_MAX = 140;
    // 同一手机号大最短信数
    public static final int MAX_SMS_MOBILE = 5;
    // 发送短信验证码间隔(分钟)
    public static final int SMS_INTERVAL = 2;
    private static Object lock = new Object();
    // 全局系统配置信息
    private static SystemConf systemConf;
    // 系统配置文件
    private Properties systemProperties;
    //im列表
    private String imListGet;
    public static SystemConf getInstance() {
        if (systemConf == null) {
            synchronized (lock) {
                systemConf = new SystemConf();
            }
        }
        return systemConf;
    }
    /**
     * 加载系统配置文件
     *
     * @return
     */
    public Properties getSystemProperties() {
        if (systemProperties == null) {
            InputStream is = null;
            try {
                is = this.getClass().getResourceAsStream("/system.properties");
                systemProperties = new Properties();
                systemProperties.load(is);
            } catch (IOException e1) {
                e1.printStackTrace();
            } finally {
                if (is != null) {
                    try {
                        is.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return systemProperties;
    }
    /**
     * 短信接口地址
     */
    public String getSmsUrl() {
        return getSystemProperties().getProperty("yihu_sms_url");
    }
    /**
     * 短信企业编号
     */
    public String getSmsCode() {
        return getSystemProperties().getProperty("yihu_sms_code");
    }
    /**
     * 短信用户名
     */
    public String getSmsName() {
        return getSystemProperties().getProperty("yihu_sms_name");
    }
    /**
     * 短信登录密码
     */
    public String getSmsPassword() {
        return getSystemProperties().getProperty("yihu_sms_password");
    }
    ;
    /**
     * 挂号接口地址
     */
    public String getGuahaoUrl() {
        return getSystemProperties().getProperty("yihu_guahao_url");
    }
    /**
     * 挂号接口对接appid
     */
    public String getGuahaoAppid() {
        return getSystemProperties().getProperty("yihu_guahao_appid");
    }
    /**
     * 挂号接口对接app secret
     */
    public String getGuahaoSecret() {
        return getSystemProperties().getProperty("yihu_guahao_secret");
    }
    /**
     * 获取文件保存的临时路径
     *
     * @return
     */
    public String getTempPath() {
        return getSystemProperties().getProperty(TEMP_PATH);
    }
    /**
     * 获取图片存在地址
     *
     * @return
     */
    /**
     * 获取服务全路径
     *
     * @return
     */
    /******************************** 挂号配置 ********************************************/
    /**
     * 获取厦门预约服务地址
     */
    public String getXMGuahaoUrl() {
        return getSystemProperties().getProperty("guahao_url");
    }
    /**
     * 获取厦门预约服务命名空间
     */
    public String getXMGuahaoNamespace() {
        return getSystemProperties().getProperty("guahao_namespace");
    }
    /****************************************************************************************/
    /********************************* EHR配置 **********************************************/
    /**
     * 是否启用EHR演示
     */
    public Boolean getEhrUsed() {
        return Boolean.valueOf(getSystemProperties().getProperty("ehr_used"));
    }
    /**
     * EHR档案服务地址
     */
    public String getEhrServices() {
        return getSystemProperties().getProperty("ehr_services");
    }
    /**
     * EHR底层地址
     */
    public String getEhrServicesBase() {
        return getSystemProperties().getProperty("ehr_services_base");
    }
    /**************************************************************************************/
    /**************************************************************************************/
}

+ 41 - 0
svr/svr-iot-job/src/main/java/com/yihu/jw/util/http/HttpResponse.java

@ -0,0 +1,41 @@
package com.yihu.jw.util.http;
/**
 * Utils - Http请求辅助类,简化页面页面判断逻辑
 * Created by progr1mmer on 2018/1/16.
 */
public class HttpResponse {
    private int status;
    private String content;
    public HttpResponse(int status, String content) {
        this.status = status;
        this.content = content;
    }
    public int getStatus() {
        return status;
    }
    public void setStatus(int status) {
        this.status = status;
    }
    public String getContent() {
        return content;
    }
    public void setContent(String content) {
        this.content = content;
    }
    public boolean isSuccessFlg() {
        return status == 200;
    }
    public String getErrorMsg() {
        return content;
    }
}

+ 382 - 0
svr/svr-iot-job/src/main/java/com/yihu/jw/util/http/HttpUtils.java

@ -0,0 +1,382 @@
package com.yihu.jw.util.http;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.util.StringUtils;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
 * Utils - HTTP请求辅助工具类
 * Created by progr1mmer on 2017/9/27.
 */
public class HttpUtils {
    public static HttpResponse doGet(String url, Map<String, Object> params) throws Exception {
        return doGet(url, params, null);
    }
    public static HttpResponse doGet(String url, Map<String, Object> params, Map<String, String> headers) throws Exception {
        return doGet(url, params, headers, null, null);
    }
    public static HttpResponse doGet(String url, Map<String, Object> params, Map<String, String> headers, String username, String password) throws Exception {
        String response;
        int status;
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse closeableHttpResponse = null;
        List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
        if (params != null) {
            for (String key : params.keySet()) {
                Object value = params.get(key);
                if (value != null) {
                    nameValuePairList.add(new BasicNameValuePair(key, String.valueOf(params.get(key))));
                }
            }
        }
        String paramStr = EntityUtils.toString(new UrlEncodedFormEntity(nameValuePairList, "UTF-8"));
        HttpGet httpGet = new HttpGet(url + "?" + paramStr);
        if (headers != null) {
            for (String key : headers.keySet()) {
                httpGet.addHeader(key, headers.get(key));
            }
        }
        try {
            if (!StringUtils.isEmpty(username) && !StringUtils.isEmpty(password)) {
                UsernamePasswordCredentials usernamePasswordCredentials = new UsernamePasswordCredentials(username, password);
                CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
                credentialsProvider.setCredentials(AuthScope.ANY, usernamePasswordCredentials);
                httpClient = HttpClients.custom().setDefaultCredentialsProvider(credentialsProvider).build();
            } else {
                httpClient = HttpClients.createDefault();
            }
            closeableHttpResponse = httpClient.execute(httpGet);
            HttpEntity resEntity = closeableHttpResponse.getEntity();
            status = closeableHttpResponse.getStatusLine().getStatusCode();
            response = getRespString(resEntity);
        } finally {
            try {
                if (closeableHttpResponse != null) {
                    closeableHttpResponse.close();
                }
                if (httpClient != null) {
                    httpClient.close();
                }
            }catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (status != HttpStatus.SC_OK) {
//            LogService.getLogger().error(" GET: " + url + " " + status);
        }
        HttpResponse httpResponse = new HttpResponse(status, response);
        return httpResponse;
    }
    public static HttpResponse doPost(String url, Map<String, Object> params) throws Exception {
        return doPost(url, params, null);
    }
    public static HttpResponse doPost(String url, Map<String, Object> params, Map<String, String> headers) throws Exception{
        return doPost(url, params, headers, null, null);
    }
    public static HttpResponse doPost(String url, Map<String, Object> params, Map<String, String> headers, String username, String password) throws Exception{
        String response;
        int status;
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse closeableHttpResponse = null;
        HttpPost httpPost = new HttpPost(url);
        List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
        if (params != null) {
            for (String key : params.keySet()) {
                Object value = params.get(key);
                if (value != null) {
                    nameValuePairList.add(new BasicNameValuePair(key, String.valueOf(params.get(key))));
                }
            }
        }
        httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairList, "UTF-8"));
        if (headers != null) {
            for (String key : headers.keySet()) {
                httpPost.addHeader(key, headers.get(key));
            }
        }
        try {
            if (!StringUtils.isEmpty(username) && !StringUtils.isEmpty(password)) {
                UsernamePasswordCredentials usernamePasswordCredentials = new UsernamePasswordCredentials(username, password);
                CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
                credentialsProvider.setCredentials(AuthScope.ANY, usernamePasswordCredentials);
                httpClient = HttpClients.custom().setDefaultCredentialsProvider(credentialsProvider).build();
            } else {
                httpClient = HttpClients.createDefault();
            }
            closeableHttpResponse = httpClient.execute(httpPost);
            HttpEntity resEntity = closeableHttpResponse.getEntity();
            status = closeableHttpResponse.getStatusLine().getStatusCode();
            response = getRespString(resEntity);
        } finally {
            try {
                if (closeableHttpResponse != null) {
                    closeableHttpResponse.close();
                }
                if (httpClient != null) {
                    httpClient.close();
                }
            }catch (Exception e) {
                e.printStackTrace();
            }
        }
        if(status != HttpStatus.SC_OK) {
//            LogService.getLogger().error(" POST: " + url + " " + status);
        }
        HttpResponse httpResponse = new HttpResponse(status, response);
        return httpResponse;
    }
    public static HttpResponse doJsonPost(String url, String jsonData, Map<String, String> headers, String username, String password) throws Exception{
        String response;
        int status;
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse closeableHttpResponse = null;
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
        httpPost.setEntity(new StringEntity(jsonData, "UTF-8"));
        if (headers != null) {
            for (String key : headers.keySet()) {
                httpPost.addHeader(key, headers.get(key));
            }
        }
        try {
            if (!StringUtils.isEmpty(username) && !StringUtils.isEmpty(password)) {
                UsernamePasswordCredentials usernamePasswordCredentials = new UsernamePasswordCredentials(username, password);
                CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
                credentialsProvider.setCredentials(AuthScope.ANY, usernamePasswordCredentials);
                httpClient = HttpClients.custom().setDefaultCredentialsProvider(credentialsProvider).build();
            } else {
                httpClient = HttpClients.createDefault();
            }
            closeableHttpResponse = httpClient.execute(httpPost);
            HttpEntity resEntity = closeableHttpResponse.getEntity();
            status = closeableHttpResponse.getStatusLine().getStatusCode();
            response = getRespString(resEntity);
        } finally {
            try {
                if (closeableHttpResponse != null) {
                    closeableHttpResponse.close();
                }
                if (httpClient != null) {
                    httpClient.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if(status != HttpStatus.SC_OK) {
//            LogService.getLogger().error(" POST: " + url + " " + status);
        }
        HttpResponse httpResponse = new HttpResponse(status, response);
        return httpResponse;
    }
    public static HttpResponse doPut(String url, Map<String, Object> params) throws Exception {
        return doPut(url, params, null);
    }
    public static HttpResponse doPut(String url, Map<String, Object> params, Map<String, String> headers) throws Exception {
        return doPut(url, params, headers, null, null);
    }
    public static HttpResponse doPut(String url, Map<String, Object> params, Map<String, String> headers, String username, String password) throws Exception {
        String response;
        int status;
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse closeableHttpResponse = null;
        HttpPut httpPut = new HttpPut(url);
        List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
        if (params != null) {
            for (String key : params.keySet()) {
                Object value = params.get(key);
                if (value != null) {
                    nameValuePairList.add(new BasicNameValuePair(key, String.valueOf(params.get(key))));
                }
            }
        }
        httpPut.setEntity(new UrlEncodedFormEntity(nameValuePairList, "UTF-8"));
        if (headers != null) {
            for (String key : headers.keySet()) {
                httpPut.addHeader(key, headers.get(key));
            }
        }
        try {
            if (!StringUtils.isEmpty(username) && !StringUtils.isEmpty(password)) {
                UsernamePasswordCredentials usernamePasswordCredentials = new UsernamePasswordCredentials(username, password);
                CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
                credentialsProvider.setCredentials(AuthScope.ANY, usernamePasswordCredentials);
                httpClient = HttpClients.custom().setDefaultCredentialsProvider(credentialsProvider).build();
            } else {
                httpClient = HttpClients.createDefault();
            }
            closeableHttpResponse = httpClient.execute(httpPut);
            HttpEntity resEntity = closeableHttpResponse.getEntity();
            status = closeableHttpResponse.getStatusLine().getStatusCode();
            response = getRespString(resEntity);
        } finally {
            try {
                if (closeableHttpResponse != null) {
                    closeableHttpResponse.close();
                }
                if (httpClient != null) {
                    httpClient.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (status != HttpStatus.SC_OK) {
//            LogService.getLogger().error(" PUT: " + url + " " + status);
        }
        HttpResponse httpResponse = new HttpResponse(status, response);
        return httpResponse;
    }
    public static HttpResponse doJsonPut(String url, String jsonData, Map<String, String> headers, String username, String password) throws Exception {
        String response;
        int status;
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse closeableHttpResponse = null;
        HttpPut httpPut = new HttpPut(url);
        httpPut.setHeader("Content-Type", "application/json;charset=UTF-8");
        httpPut.setEntity(new StringEntity(jsonData, "UTF-8"));
        if (headers != null) {
            for (String key : headers.keySet()) {
                httpPut.addHeader(key, headers.get(key));
            }
        }
        try {
            if (!StringUtils.isEmpty(username) && !StringUtils.isEmpty(password)) {
                UsernamePasswordCredentials usernamePasswordCredentials = new UsernamePasswordCredentials(username, password);
                CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
                credentialsProvider.setCredentials(AuthScope.ANY, usernamePasswordCredentials);
                httpClient = HttpClients.custom().setDefaultCredentialsProvider(credentialsProvider).build();
            } else {
                httpClient = HttpClients.createDefault();
            }
            closeableHttpResponse = httpClient.execute(httpPut);
            HttpEntity resEntity = closeableHttpResponse.getEntity();
            status = closeableHttpResponse.getStatusLine().getStatusCode();
            response = getRespString(resEntity);
        } finally {
            try {
                if (closeableHttpResponse != null) {
                    closeableHttpResponse.close();
                }
                if (httpClient != null) {
                    httpClient.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (status != HttpStatus.SC_OK) {
//            LogService.getLogger().error(" PUT: " + url + " " + status);
        }
        HttpResponse httpResponse = new HttpResponse(status, response);
        return httpResponse;
    }
    public static HttpResponse doDelete(String url, Map<String, Object> params) throws Exception {
        return doDelete(url, params, null);
    }
    public static HttpResponse doDelete(String url, Map<String, Object> params, Map<String, String> headers) throws Exception {
        return doDelete(url, params, headers, null, null);
    }
    public static HttpResponse doDelete(String url, Map<String, Object> params, Map<String, String> headers, String username, String password) throws Exception {
        String response;
        int status;
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse closeableHttpResponse = null;
        List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
        if (params != null) {
            for (String key : params.keySet()) {
                Object value = params.get(key);
                if (value != null) {
                    nameValuePairList.add(new BasicNameValuePair(key, String.valueOf(params.get(key))));
                }
            }
        }
        String paramStr = EntityUtils.toString(new UrlEncodedFormEntity(nameValuePairList, "UTF-8"));
        HttpDelete httpDelete = new HttpDelete(url + "?" + paramStr);
        if (headers != null) {
            for (String key : headers.keySet()) {
                httpDelete.addHeader(key, headers.get(key));
            }
        }
        try {
            if (!StringUtils.isEmpty(username) && !StringUtils.isEmpty(password)) {
                UsernamePasswordCredentials usernamePasswordCredentials = new UsernamePasswordCredentials(username, password);
                CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
                credentialsProvider.setCredentials(AuthScope.ANY, usernamePasswordCredentials);
                httpClient = HttpClients.custom().setDefaultCredentialsProvider(credentialsProvider).build();
            } else {
                httpClient = HttpClients.createDefault();
            }
            closeableHttpResponse = httpClient.execute(httpDelete);
            HttpEntity resEntity = closeableHttpResponse.getEntity();
            status = closeableHttpResponse.getStatusLine().getStatusCode();
            response = getRespString(resEntity);
        } finally {
            try {
                if (closeableHttpResponse != null) {
                    closeableHttpResponse.close();
                }
                if (httpClient != null) {
                    httpClient.close();
                }
            }catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (status != HttpStatus.SC_OK) {
//            LogService.getLogger().error(" DELETE: " + url + " " + status);
        }
        HttpResponse httpResponse = new HttpResponse(status, response);
        return httpResponse;
    }
    private static String getRespString(HttpEntity entity) throws Exception {
        if (entity == null) {
            return null;
        }
        InputStream is = entity.getContent();
        BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
        StringBuilder stringBuilder = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            stringBuilder.append(line);
        }
        return stringBuilder.toString();
    }
}

+ 54 - 0
svr/svr-iot-job/src/main/java/com/yihu/jw/util/http/IPInfoUtils.java

@ -0,0 +1,54 @@
package com.yihu.jw.util.http;
import javax.servlet.http.HttpServletRequest;
/**
 * Utils - ip信息辅助工具类
 * Created by progr1mmer on 2018/1/18.
 */
public class IPInfoUtils {
    private static final long A1 = getIpNum("10.0.0.0");
    private static final long A2 = getIpNum("10.255.255.255");
    private static final long B1 = getIpNum("172.16.0.0");
    private static final long B2 = getIpNum("172.31.255.255");
    private static final long C1 = getIpNum("192.168.0.0");
    private static final long C2 = getIpNum("192.168.255.255");
    private static final long D1 = getIpNum("10.44.0.0");
    private static final long D2 = getIpNum("10.69.0.255");
    private static long getIpNum(String ipAddress) {
        String [] ip = ipAddress.split("\\.");
        long a = Integer.parseInt(ip[0]);
        long b = Integer.parseInt(ip[1]);
        long c = Integer.parseInt(ip[2]);
        long d = Integer.parseInt(ip[3]);
        return a * 256 * 256 * 256 + b * 256 * 256 + c * 256 + d;
    }
    public static boolean isInnerIP(String ip){
        long n = getIpNum(ip);
        return (n >= A1 && n <= A2) || (n >= B1 && n <= B2) || (n >= C1 && n <= C2) || (n >= D1 && n <= D2);
    }
    public static String getIPAddress(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
}

+ 571 - 0
svr/svr-iot-job/src/main/java/com/yihu/jw/web/BaseController.java

@ -0,0 +1,571 @@
package com.yihu.jw.web;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.jw.restmodel.web.ObjEnvelop;
import com.yihu.jw.util.DateUtil;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.util.ReflectionUtils;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;
import java.util.*;
public class BaseController {
    private static Logger logger = LoggerFactory.getLogger(BaseController.class);
    @Autowired
    protected HttpServletRequest request;
    /**
     * 獲取髮送請求用戶的uid
     *
     * @return
     */
    public String getUID() {
        try {
            String userAgent = request.getHeader("userAgent");
            if (StringUtils.isEmpty(userAgent)) {
                userAgent = request.getHeader("User-Agent");
            }
            JSONObject json = new JSONObject(userAgent);
            return json.getString("uid");
        } catch (Exception e) {
            return null;
        }
    }
    /**
     * 获取被代理人的code
     * @return
     */
    public String getRepresentedUID() {
        try {
            String userAgent = request.getHeader("userAgent");
            if (StringUtils.isEmpty(userAgent)) {
                userAgent = request.getHeader("User-Agent");
            }
            JSONObject json = new JSONObject(userAgent);
            return json.getString("represented");
        } catch (Exception e) {
            return null;
        }
    }
    /**
     * 获取被代理人code,若没有则返回当前登录者
     * @return
     */
    public String getRepUID(){
        try {
            String userAgent = request.getHeader("userAgent");
            if (StringUtils.isEmpty(userAgent)) {
                userAgent = request.getHeader("User-Agent");
            }
            JSONObject json = new JSONObject(userAgent);
            if(json.isNull("represented")){
                return json.getString("uid");
            }
            return json.getString("represented");
        } catch (Exception e) {
            return null;
        }
    }
    /**
     * 獲取髮送請求用戶的uid
     *
     * @return
     */
    public String getLastUid() {
        try {
            String userAgent = request.getHeader("userAgent");
            if (StringUtils.isEmpty(userAgent)) {
                userAgent = request.getHeader("User-Agent");
            }
            JSONObject json = new JSONObject(userAgent);
            return json.getString("lastUid");
        } catch (Exception e) {
            return null;
        }
    }
    public String getAppVersion() {
        try {
            String userAgent = request.getHeader("userAgent");
            if (StringUtils.isEmpty(userAgent)) {
                userAgent = request.getHeader("User-Agent");
            }
            JSONObject json = new JSONObject(userAgent);
            return json.getString("appVersion");
        } catch (Exception e) {
            return null;
        }
    }
    public String getOpenid() {
        try {
            String userAgent = request.getHeader("userAgent");
            if (StringUtils.isEmpty(userAgent)) {
                userAgent = request.getHeader("User-Agent");
            }
            JSONObject json = new JSONObject(userAgent);
            return json.getString("openid");
        } catch (Exception e) {
            return null;
        }
    }
    /**
     * 获取用户ID
     *
     * @return
     */
    public long getId() {
        try {
            String userAgent = request.getHeader("userAgent");
            if (StringUtils.isEmpty(userAgent)) {
                userAgent = request.getHeader("User-Agent");
            }
            JSONObject json = new JSONObject(userAgent);
            return json.getLong("id");
        } catch (Exception e) {
            return 0;
        }
    }
    public String getIMEI() {
        try {
            String userAgent = request.getHeader("userAgent");
            if (StringUtils.isEmpty(userAgent)) {
                userAgent = request.getHeader("User-Agent");
            }
            JSONObject json = new JSONObject(userAgent);
            return json.getString("imei");
        } catch (Exception e) {
            return null;
        }
    }
    public String getToken() {
        try {
            String userAgent = request.getHeader("userAgent");
            if (StringUtils.isEmpty(userAgent)) {
                userAgent = request.getHeader("User-Agent");
            }
            JSONObject json = new JSONObject(userAgent);
            return json.getString("token");
        } catch (Exception e) {
            return null;
        }
    }
    public void error(Exception e) {
        logger.error(DateUtil.dateToStr(new Date(),"yyyy-MM-dd HH:mm:ss")+":"+getClass().getName() + ":", e.getMessage());
        e.printStackTrace();
    }
    public void warn(Exception e) {
        logger.warn(getClass().getName() + ":", e.getMessage());
        e.printStackTrace();
    }
    public void infoMessage(String message) {
        logger.info(message);
    }
    /**
     * 返回接口处理结果
     *
     * @param code  结果码,成功为200
     * @param msg   结果提示信息
     * @return
     */
    public String error(int code, String msg) {
        try {
            Map<Object, Object> map = new HashMap<Object, Object>();
            ObjectMapper mapper = new ObjectMapper();
            map.put("status", code);
            map.put("msg", msg);
            return mapper.writeValueAsString(map);
        } catch (Exception e) {
            error(e);
            return null;
        }
    }
    /**
     * 接口处理成功
     *
     * @param msg
     * @return
     */
    public String success(String msg) {
        try {
            Map<Object, Object> map = new HashMap<Object, Object>();
            ObjectMapper mapper = new ObjectMapper();
            map.put("status", 200);
            map.put("msg", msg);
            return mapper.writeValueAsString(map);
        } catch (Exception e) {
            error(e);
            return null;
        }
    }
    public String write(int code, String msg) {
        try {
            Map<Object, Object> map = new HashMap<Object, Object>();
            ObjectMapper mapper = new ObjectMapper();
            map.put("status", code);
            map.put("msg", msg);
            return mapper.writeValueAsString(map);
        } catch (Exception e) {
            error(e);
            return null;
        }
    }
    /**
     * 返回接口处理结果
     *
     * @param code  结果码,成功为200
     * @param msg   结果提示信息
     * @return
     */
    public String write(int code, String msg, String key, List<?> list) {
        try {
            Map<Object, Object> map = new HashMap<Object, Object>();
            ObjectMapper mapper = new ObjectMapper();
            map.put("status", code);
            map.put("msg", msg);
            map.put(key, list);
            return mapper.writeValueAsString(map);
        } catch (Exception e) {
            error(e);
            return error(-1, "服务器异常,请稍候再试!");
        }
    }
    /**
     * 返回接口处理结果
     *
     * @param code  结果码,成功为200
     * @param msg   结果提示信息
     * @param value 结果数据
     * @return
     */
    public String write(int code, String msg, String key, JSONObject value) {
        try {
            JSONObject json = new JSONObject();
            json.put("status", code);
            json.put("msg", msg);
            json.put(key, value);
            return json.toString();
        } catch (Exception e) {
            error(e);
            return error(-1, "服务器异常,请稍候再试!");
        }
    }
    /**
     * 返回接口处理结果
     *
     * @param code  结果码,成功为200
     * @param msg   结果提示信息
     * @param value 结果数据
     * @return
     */
    public String write(int code, String msg, String key, JSONArray value) {
        try {
            JSONObject json = new JSONObject();
            json.put("status", code);
            json.put("msg", msg);
            json.put(key, value);
            return json.toString();
        } catch (Exception e) {
            error(e);
            return error(-1, "服务器异常,请稍候再试!");
        }
    }
    /**
     * 返回接口处理结果
     *
     * @param code  结果码,成功为200
     * @param msg   结果提示信息
     * @param total 总数
     * @param value 结果数据
     * @return
     */
    public String write(int code, String msg, int total, String key, JSONArray value) {
        try {
            JSONObject json = new JSONObject();
            json.put("status", code);
            json.put("msg", msg);
            json.put("total", total);
            json.put(key, value);
            return json.toString();
        } catch (Exception e) {
            error(e);
            return error(-1, "服务器异常,请稍候再试!");
        }
    }
    /**
     * 返回接口处理结果
     *
     * @param code  结果码,成功为200
     * @param msg   结果提示信息
     * @param value 结果数据
     * @return
     */
    public String write(int code, String msg, String key, Object value) {
        try {
            Map<Object, Object> map = new HashMap<Object, Object>();
            ObjectMapper mapper = new ObjectMapper();
            map.put("status", code);
            map.put("msg", msg);
            map.put(key, value);
            return mapper.writeValueAsString(map);
        } catch (Exception e) {
            error(e);
            return error(-1, "服务器异常,请稍候再试!");
        }
    }
    /**
     * 返回接口处理结果
     *
     * @param code  结果码,成功为200
     * @param msg   结果提示信息
     * @return
     */
    public String write(int code, String msg, String key, Page<?> list) {
        try {
            Map<Object, Object> map = new HashMap<Object, Object>();
            ObjectMapper mapper = new ObjectMapper();
            map.put("status", code);
            map.put("msg", msg);
            // 是否为第一页
            map.put("isFirst", list.isFirst());
            // 是否为最后一页
            map.put("isLast", list.isLast());
            // 总条数
            map.put("total", list.getTotalElements());
            // 总页数
            map.put("totalPages", list.getTotalPages());
            map.put(key, list.getContent());
            return mapper.writeValueAsString(map);
        } catch (Exception e) {
            error(e);
            return error(-1, "服务器异常,请稍候再试!");
        }
    }
    /**
     * 返回接口处理结果
     *
     * @param code  结果码,成功为200
     * @param msg   结果提示信息
     * @return
     */
    public String write(int code, String msg, String key, Page<?> page, JSONArray array) {
        try {
            JSONObject json = new JSONObject();
            json.put("status", code);
            json.put("msg", msg);
            // 是否为第一页
            json.put("isFirst", page == null ? false : page.isFirst());
            // 是否为最后一页
            json.put("isLast", page == null ? true : page.isLast());
            // 总条数
            json.put("total", page == null ? 0 : page.getTotalElements());
            // 总页数
            json.put("totalPages", page == null ? 0 : page.getTotalPages());
            json.put(key, array);
            return json.toString();
        } catch (Exception e) {
            error(e);
            return error(-1, "服务器异常,请稍候再试!");
        }
    }
    /**
     * 返回接口处理结果
     *
     * @param code  结果码,成功为200
     * @param msg   结果提示信息
     * @param value 结果数据
     * @return
     */
    public String write(int code, String msg, String key, Map<?, ?> value) {
        try {
            Map<Object, Object> map = new HashMap<Object, Object>();
            ObjectMapper mapper = new ObjectMapper();
            map.put("status", code);
            map.put("msg", msg);
            map.put(key, value);
            return mapper.writeValueAsString(map);
        } catch (Exception e) {
            error(e);
            return error(-1, "服务器异常,请稍候再试!");
        }
    }
    /**
     * 返回接口处理结果
     *
     * @param code  结果码,成功为200
     * @param msg   结果提示信息
     * @param value 结果数据
     * @return
     */
    public String write(int code, String msg, String key, String value) {
        try {
            Map<Object, Object> map = new HashMap<Object, Object>();
            ObjectMapper mapper = new ObjectMapper();
            map.put("status", code);
            map.put("msg", msg);
            map.put(key, value);
            return mapper.writeValueAsString(map);
        } catch (Exception e) {
            error(e);
            return error(-1, "服务器异常,请稍候再试!");
        }
    }
 /*   *//**
     * 返回接口处理结果
     *
     * @param code  结果码,成功为200
     * @param msg   结果提示信息
     * @return
     *//*
    public String write(int code, String msg, String key, IdEntity entity) {
        try {
            Map<Object, Object> map = new HashMap<Object, Object>();
            ObjectMapper mapper = new ObjectMapper();
            map.put("status", code);
            map.put("msg", msg);
            map.put(key, entity);
            return mapper.writeValueAsString(map);
        } catch (Exception e) {
            error(e);
            return error(-1, "服务器异常,请稍候再试!");
        }
    }*/
    /**
     * 返回接口处理结果
     *
     * @param code  结果码,成功为200
     * @param msg   结果提示信息
     * @return
     */
    public String write(int code, String msg, boolean isFirst, boolean isLast, long total, int totalPages, String key, Object values) {
        try {
            JSONObject json = new JSONObject();
            json.put("status", code);
            json.put("msg", msg);
            // 是否为第一页
            json.put("isFirst", isFirst);
            // 是否为最后一页
            json.put("isLast", isLast);
            // 总条数
            json.put("total", total);
            // 总页数
            json.put("totalPages", totalPages);
            json.put(key, values);
            return json.toString();
        } catch (Exception e) {
            logger.error("BaseController:", e.getMessage());
            return error(-1, "服务器异常,请稍候再试!");
        }
    }
    public String trimEnd(String param, String trimChars) {
        if (param.endsWith(trimChars)) {
            param = param.substring(0, param.length() - trimChars.length());
        }
        return param;
    }
    /**
     * 无效用户消息返回
     *
     * @param e
     * @param defaultCode
     * @param defaultMsg
     * @return
     */
    public String invalidUserException(Exception e, int defaultCode, String defaultMsg) {
        try {
            // if (e instanceof UndeclaredThrowableException) {
            // UndeclaredThrowableException ute = (UndeclaredThrowableException) e;
            // InvalidUserException iue = (InvalidUserException) ute.getUndeclaredThrowable();
            // if (iue != null) {
            // return error(iue.getCode(), iue.getMsg());
            // }
            // }
            return error(defaultCode, defaultMsg);
        } catch (Exception e2) {
            return null;
        }
    }
    public List<Map<String, Object>> copyBeans(Collection<? extends Object> beans, String... propertyNames) {
        List<Map<String, Object>> result = new ArrayList<>();
        for (Object bean : beans) {
            result.add(copyBeanProperties(bean, propertyNames));
        }
        return result;
    }
    /**
     * 复制特定属性。
     *
     * @param bean
     * @param propertyNames
     * @return
     */
    public Map<String, Object> copyBeanProperties(Object bean, String... propertyNames) {
        Map<String, Object> simplifiedBean = new HashMap<>();
        for (String propertyName : propertyNames) {
            Field field = ReflectionUtils.findField(bean.getClass(), propertyName);
            if (field != null) {
                field.setAccessible(true);
                Object value = ReflectionUtils.getField(field, bean);
                simplifiedBean.put(propertyName, value == null ? "" : value);
            } else {
                simplifiedBean.put(propertyName, "");
            }
        }
        return simplifiedBean;
    }
    protected <J> ObjEnvelop<J> success(J obj){
        return success("success", obj);
    }
    protected <J> ObjEnvelop<J> success(String message, J obj){
        return success(message, 200, obj);
    }
    protected <J> ObjEnvelop<J> success(String message, int status, J obj){
        ObjEnvelop<J> objEnvelop = new ObjEnvelop<>();
        objEnvelop.setMessage(message);
        objEnvelop.setStatus(status);
        objEnvelop.setObj(obj);
        return objEnvelop;
    }
}

+ 326 - 0
svr/svr-iot-job/src/main/java/com/yihu/jw/web/quota/JobController.java

@ -0,0 +1,326 @@
package com.yihu.jw.web.quota;
import com.yihu.jw.entity.hospital.prescription.WlyyOutpatientDO;
import com.yihu.jw.im.service.ImService;
import com.yihu.jw.internet.service.DataGeneratorService;
import com.yihu.jw.internet.service.ykyy.YkyyInternetService;
import com.yihu.jw.job.*;
import com.yihu.jw.job.wlw.DeviceQualityPlanJob;
import com.yihu.jw.job.wlw.SimBalanceJob;
import com.yihu.jw.job.wlw.SimSetMealJob;
import com.yihu.jw.restmodel.web.ObjEnvelop;
import com.yihu.jw.service.channel.DeviceQualityPlanService;
import com.yihu.jw.service.channel.SimBalanceService;
import com.yihu.jw.service.channel.SimSetMealService;
import com.yihu.jw.service.quota.JobService;
import com.yihu.jw.util.SystemConf;
import com.yihu.jw.web.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.List;
/**
 * 任务启动
 *
 * @author chenweida
 */
@RestController
@RequestMapping(value = "/job", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Api(description = "后台-任务控制")
public class JobController extends BaseController {
    private org.slf4j.Logger logger = LoggerFactory.getLogger(JobController.class);
    private final JobService jobService;
    private final QuartzHelper quartzHelper;
    @Autowired
    private ImService imService;
    @Autowired
    private DataGeneratorService dataGeneratorService;
    @Autowired
    private YkyyInternetService ykyyInternetService;
    @Autowired
    private SimBalanceService simBalanceService;
    @Autowired
    private DeviceQualityPlanService deviceQualityPlanService;
    @Autowired
    private SimSetMealService simSetMealService;
    @Autowired
    public JobController(JobService jobService, QuartzHelper quartzHelper) {
        this.jobService = jobService;
        this.quartzHelper = quartzHelper;
    }
    /**
     * 测试方法
     * @return
     */
    @RequestMapping(value = "unSettledHISPrescription", method = RequestMethod.GET)
    public String unSettledHISPrescription() {
        try {
            simSetMealService.autoPush();
            return success("成功!");
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "失败:" + e.getMessage());
        }
    }
    @RequestMapping(value = "removeJob", method = RequestMethod.GET)
    public String removeJob(String taskId) {
        try {
            if(quartzHelper.isExistJob(taskId)){
                quartzHelper.removeJob(taskId);
                return success("删除成功!");
            }
            return success("删除成功!");
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "删除失败:" + e.getMessage());
        }
    }
    @RequestMapping(value = "getCalendar", method = RequestMethod.GET)
    public ObjEnvelop getCalendar() throws Exception{
       return success(quartzHelper.getCalendar());
    }
    @RequestMapping(value = "isExist", method = RequestMethod.GET)
    public String isExist(String taskId) {
        try {
            if(quartzHelper.isExistJob(taskId)){
                return success("job已经存在!");
            }
            return success("job不存在!");
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "执行失败:" + e.getMessage());
        }
    }
    @RequestMapping(value = "reStartById", method = RequestMethod.GET)
    public String reStartById(String taskId) {
        try {
            if(quartzHelper.isExistJob(taskId)){
                quartzHelper.removeJob(taskId);
            }
            switch(taskId){
                case "data_device_quality_plan_job":
                    if (!quartzHelper.isExistJob("data_device_quality_plan_job")) {
                        String trigger = SystemConf.getInstance().getSystemProperties().getProperty("data_device_quality_plan_job");
                        quartzHelper.addJob(DeviceQualityPlanJob.class, trigger, "data_device_quality_plan_job", new HashMap<String, Object>());
                        logger.info("data_device_quality_plan_job  job success");
                    } else {
                        logger.info("data_device_quality_plan_job  job exist");
                    }
                    break;
                case "data_sim_Balance_remind_job":
                    if (!quartzHelper.isExistJob("data_sim_Balance_remind_job")) {
                        String trigger = simBalanceService.getCron();
                        quartzHelper.addJob(SimBalanceJob.class, trigger, "data_sim_Balance_remind_job", new HashMap<String, Object>());
                        logger.info("data_sim_Balance_remind_job  job success");
                    } else {
                        logger.info("data_sim_Balance_remind_job  job exist");
                    }
                    break;
                case "data_sim_set_meal_job":
                    if (!quartzHelper.isExistJob("data_sim_set_meal_job")) {
                        String trigger = simBalanceService.getCron();
                        quartzHelper.addJob(SimSetMealJob.class, trigger, "data_sim_set_meal_job", new HashMap<String, Object>());
                        logger.info("data_sim_set_meal_job  job success");
                    } else {
                        logger.info("data_sim_set_meal_job  job exist");
                    }
                    break;
                default :
            }
            return success("启动成功!");
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "启动失败:" + e.getMessage());
        }
    }
    /**
     * 生成过去几天的数据
     *
     * @param day
     * @return
     */
    @RequestMapping(value = "productDataByDay", method = RequestMethod.GET)
    public String productDataByDay(Integer day) {
        try {
            jobService.productDataByDay(day);
            return success("启动成功!");
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "启动失败:" + e.getMessage());
        }
    }
    /**
     * 生成过去某一天的全部的数据
     *
     * @param day
     * @return
     */
    @RequestMapping(value = "productDataByOneDay", method = RequestMethod.GET)
    public String productDataByOneDay(String day) {
        try {
            jobService.productDataByOneDay(day);
            return success("启动成功!");
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "启动失败:" + e.getMessage());
        }
    }
    /**
     * 生成过去某一天的某一个指标的数据
     *
     * @param day
     * @return
     */
    @RequestMapping(value = "productDataByOneDayWithId", method = RequestMethod.GET)
    public String productDataByOneDayWithId(String day, String id) {
        try {
            jobService.productDataByOneDayWithId(day, id);
            return success("启动成功!");
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "启动失败:" + e.getMessage());
        }
    }
    /**
     * 生成过去某几天的某一个指标的数据
     *
     * @param day
     * @return
     */
    @RequestMapping(value = "productDataByDayAndId", method = RequestMethod.GET)
    public String productDataByDayAndId(Integer day, String id) {
        try {
            jobService.productDataByDayAndId(day, id);
            return success("启动成功!");
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "启动失败:" + e.getMessage());
        }
    }
    /**
     * 启动任务
     *
     * @param id id
     * @return
     */
    @RequestMapping(value = "startById", method = RequestMethod.GET)
    public String startById(String id) {
        try {
            jobService.startById(id);
            return success("启动成功!");
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "启动失败:" + e.getMessage());
        }
    }
    /**
     * 停止任务
     *
     * @param id id
     * @return
     */
    @RequestMapping(value = "stopById", method = RequestMethod.GET)
    public String stopById(String id) {
        try {
            jobService.stopById(id);
            return success("停止成功!");
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "启动失败:" + e.getMessage());
        }
    }
    /**
     * 停止所有任务
     *
     * @return
     */
    @RequestMapping(value = "stopAll", method = RequestMethod.GET)
    public String stopAll() {
        try {
            jobService.stopAll();
            return success("停止成功!");
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "启动失败:" + e.getMessage());
        }
    }
    /**
     * 启动所有任务
     *
     * @return
     */
    @RequestMapping(value = "startAll", method = RequestMethod.GET)
    public String startAll() {
        try {
            jobService.startAll();
            return success("启动成功!");
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "启动失败:" + e.getMessage());
        }
    }
    @RequestMapping(value = "/delData", method = RequestMethod.POST)
    @ApiOperation("删除数据")
    public String delData(String doctor,String date) {
        try {
            List<WlyyOutpatientDO> list = dataGeneratorService.delData(doctor,date);
            imService.deleteJobData(list,date);
            return write(200, "数据已经删除");
        } catch (Exception e) {
            error(e);
            return error(-1, "数据已经删除");
        }
    }
    @RequestMapping(value = "/testImg", method = RequestMethod.GET)
    @ApiOperation("测试图片")
    public String testImg(String path) {
      return write(200, ykyyInternetService.testImg(path));
    }
}

+ 110 - 0
svr/svr-iot-job/src/main/java/com/yihu/jw/web/quota/WlyyJobConfigVO.java

@ -0,0 +1,110 @@
package com.yihu.jw.web.quota;
import java.io.Serializable;
/**
 * Created by Administrator on 2016/8/16.
 */
public class WlyyJobConfigVO implements  Serializable {
    private static final long serialVersionUID = 1L;
    private String id;
    private String quotaId;//指标id
    private String jobName;//任务名称
    private String jobInfo;//任务描述
    private String jobType;//任务类型(0--单次执行  1--周期执行 2--监听任务)
    private String jobClass;//任务执行的class
    private String quartzCron;//quartz表达式
    private String status;//1 启动 0停止
    private String del;//是否删除 1正常 0删除
    public WlyyJobConfigVO() {
    }
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getQuotaId() {
        return quotaId;
    }
    public void setQuotaId(String quotaId) {
        this.quotaId = quotaId;
    }
    public String getJobName() {
        return jobName;
    }
    public void setJobName(String jobName) {
        this.jobName = jobName;
    }
    public String getJobInfo() {
        return jobInfo;
    }
    public void setJobInfo(String jobInfo) {
        this.jobInfo = jobInfo;
    }
    public String getJobType() {
        return jobType;
    }
    public void setJobType(String jobType) {
        this.jobType = jobType;
    }
    public String getJobClass() {
        return jobClass;
    }
    public void setJobClass(String jobClass) {
        this.jobClass = jobClass;
    }
    public String getQuartzCron() {
        return quartzCron;
    }
    public void setQuartzCron(String quartzCron) {
        this.quartzCron = quartzCron;
    }
    public String getStatus() {
        return status;
    }
    public void setStatus(String status) {
        this.status = status;
    }
    public String getDel() {
        return del;
    }
    public void setDel(String del) {
        this.del = del;
    }
    @Override
    public String toString() {
        return "WlyyJobConfigVO{" +
                "id='" + id + '\'' +
                ", quotaId='" + quotaId + '\'' +
                ", jobName='" + jobName + '\'' +
                ", jobInfo='" + jobInfo + '\'' +
                ", jobType='" + jobType + '\'' +
                ", jobClass='" + jobClass + '\'' +
                ", quartzCron='" + quartzCron + '\'' +
                ", status='" + status + '\'' +
                ", del='" + del + '\'' +
                '}';
    }
}

+ 107 - 0
svr/svr-iot-job/src/main/java/com/yihu/jw/web/quota/WlyyQuotaVO.java

@ -0,0 +1,107 @@
package com.yihu.jw.web.quota;
import java.io.Serializable;
import java.util.Date;
/**
 * Created by Administrator on 2016/8/16.
 */
public class WlyyQuotaVO implements Serializable {
    private static final long serialVersionUID = 2L;
    private String id;
    private String name;//指标名称
    private String level1;//指标维度(1:机构维度)
    private String level2;//2级维度 (1:患者性别 2:患者分组 3:患者年龄)
    private String cycle;//统计周期( 1:天 )
    private String type;//尺度(1 新增 2是累计)
    private Date createTime;//创建时间
    private Date modifyTime;//修改时间
    private String del;//1: 正常 0: 删除
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getLevel1() {
        return level1;
    }
    public void setLevel1(String level1) {
        this.level1 = level1;
    }
    public String getLevel2() {
        return level2;
    }
    public void setLevel2(String level2) {
        this.level2 = level2;
    }
    public String getCycle() {
        return cycle;
    }
    public void setCycle(String cycle) {
        this.cycle = cycle;
    }
    public String getType() {
        return type;
    }
    public void setType(String type) {
        this.type = type;
    }
    public Date getCreateTime() {
        return createTime;
    }
    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }
    public Date getModifyTime() {
        return modifyTime;
    }
    public void setModifyTime(Date modifyTime) {
        this.modifyTime = modifyTime;
    }
    public String getDel() {
        return del;
    }
    public void setDel(String del) {
        this.del = del;
    }
    @Override
    public String toString() {
        return "WlyyQuotaVO{" +
                "id='" + id + '\'' +
                ", name='" + name + '\'' +
                ", level1='" + level1 + '\'' +
                ", level2='" + level2 + '\'' +
                ", cycle='" + cycle + '\'' +
                ", type='" + type + '\'' +
                ", createTime=" + createTime +
                ", modifyTime=" + modifyTime +
                ", del='" + del + '\'' +
                '}';
    }
}

+ 287 - 0
svr/svr-iot-job/src/main/resources/application.yml

@ -0,0 +1,287 @@
#通用的配置不用区分环境变量
server:
  port: 10031
spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    max-active: 50
    max-idle: 50 #最大空闲连接
    min-idle: 10 #最小空闲连接
    validation-query-timeout: 20
    log-validation-errors: true
    validation-interval: 60000 #避免过度验证,保证验证不超过这个频率——以毫秒为单位。如果一个连接应该被验证,但上次验证未达到指定间隔,将不再次验证。
    validation-query: SELECT 1 #SQL 查询, 用来验证从连接池取出的连接, 在将连接返回给调用者之前。 如果指定, 则查询必须是一个SQL SELECT 并且必须返回至少一行记录
    test-on-borrow: true #指明是否在从池中取出连接前进行检验, 如果检验失败, 则从池中去除连接并尝试取出另一个。注意: 设置为true 后如果要生效,validationQuery 参数必须设置为非空字符串
    test-on-return: true #指明是否在归还到池中前进行检验 注意: 设置为true 后如果要生效validationQuery 参数必须设置为非空字符串
    idle-timeout: 30000
    connection-test-query: SELECT 1
    num-tests-per-eviction-run: 50 #在每次空闲连接回收器线程(如果有)运行时检查的连接数量,最好和maxActive
    test-while-idle: true #指明连接是否被空闲连接回收器(如果有)进行检验,如果检测失败,则连接将被从池中去除
    min-evictable-idle-time-millis: 3600000 #连接池中连接,在时间段内一直空闲,被逐出连接池的时间(1000*60*60),以毫秒为单位
    time-between-eviction-runs-millis: 300000 #在空闲连接回收器线程运行期间休眠的时间值,以毫秒为单位,一般比minEvictableIdleTimeMillis小
fast-dfs:
  tracker-server: 172.26.0.110:22122 #服务器地址
  connect-timeout: 2 #链接超时时间
  network-timeout: 30
  charset: ISO8859-1 #编码
  http:
    tracker-http-port: 80
    anti-steal-token: no
    secret-key: FastDFS1234567890
  pool: #连接池大小
    init-size: 5
    max-size: 20
    wait-time: 500
configDefault: # 默认配置
  saasId: xmjkzl_saasId
express:
  sf_url: http://bsp-oisp.sf-express.com/bsp-oisp/sfexpressService
  sf_code: JKZL
  sf_check_word: QkeIfIvQdheqIv2cVSgAUnBU29lfNbVk
quartz:
  name: schedulerFactoryBean
# 上传文件临时路径配置
FileTempPath:
  upload_temp_path : /var/local/temp
  image_path : /var/local/upload/images
  voice_path : /var/local/upload/voice
  chat_file_path : /var/local/upload/chat
#发现服务
#eureka:
#  client:
#    healthcheck:
#      enabled: true #监控检查
#    serviceUrl:
#      defaultZone: http://172.16.100.63:8761/eureka/
#  instance:
#    prefer-ip-address: false
#    instance-id: ${spring.cloud.client.ipAddress}:${server.port}
---
spring:
  profiles: jwdev
  datasource:
    url: jdbc:mysql://172.26.0.104/base?useUnicode:true&characterEncoding=utf-8&autoReconnect=true
    username: ssgg
    password: ssgg@jkzl2019
hlwyyEntrance:
  url: http://localhost:10023
# mq 是否获取his数据,flag代表获取演示数据,false代表获取his真实数据
demo:
  flag: true
hospital:
  url: https://wx.xmzsh.com
  mqUser: JKZL
  mqPwd: 123456
  SourceSysCode: S60
  TargetSysCode: S01
im:
  im_list_get: http://172.26.0.105:3000/
  data_base_name: im_internet_hospital
fastDFS:
  fastdfs_file_url: http://172.26.0.110:8888/
wechat:
  id: d24d1367-7f4f-43af-910e-a0a43799e040  # base库中,wx_wechat 的id字段
---
spring:
  profiles: jwtest
  datasource:
    url: jdbc:mysql://172.26.0.104/xmiot?useUnicode:true&amp;characterEncoding=utf-8&amp;autoReconnect=true
    username: ssgg
    password: ssgg@jkzl2019
hlwyyEntrance:
  url: http://localhost:10023
# mq 是否获取his数据,flag代表获取演示数据,false代表获取his真实数据
demo:
  flag: true
hospital:
  url: https://wx.xmzsh.com
  mqUser: JKZL
  mqPwd: 123456
  SourceSysCode: S60
  TargetSysCode: S01
im:
  im_list_get: http://172.26.0.105:3000/
  data_base_name: im_internet_hospital
fastDFS:
  fastdfs_file_url: http://172.26.0.110:8888/
wlyy:
  url: http://www.xmtyw.cn/wlyytest/
wechat:
  id: d24d1367-7f4f-43af-910e-a0a43799e040  # base库中,wx_wechat 的id字段
---
spring:
  profiles: jwOracleTest
  datasource:
    driver-class-name: oracle.jdbc.driver.OracleDriver
    url: jdbc:oracle:thin:@172.26.0.141:1521:helowin
    username: normal
    password: normal
  jpa:
    properties:
      hibernate:
        dialect: org.hibernate.dialect.Oracle10gDialect
        show_sql: true
    database: oracle
hlwyyEntrance:
  url: http://172.16.1.42:10023
# mq 是否获取his数据,flag代表获取演示数据,false代表获取his真实数据
demo:
  flag: false
hospital:
  url: https://wx.xmzsh.com
  mqUser: JKZL
  mqPwd: 123456
  SourceSysCode: S60
  TargetSysCode: S01
im:
  im_list_get: http://172.26.0.105:3000/
  data_base_name: im_internet_hospital
fastDFS:
  fastdfs_file_url: http://172.26.0.110:8888/
wlyy:
  url: http://www.xmtyw.cn/wlyytest/
wechat:
  id: xm_ykyy_wx  # base库中,wx_wechat 的id字段
---
spring:
  profiles: jwOracleProd
  datasource:
    driver-class-name: oracle.jdbc.driver.OracleDriver
    url: jdbc:oracle:thin:@10.10.10.16:1521/rac
    username: HLWYY
    password: Xmykzxhlwyy963
  jpa:
    properties:
      hibernate:
        dialect: org.hibernate.dialect.Oracle10gDialect
        show_sql: true
    database: oracle
hlwyyEntrance:
  url: http://172.16.1.42:10023
# mq 是否获取his数据,flag代表获取演示数据,false代表获取his真实数据
demo:
  flag: false
hospital:
  url: https://wx.xmzsh.com
  mqUser: JKZL
  mqPwd: 123456
  SourceSysCode: S60
  TargetSysCode: S01
im:
  im_list_get: http://172.26.0.105:3000/
  data_base_name: im_internet_hospital
fastDFS:
  fastdfs_file_url: http://172.26.0.110:8888/
wlyy:
  url: http://www.xmtyw.cn/wlyytest/
wechat:
  id: xm_ykyy_wx  # base库中,wx_wechat 的id字段
---
spring:
  profiles: jwprod
  datasource:
    url: jdbc:mysql://192.0.33.27:3306/base?useUnicode:true&characterEncoding=utf-8&autoReconnect=true
    username: im
    password: 2oEq3Kf7
hlwyyEntrance:
  url: http://172.16.1.42:10023
# mq 是否获取his数据,flag代表获取演示数据,false代表获取his真实数据
demo:
  flag: false
hospital:
  url: https://172.16.1.34
  mqUser: JKZL
  mqPwd: 123456
  SourceSysCode: S60
  TargetSysCode: S01
im:
  im_list_get: http://172.16.1.42:3000/
  data_base_name: im
fastDFS:
  fastdfs_file_url: http://192.0.33.26:8888/
wlyy:
  url: http://www.xmtyw.cn/wlyytest/
wechat:
  id: d24d1367-7f4f-43af-910e-a0a43799e040  # base库中,wx_wechat 的id字段
---
spring:
  profiles: xzprod
  datasource:
    url: jdbc:mysql://172.16.100.240:7306/base?useUnicode:true&characterEncoding=utf-8&autoReconnect=true
    username: jkzl
    password: jkzl@2020
hlwyyEntrance:
  url: http://172.16.100.63:10023
# mq 是否获取his数据,flag代表获取演示数据,false代表获取his真实数据
demo:
  flag: false
hospital:
  url: https://wx.xmzsh.com
  mqUser: JKZL
  mqPwd: 123456
  SourceSysCode: S60
  TargetSysCode: S01
im:
  im_list_get: http://172.16.100.241:3000/
  data_base_name: im
fastDFS:
  fastdfs_file_url: http://172.16.100.240:8888/
wlyy:
  url: http://www.xmtyw.cn/wlyytest/
wechat:
  id: d24d1367-7f4f-43af-910e-a0a43799e040  # base库中,wx_wechat 的id字段
---
spring:
  profiles: xzprod_in
  datasource:
    url: jdbc:mysql://192.168.103.155:7306/base?useUnicode:true&characterEncoding=utf-8&autoReconnect=true
    username: jkzl
    password: jkzl@2020
hlwyyEntrance:
  url: http://172.16.100.63:10023
# mq 是否获取his数据,flag代表获取演示数据,false代表获取his真实数据
demo:
  flag: false
hospital:
  url: https://wx.xmzsh.com
  mqUser: JKZL
  mqPwd: 123456
  SourceSysCode: S60
  TargetSysCode: S01
im:
  im_list_get: http://192.168.103.150:3000/
  data_base_name: im
fastDFS:
  fastdfs_file_url: http://192.168.103.159:8888/
wlyy:
  url: http://www.xmtyw.cn/wlyytest/
wechat:
  id: d24d1367-7f4f-43af-910e-a0a43799e040  # base库中,wx_wechat 的id字段

+ 6 - 0
svr/svr-iot-job/src/main/resources/banner.txt

@ -0,0 +1,6 @@
                               _           _                                  _             _                             _   _             _             _           _
  ___  __   __  _ __          (_)  _ __   | |_    ___   _ __   _ __     ___  | |_          | |__     ___    ___   _ __   (_) | |_    __ _  | |           (_)   ___   | |__
 / __| \ \ / / | '__|  _____  | | | '_ \  | __|  / _ \ | '__| | '_ \   / _ \ | __|  _____  | '_ \   / _ \  / __| | '_ \  | | | __|  / _` | | |  _____    | |  / _ \  | '_ \
 \__ \  \ V /  | |    |_____| | | | | | | | |_  |  __/ | |    | | | | |  __/ | |_  |_____| | | | | | (_) | \__ \ | |_) | | | | |_  | (_| | | | |_____|   | | | (_) | | |_) |
 |___/   \_/   |_|            |_| |_| |_|  \__|  \___| |_|    |_| |_|  \___|  \__|         |_| |_|  \___/  |___/ | .__/  |_|  \__|  \__,_| |_|          _/ |  \___/  |_.__/
                                                                                                                 |_|                                   |__/

+ 61 - 0
svr/svr-iot-job/src/main/resources/bootstrap.yml

@ -0,0 +1,61 @@
spring:
  application:
    name: svr-iot-job
  cloud:
    config:
      failFast: true
      username: jw
      password: jkzl
---
spring:
  profiles: jwdev
  cloud:
    config:
      uri: ${wlyy.spring.config.uri:http://172.26.0.107:1221}
      label: ${wlyy.spring.config.label:jwdev}
---
spring:
  profiles: jwtest
  cloud:
    config:
      uri: ${wlyy.spring.config.uri:http://172.26.0.107:1221}
      label: ${wlyy.spring.config.label:jwdev}
---
spring:
  profiles: jwOracleTest
  cloud:
    config:
      uri: ${wlyy.spring.config.uri:http://172.26.0.107:1221}
      label: ${wlyy.spring.config.label:jwdev}
---
spring:
  profiles: jwOracleProd
  cloud:
    config:
      uri: ${wlyy.spring.config.uri:http://192.168.33.199:1221}
      label: ${wlyy.spring.config.label:jwdev}
---
spring:
  profiles: jwprod
  cloud:
    config:
      uri: ${wlyy.spring.config.uri:http://192.0.33.26:1221}
      label: ${wlyy.spring.config.label:master}
---
spring:
  profiles: local
  cloud:
    config:
      uri: ${wlyy.spring.config.uri:http://192.168.131.174:1221}
      label: ${wlyy.spring.config.label:local}
---
spring:
  profiles: xzprod
  cloud:
    config:
      uri: ${wlyy.pring.config.uri:http://172.16.100.63:1221}
      label: ${wlyy.spring.config.label:master}

+ 44 - 0
svr/svr-iot-job/src/main/resources/quartz.properties

@ -0,0 +1,44 @@
# Default Properties file for use by StdSchedulerFactory
# to create a Quartz Scheduler Instance, if a different
# properties file is not explicitly specified.
#
 
org.quartz.scheduler.instanceName: DefaultQuartzScheduler
org.quartz.scheduler.rmi.export: false
org.quartz.scheduler.rmi.proxy: false
org.quartz.scheduler.wrapJobExecutionInUserTransaction: false
 
org.quartz.threadPool.class: org.quartz.simpl.SimpleThreadPool
org.quartz.threadPool.threadCount: 5
org.quartz.threadPool.threadPriority: 5
org.quartz.threadPool.threadsInheritContextClassLoaderOfInitializingThread: true
 
org.quartz.jobStore.misfireThreshold: 60000
#是否集群
org.quartz.jobStore.isClustered=false
 
#============================================================================
# Configure JobStore
#============================================================================
 
# RAM
# org.quartz.jobStore.class: org.quartz.simpl.RAMJobStore
# Configure JobStore Cluster
org.quartz.jobStore.useProperties = true
org.quartz.jobStore.class:org.quartz.impl.jdbcjobstore.JobStoreTX
org.quartz.jobStore.driverDelegateClass:org.quartz.impl.jdbcjobstore.StdJDBCDelegate
#datasource׺
org.quartz.jobStore.tablePrefix:QRTZ_
#org.quartz.jobStore.dataSource:qzDS
#
##============================================================================
## Configure Datasources
##============================================================================
##datasource
#org.quartz.dataSource.qzDS.driver: com.mysql.jdbc.Driver
#org.quartz.dataSource.qzDS.URL: jdbc:mysql://172.19.103.85/wlyy?useUnicode=true&characterEncoding=utf-8&autoReconnect=true
#org.quartz.dataSource.qzDS.user: root
#org.quartz.dataSource.qzDS.password: 123456
org.quartz.jobGroupName = RS_JOBGROUP_NAME
org.quartz.triggerGroupName = RS_TRIGGERGROUP_NAME

+ 23 - 0
svr/svr-iot-job/src/main/resources/system.properties

@ -0,0 +1,23 @@
#-------------------------中山医院-----------------------------#
# 健康频道状态
prescriptionStatus_update_job=0 */2 * * * ?
# 门诊记录过期job,每天1 点触发
prescription_overdue_job=0 0 1 * * ?
#每天13 点触发
data_upload_job=0 0 2 * * ?
#-------------------------中山医院end-----------------------------#
#-------------------------眼科医院-----------------------------#
data_ykupload_job=0 0 0 * * ?
#每间隔1分钟触发
unsettled_prescription_notice_job=0 */1 * * * ?
#-------------------------眼科医院end-----------------------------#
#-------------------------监管平台通用医院-----------------------------#
data_common_upload_job=0 0 0 * * ?
#------------------------物联网后台系统---------------------------#
#设备质检时间 每天24 点触发
data_device_quality_plan_job=0 0 0 * * ?
#SIM卡每月套餐扣费  每月1号凌晨0点0分0秒扣费
data_sim_set_meal_job=0 0 0 1 * ?

+ 5 - 2
svr/svr-iot/src/main/java/com/yihu/iot/controller/platform/IotInterfaceController.java

@ -2,7 +2,7 @@ package com.yihu.iot.controller.platform;
import com.yihu.iot.service.company.IotCompanyService;
import com.yihu.iot.service.platform.IotCompanyAppInterfaceService;
import com.yihu.iot.service.log.IotInterfaceLogService;
import com.yihu.iot.service.platform.IotInterfaceLogService;
import com.yihu.iot.service.platform.IotShareInterfaceService;
import com.yihu.jw.entity.iot.company.IotCompanyDO;
import com.yihu.jw.entity.iot.platform.IotCompanyAppInterfaceDO;
@ -18,7 +18,6 @@ import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
@ -44,6 +43,7 @@ public class IotInterfaceController extends EnvelopRestEndpoint {
    @Autowired
    private IotCompanyService iotCompanyService;
    @PostMapping(value = IotRequestMapping.Platform.addInterface)
    @ApiOperation(value = "新增共享接口",notes = "新增共享接口")
    public MixEnvelop<IotShareInterfaceDO,IotShareInterfaceDO> addInterface(@ApiParam(name = "JSON",value = "接口JSON串") @RequestParam(value = "JSON",required = true)String json){
@ -179,6 +179,9 @@ public class IotInterfaceController extends EnvelopRestEndpoint {
    }
    @GetMapping(value = IotRequestMapping.Platform.dataConsumption)
    @ApiOperation(value = "接口数据消费分页查询",notes = "接口数据消费分页查询")
    public MixEnvelop<IotInterfaceLogVO,IotInterfaceLogVO> dataConsumption(@ApiParam(name = "page", value = "第几页", defaultValue = "")

+ 1 - 1
svr/svr-iot/src/main/java/com/yihu/iot/dao/device/IotDeviceQualityInspectionPlanDao.java

@ -31,7 +31,7 @@ public interface IotDeviceQualityInspectionPlanDao extends PagingAndSortingRepos
    @Query(value = "SELECT a.* from iot_device_quality_inspection_plan a WHERE a.purchase_id = ?1 and a.status=?2 and a.del=1 ORDER BY a.plan_time asc limit 1",nativeQuery = true)
    IotDeviceQualityInspectionPlanDO findFirstByPurchaseId(String purchaseId,String status);
    @Query("from IotDeviceQualityInspectionPlanDO c where c.del=1")
    @Query("from IotDeviceQualityInspectionPlanDO c where c.del=1 and c.orderNo=?1")
    List<IotDeviceQualityInspectionPlanDO> findByOrderNo(String orderNo);
    @Query("from IotDeviceQualityInspectionPlanDO c where c.del=1")

+ 14 - 0
svr/svr-iot/src/main/java/com/yihu/iot/dao/platform/IotInterfaceLogDao.java

@ -0,0 +1,14 @@
package com.yihu.iot.dao.platform;
import com.yihu.jw.entity.iot.platform.IotInterfaceLogDO;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
/**
 * @author HZY
 * @vsrsion 1.0
 * Created at 2020/4/28
 */
public interface IotInterfaceLogDao extends PagingAndSortingRepository<IotInterfaceLogDO,String>, JpaSpecificationExecutor<IotInterfaceLogDO> {
}

+ 255 - 0
svr/svr-iot/src/main/java/com/yihu/iot/service/platform/IotInterfaceLogService.java

@ -0,0 +1,255 @@
package com.yihu.iot.service.platform;
import com.alibaba.fastjson.JSONObject;
import com.yihu.iot.dao.company.IotCompanyAppDao;
import com.yihu.iot.dao.platform.IotInterfaceLogDao;
import com.yihu.iot.dao.workType.IotWorkTypeDao;
import com.yihu.iot.service.useragent.UserAgent;
import com.yihu.jw.entity.iot.company.IotCompanyAppDO;
import com.yihu.jw.entity.iot.platform.IotInterfaceLogDO;
import com.yihu.jw.entity.iot.workType.IotWorkTypeDO;
import com.yihu.jw.restmodel.iot.platform.IotInterfaceLogVO;
import com.yihu.jw.restmodel.web.MixEnvelop;
import com.yihu.jw.rm.iot.IotRequestMapping;
import com.yihu.mysql.query.BaseJpaService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.util.*;
/**
 * @author HZY
 * @vsrsion 1.0
 * Created at 2020/4/28
 */
@Service
public class IotInterfaceLogService extends BaseJpaService<IotInterfaceLogDO, IotInterfaceLogDao> {
    private static final Logger logger = LoggerFactory.getLogger(IotInterfaceLogService.class);
    @Autowired
    private IotInterfaceLogDao iotInterfaceLogDao;
    @Autowired
    private UserAgent userAgent;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private IotCompanyAppDao iotCompanyAppDao;
    @Autowired
    private IotWorkTypeDao iotWorkTypeDao;
    /**
     * 分页查询日志信息
     * @param page
     * @param size
     * @return
     * @throws ParseException
     */
    public MixEnvelop<IotInterfaceLogVO,IotInterfaceLogVO> findAll(Integer page, Integer size) throws ParseException {
        String sql = "select * from iot_interface_log where 1=1;";
        String sorts = "-updateTime";//按更新时间降序
//        List<IotInterfaceLogDO> list = search(null, filters, sorts, page, size);
        List<IotInterfaceLogDO> list = jdbcTemplate.query(sql,new BeanPropertyRowMapper(IotInterfaceLogDO.class));
        ArrayList<IotInterfaceLogVO> resultList = new ArrayList<>();
        list.forEach(one->{
            IotInterfaceLogVO target = new IotInterfaceLogVO();
            BeanUtils.copyProperties(one,target);
            resultList.add(target);
        });
        long count =list.size();
        return MixEnvelop.getSuccessListWithPage(IotRequestMapping.Platform.message_success_find,resultList,page, size,count);
    }
    /**
     * 数据消费
     * @param page
     * @param size
     * @return
     */
    public MixEnvelop<IotInterfaceLogVO,IotInterfaceLogVO> dataConsumption(Integer page,Integer size){
/*        //根据应用和接口确定唯一的接口被调用次数
        String sqlTotal="SELECT COUNT(id) num,app_name,interface_name,work_type FROM iot_interface_log GROUP BY app_name,interface_name;";
        //根据应用和接口确定唯一的接口被调用的失败次数
        String sql="SELECT COUNT(id) num,app_name,interface_name,work_type FROM iot_interface_log  WHERE state=0 GROUP BY app_name,interface_name;";
        List<IotInterfaceLogVO> list = new ArrayList<>();
        List<Map<String, Object>> total = jdbcTemplate.queryForList(sqlTotal);
        List<Map<String, Object>> failCount = jdbcTemplate.queryForList(sql);
        total.forEach(one->{
            IotInterfaceLogVO iotInterfaceLogVO = new IotInterfaceLogVO();
            iotInterfaceLogVO.setAppName(one.get("app_name").toString());
            iotInterfaceLogVO.setInterfaceName(one.get("interface_name").toString());
            iotInterfaceLogVO.setWorkType(one.get("work_type").toString());
            iotInterfaceLogVO.setCount(one.get("num").toString());
            list.add(iotInterfaceLogVO);
        });
        //获取总的调用次数
        Long totalCount = (long) list.size();
        //获取失败次数
        if (failCount==null){
            list.forEach(one->{
                one.setFailureRate("0.00");
            });
            return MixEnvelop.getSuccessListWithPage(IotRequestMapping.Platform.message_success_find,list,page, size,totalCount);
        }
        list.forEach(iotInterfaceLogVO->{
            failCount.forEach(one->{
                if(iotInterfaceLogVO.getAppName().equalsIgnoreCase(one.get("app_name").toString())
                        && iotInterfaceLogVO.getInterfaceName().equalsIgnoreCase(one.get("interface_name").toString()) ){
                    String num = one.get("num").toString();
                    Double value = Double.valueOf(num);
                    String count = iotInterfaceLogVO.getCount();
                    Double all = Double.valueOf(count);
                    DecimalFormat df=new DecimalFormat("0.00");//设置保留位数
                    String format = df.format(value / all);
                    iotInterfaceLogVO.setFailureRate(format);
                }
            });
        });
        return MixEnvelop.getSuccessListWithPage(IotRequestMapping.Platform.message_success_find,list,page, size,totalCount);*/
        String sql ="SELECT  COALESCE(c.fali,0),b.count,b.app_name,b.interface_name,b.work_type FROM " +
                "                                        (SELECT COUNT(id) fali,app_name,interface_name FROM iot_interface_log  WHERE state=0 GROUP BY app_name,interface_name) c " +
                                                         "RIGHT JOIN (SELECT count(id) count,app_name,interface_name,work_type FROM iot_interface_log " +
                                                         " GROUP BY app_name,interface_name) b ON c.app_name=b.app_name AND c.interface_name=b.interface_name;";
        List<Map<String, Object>> listSql = jdbcTemplate.queryForList(sql);
        List<IotInterfaceLogVO> list = new ArrayList<>();
        listSql.forEach(one->{
            IotInterfaceLogVO iotInterfaceLogVO = new IotInterfaceLogVO();
            iotInterfaceLogVO.setAppName(one.get("app_name").toString());
            iotInterfaceLogVO.setInterfaceName(one.get("interface_name").toString());
            iotInterfaceLogVO.setWorkType(one.get("work_type").toString());
            iotInterfaceLogVO.setCount(one.get("count").toString());
            iotInterfaceLogVO.setFailureRate(Float.toString(Float.parseFloat(one.get("COALESCE(c.fali,0)").toString())/Float.parseFloat(one.get("count").toString())));
            list.add(iotInterfaceLogVO);
        });
        long totalCount=listSql.size();
        return MixEnvelop.getSuccessListWithPage(IotRequestMapping.Platform.message_success_find,list,page, size,totalCount);
    }
    /**
     * 保存接口调用日志
     * @param appId 应用ID
     * @param params 入参
     * @param response 出参
     * @param request
     * @param state 调用状态
     * @param interfaceName 接口名称
     * @param method 方法名
     * @param workTypeId 业务类型
     * @param time 调用时间
     */
    public void saveLog(String appId, String params, String response, HttpServletRequest request,Integer state,String  interfaceName,String method,String workTypeId,Date time){
        IotInterfaceLogDO interfaceLogDO = new IotInterfaceLogDO();
        //设置应用与公司
        IotCompanyAppDO appDO = iotCompanyAppDao.findById(appId);
        interfaceLogDO.setAppId(appId);
        interfaceLogDO.setAppName(appDO.getName());
        interfaceLogDO.setCompanyId(appDO.getCompanyId());
        interfaceLogDO.setCompanyName(appDO.getCompanyName());
        //设置业务类型
        IotWorkTypeDO work = iotWorkTypeDao.findById(workTypeId);
        interfaceLogDO.setWorkType(work.getName());
        interfaceLogDO.setExplanation(work.getExplanation());
        interfaceLogDO.setWorkTypeId(workTypeId);
        //设置用户名称与ID
        if(StringUtils.isBlank(userAgent.getUID())){
            interfaceLogDO.setUserId("system");
            interfaceLogDO.setUserName("system");
        }else{
            interfaceLogDO.setUserId(userAgent.getUID());
            interfaceLogDO.setUserId(userAgent.getUNAME());
        }
        interfaceLogDO.setAddressIp(getIpAddress(request));
        interfaceLogDO.setUrl(request.getRequestURL().toString());
        HashMap<String, String> headMap = new HashMap<>(16);
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()){
            String name = headerNames.nextElement();
            String value = request.getHeader(name);
            headMap.put(name,value);
        }
        String headJson = JSONObject.toJSONString(headMap);
        interfaceLogDO.setHead(headJson);
        interfaceLogDO.setRequest(params);
        interfaceLogDO.setResponse(response);
        interfaceLogDO.setState(state);
        interfaceLogDO.setInterfaceName(interfaceName);
        interfaceLogDO.setMethod(method);
        interfaceLogDO.setTime(time);
        iotInterfaceLogDao.save(interfaceLogDO);
    }
    /**
     * 获取用户真实IP地址,不使用request.getRemoteAddr();的原因是有可能用户使用了代理软件方式避免真实IP地址。
     * 可是,如果通过了多级反向代理的话,X-Forwarded-For的值并不止一个,而是一串IP值,究竟哪个才是真正的用户端的真实IP呢?
     * 答案是取X-Forwarded-For中第一个非unknown的有效IP字符串
     * @param request
     * @return
     */
    private String getIpAddress(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
            if("127.0.0.1".equals(ip)||"0:0:0:0:0:0:0:1".equals(ip)){
                //根据网卡取本机配置的IP
                InetAddress inet=null;
                try {
                    inet = InetAddress.getLocalHost();
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                }
                ip= inet.getHostAddress();
            }
        }
        return ip;
    }
}