Explorar el Código

Merge branch 'dev' of LiTaohong/patient-co-management into dev

huangwenjie hace 7 años
padre
commit
918f6b685f
Se han modificado 31 ficheros con 2190 adiciones y 53 borrados
  1. 97 0
      common/common-entity/src/main/java/com/yihu/figure_label/entity/FLJobConfig.java
  2. 43 0
      common/common-entity/src/main/java/com/yihu/figure_label/entity/FLlabelDict.java
  3. 52 0
      common/common-entity/src/main/java/com/yihu/figure_label/entity/FLlabelDictJob.java
  4. 9 0
      patient-co/patient-co-figure-label/pom.xml
  5. 8 2
      patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/FigureLabelApplication.java
  6. 2 2
      patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/config/db/WlyyJpa.java
  7. 445 0
      patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/controller/BaseController.java
  8. 231 0
      patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/controller/JobController.java
  9. 65 0
      patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/convert/AgeConvert.java
  10. 41 0
      patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/convert/BirthConvert.java
  11. 4 2
      patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/convert/Convert.java
  12. 102 0
      patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/convert/ConvertHelper.java
  13. 14 0
      patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/convert/HealthConditionConvert.java
  14. 36 0
      patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/convert/SexConvert.java
  15. 56 0
      patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/dao/FLJobConfigDao.java
  16. 29 0
      patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/dao/FLLabelDictDao.java
  17. 29 0
      patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/dao/FLLabelDictJobDao.java
  18. 7 2
      patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/extract/Extracter.java
  19. 20 2
      patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/extract/MysqlExtracter.java
  20. 121 7
      patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/job/Mysql2ESJob.java
  21. 80 0
      patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/model/DataModel.java
  22. 0 31
      patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/model/ExtractModel.java
  23. 15 0
      patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/model/SaveModel.java
  24. 5 0
      patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/service/ExtractService.java
  25. 378 0
      patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/service/JobService.java
  26. 27 0
      patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/storage/Store2ES.java
  27. 12 0
      patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/storage/Store2Hbase.java
  28. 7 0
      patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/util/ConstantUtil.java
  29. 114 0
      patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/util/IdCardUtil.java
  30. 124 0
      patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/util/QuartzHelper.java
  31. 17 5
      patient-co/patient-co-figure-label/src/main/resources/application-dev.yml

+ 97 - 0
common/common-entity/src/main/java/com/yihu/figure_label/entity/FLJobConfig.java

@ -0,0 +1,97 @@
package com.yihu.figure_label.entity;
import com.yihu.wlyy.entity.IdEntity;
import javax.persistence.Entity;
import javax.persistence.Table;
/**
 * Created by lith on 2018/03/07.
 */
@Entity
@Table(name = "fl_job_config")
public class FLJobConfig extends IdEntity {
    private String jobName;
    private String jobClass;
    private String sql;
    private Integer sqlFieldType;
    private String sqlFieldValue;
    private String sqlField;
    private String quartzCron;
    private String status;
    private String del;
    public String getJobName() {
        return jobName;
    }
    public void setJobName(String jobName) {
        this.jobName = jobName;
    }
    public String getJobClass() {
        return jobClass;
    }
    public void setJobClass(String jobClass) {
        this.jobClass = jobClass;
    }
    public String getSql() {
        return sql;
    }
    public void setSql(String sql) {
        this.sql = sql;
    }
    public Integer getSqlFieldType() {
        return sqlFieldType;
    }
    public void setSqlFieldType(Integer sqlFieldType) {
        this.sqlFieldType = sqlFieldType;
    }
    public String getSqlFieldValue() {
        return sqlFieldValue;
    }
    public void setSqlFieldValue(String sqlFieldValue) {
        this.sqlFieldValue = sqlFieldValue;
    }
    public String getSqlField() {
        return sqlField;
    }
    public void setSqlField(String sqlField) {
        this.sqlField = sqlField;
    }
    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;
    }
}

+ 43 - 0
common/common-entity/src/main/java/com/yihu/figure_label/entity/FLlabelDict.java

@ -0,0 +1,43 @@
package com.yihu.figure_label.entity;
import com.yihu.wlyy.entity.IdEntity;
import javax.persistence.Entity;
import javax.persistence.Table;
/**
 * Created by lith on 2018/03/07.
 */
@Entity
@Table(name = "fl_label_dict")
public class FLlabelDict extends IdEntity {
    private String parentCode;
    private String labelName;
    private String labelCode;
    public String getParentCode() {
        return parentCode;
    }
    public void setParentCode(String parentCode) {
        this.parentCode = parentCode;
    }
    public String getLabelName() {
        return labelName;
    }
    public void setLabelName(String labelName) {
        this.labelName = labelName;
    }
    public String getLabelCode() {
        return labelCode;
    }
    public void setLabelCode(String labelCode) {
        this.labelCode = labelCode;
    }
}

+ 52 - 0
common/common-entity/src/main/java/com/yihu/figure_label/entity/FLlabelDictJob.java

@ -0,0 +1,52 @@
package com.yihu.figure_label.entity;
import com.yihu.wlyy.entity.IdEntity;
import javax.persistence.Entity;
import javax.persistence.Table;
/**
 * Created by lith on 2018/03/07.
 */
@Entity
@Table(name = "fl_label_dict_job")
public class FLlabelDictJob extends IdEntity {
    private String jobId;
    private String labelType;
    private String sql;
    private String convertClazz;
    public String getJobId() {
        return jobId;
    }
    public void setJobId(String jobId) {
        this.jobId = jobId;
    }
    public String getLabelType() {
        return labelType;
    }
    public void setLabelType(String labelType) {
        this.labelType = labelType;
    }
    public String getSql() {
        return sql;
    }
    public void setSql(String sql) {
        this.sql = sql;
    }
    public String getConvertClazz() {
        return convertClazz;
    }
    public void setConvertClazz(String convertClazz) {
        this.convertClazz = convertClazz;
    }
}

+ 9 - 0
patient-co/patient-co-figure-label/pom.xml

@ -78,5 +78,14 @@
            <artifactId>hibernate-core</artifactId>
            <version>4.3.5.Final</version>
        </dependency>
        <dependency>
            <groupId>com.yihu</groupId>
            <artifactId>common-data-es-starter</artifactId>
            <version>1.0.2</version>
        </dependency>
        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
        </dependency>
    </dependencies>
</project>

+ 8 - 2
patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/FigureLabelApplication.java

@ -8,17 +8,23 @@ import org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchDa
import org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchRepositoriesAutoConfiguration;
import org.springframework.boot.autoconfigure.data.redis.RedisRepositoriesAutoConfiguration;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
/**
 * Created by chenweida on 2018/3/5.
 */
@SpringBootApplication
@EnableJpaRepositories(
        entityManagerFactoryRef = "wlyyEntityManagerFactory",
        transactionManagerRef = "wlyyTransactionManager")
@EnableAutoConfiguration(exclude = {
        ElasticsearchAutoConfiguration.class,
//        ElasticsearchAutoConfiguration.class,
        ElasticsearchRepositoriesAutoConfiguration.class,
        ElasticsearchDataAutoConfiguration.class,
//        ElasticsearchDataAutoConfiguration.class,
        RedisRepositoriesAutoConfiguration.class
})
@ComponentScan({"com.yihu.wlyy.figure"})
public class FigureLabelApplication {
    public static ApplicationContext ctx = null;

+ 2 - 2
patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/config/db/WlyyJpa.java

@ -31,7 +31,7 @@ import java.util.Properties;
@EnableJpaRepositories(
        entityManagerFactoryRef = "wlyyEntityManagerFactory",
        transactionManagerRef = "wlyyTransactionManager",
        basePackages = {"com.yihu.wlyy.repository"})   //设置Repository所在位置
        basePackages = {"com.yihu.wlyy.figure.label.dao"})   //设置Repository所在位置
public class WlyyJpa {
    @Autowired
@ -84,7 +84,7 @@ public class WlyyJpa {
        LocalContainerEntityManagerFactoryBean emfb = new LocalContainerEntityManagerFactoryBean();
        emfb.setDataSource(dataSource);
        emfb.setPackagesToScan("com.yihu.wlyy.entity");
        emfb.setPackagesToScan("com.yihu.figure_label.entity");
        emfb.setPersistenceUnitName("wlyy");
        JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        emfb.setJpaVendorAdapter(vendorAdapter);

+ 445 - 0
patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/controller/BaseController.java

@ -0,0 +1,445 @@
package com.yihu.wlyy.figure.label.controller;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.wlyy.entity.IdEntity;
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 javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class BaseController {
	private static Logger logger = LoggerFactory.getLogger(BaseController.class);
	@Autowired
	protected HttpServletRequest request;
	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(getClass().getName() + ":", e.getMessage());
		e.printStackTrace();
	}
	public void warn(Exception e) {
		logger.warn(getClass().getName() + ":", e.getMessage());
		e.printStackTrace();
	}
	/**
	 * 返回接口处理结果
	 * 
	 * @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 结果提示信息
	 * @param value 结果数据
	 * @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 结果提示信息
	 * @param value 结果数据
	 * @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 结果提示信息
	 * @param value 结果数据
	 * @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.isFirst());
			// 是否为最后一页
			json.put("isLast", page.isLast());
			// 总条数
			json.put("total", page.getTotalElements());
			// 总页数
			json.put("totalPages", 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 结果提示信息
	* @param value 结果数据
	* @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 结果提示信息
	 * @param value 结果数据
	 * @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;
		}
	}
}

+ 231 - 0
patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/controller/JobController.java

@ -0,0 +1,231 @@
package com.yihu.wlyy.figure.label.controller;
import com.yihu.wlyy.figure.label.service.JobService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
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.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/**
 * 启动job
 */
@RestController
@RequestMapping(value = "/job", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Api(description = "定时任务控制器")
public class JobController extends BaseController{
    private Logger logger = LoggerFactory.getLogger(JobController.class);
    @Autowired
    private JobService jobService;
    /**
     * 启动任务
     * @param id
     * @return
     */
    @ApiOperation(value = "根据ID立即单个任务")
    @RequestMapping(value = "startNowById", method = RequestMethod.GET)
    public String startNowById(
            @ApiParam(name = "id", value = "任务ID", required = true)@RequestParam(value = "id", required = true) String id) {
        try {
            jobService.startNowById(id);
            return success("启动成功!");
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "启动失败:" + e.getMessage());
        }
    }
    /**
     * 生成过去某一天的全部的数据
     *
     * @param day
     * @return
     */
    @ApiOperation(value = "生成过去某一天的全部的数据")
    @RequestMapping(value = "productDataByOneDay", method = RequestMethod.GET)
    public String productDataByOneDay( @ApiParam(name = "day", value = "yyyy-MM-dd")@RequestParam(value = "day", required = true)String day) {
        try {
            jobService.productDataByOneDay(day);
            return success("启动成功!");
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "启动失败:" + e.getMessage());
        }
    }
    /**
     * 生成过去某一天到某一天的增量数据
     *
     * @param start
     * @param end
     * @return
     */
    @ApiOperation(value = "生成过去某一天到某一天的增量数据(包含头尾)")
    @RequestMapping(value = "productDataByDayToDayAndId", method = RequestMethod.GET)
    public String productDataByDayToDayAndId( @ApiParam(name = "start", value = "yyyy-MM-dd")@RequestParam(value = "start", required = true)String start,
                                              @ApiParam(name = "end", value = "yyyy-MM-dd")@RequestParam(value = "end", required = true)String end,
                                              @ApiParam(name = "ids", value = "任务ids多个逗号分割")@RequestParam(value = "ids", required = true)String ids) {
        try {
            jobService.productDataByDayToDayAndId(start,end,ids);
            return success("启动成功!");
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "启动失败:" + e.getMessage());
        }
    }
    /**
     * 生成过去某一天增量数据
     *
     * @param day
     * @return
     */
    @ApiOperation(value = "生成过去某一天增量数据")
    @RequestMapping(value = "productDataByOneDayWithId", method = RequestMethod.GET)
    public String productDataByOneDayWithId(
            @ApiParam(name = "day", value = "yyyy-MM-dd")@RequestParam(value = "day", required = true)String day,
            @ApiParam(name = "id", value = "任务id")@RequestParam(value = "id", required = true)String id) {
        try {
            jobService.productDataByOneDayWithId(day, id);
            return success("启动成功!");
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "启动失败:" + e.getMessage());
        }
    }
    /**
     * 生成过去到现在的全部的数据
     *
     * @param day
     * @return
     */
    @ApiOperation(value = "生成过去到现在的全部的数据")
    @RequestMapping(value = "productDataByDayAndId", method = RequestMethod.GET)
    public String productDataByDayAndId(
            @ApiParam(name = "day", value = "距离今天的天数(如果是要生成昨天的数据,day=1)")@RequestParam(value = "day", required = true) int day,
            @ApiParam(name="id",required=true)@RequestParam(value = "id", required = true) String id) {
        try {
            jobService.productDataByDayAndId(day, id);
            return success("启动成功!");
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "启动失败:" + e.getMessage());
        }
    }
    /**
     * 启动任务
     *
     * @param id id
     * @return
     */
    @ApiOperation(value = "启动单个任务")
    @RequestMapping(value = "startById", method = RequestMethod.GET)
    public String startById(
            @ApiParam(name="id",value="任务id",required=true)@RequestParam(value = "id", required = true) String id) {
        try {
            jobService.startById(id);
            return success("启动成功!");
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "启动失败:" + e.getMessage());
        }
    }
    /**
     * 停止任务
     *
     * @param id id
     * @return
     */
    @ApiOperation(value = "停止单个任务")
    @RequestMapping(value = "stopById", method = RequestMethod.GET)
    public String stopById(@ApiParam(name="id",value="任务id",required=true)@RequestParam(value = "id", required = true)String id) {
        try {
            jobService.stopById(id);
            return success("停止成功!");
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "启动失败:" + e.getMessage());
        }
    }
    /**
     * 停止所有任务
     *
     * @return
     */
    @ApiOperation(value = "停止所有任务")
    @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
     */
    @ApiOperation(value = "启动所有任务")
    @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());
        }
    }
    @ApiOperation(value = "清除緩存")
    @RequestMapping(value = "cleanCache", method = RequestMethod.GET)
    public String cleanCache() {
        try {
            return success("启动成功!");
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "启动失败:" + e.getMessage());
        }
    }
    /**
     * 生成过去某一天到某一天的某个指标的数据
     *
     * @param start
     * @param end
     * @return
     */
    @ApiOperation(value = "生成过去某一天到某一天的某个指标的数据(包含头尾)没有休眠时间")
    @RequestMapping(value = "productDataByDayToDayAndIdNoSleep", method = RequestMethod.GET)
    public String productDataByDayToDayAndIdNoSleep( @ApiParam(name = "start", value = "yyyy-MM-dd")@RequestParam(value = "start", required = true)String start,
                                                     @ApiParam(name = "end", value = "yyyy-MM-dd")@RequestParam(value = "end", required = true)String end,
                                                     @ApiParam(name = "id", value = "任务id")@RequestParam(value = "id", required = true)String id,
                                                     @ApiParam(name = "sleepTime", value = "任务间隔时间(秒)")@RequestParam(value = "sleepTime", required = true)Long sleepTime) {
        try {
            jobService.productDataByDayToDayAndIdNoSleep(start,end,id,sleepTime);
            return success("启动成功!");
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "启动失败:" + e.getMessage());
        }
    }
}

+ 65 - 0
patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/convert/AgeConvert.java

@ -0,0 +1,65 @@
package com.yihu.wlyy.figure.label.convert;
import com.yihu.figure_label.entity.FLlabelDict;
import com.yihu.wlyy.figure.label.model.DataModel;
import com.yihu.wlyy.figure.label.model.SaveModel;
import com.yihu.wlyy.figure.label.util.ConstantUtil;
import com.yihu.wlyy.figure.label.util.IdCardUtil;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import java.util.*;
@Component
public class AgeConvert implements Convert {
    @Override
    public List<SaveModel> convert(List<DataModel> models,List<FLlabelDict> flLabelDictList) {
        List<SaveModel> saveModels = new ArrayList<>();
        if(CollectionUtils.isEmpty(flLabelDictList)){
            return saveModels;
        }
        FLlabelDict one = flLabelDictList.get(0);
        Map<String,String> map = new HashMap<>();
        flLabelDictList.forEach(
                fLlabelDict -> {
                    map.put(fLlabelDict.getLabelCode(),fLlabelDict.getLabelName());
                }
        );
        models.forEach(
                model -> {
                    int age = IdCardUtil.getAgeForIdcard(model.getIdCard());
                    String labelCode = getAgeLabelCode(age);
                    SaveModel saveModel = new SaveModel();
                    saveModel.setLabelType(one.getParentCode());
                    saveModel.setLabelCode(labelCode);
                    saveModel.setLabeName(map.get(labelCode));
                    saveModel.setCreateTime(DateFormatUtils.format(new Date(), ConstantUtil.date_format));
                    saveModels.add(saveModel);
                }
        );
        return saveModels;
    }
    /**
     * fl_label_dict配置的code
     * @param age
     * @return
     */
    public String getAgeLabelCode(int age) {
        if (age <= 6) {
            return "10";
        }else if(age <=18){
            return "11";
        }else if(age <=30){
            return "12";
        }else if(age <=50){
            return "13";
        }else if(age <=65){
            return "14";
        }else{
            return "15";
        }
    }
}

+ 41 - 0
patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/convert/BirthConvert.java

@ -0,0 +1,41 @@
package com.yihu.wlyy.figure.label.convert;
import com.yihu.figure_label.entity.FLlabelDict;
import com.yihu.wlyy.figure.label.model.DataModel;
import com.yihu.wlyy.figure.label.model.SaveModel;
import com.yihu.wlyy.figure.label.util.ConstantUtil;
import com.yihu.wlyy.figure.label.util.IdCardUtil;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.util.CollectionUtils;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class BirthConvert implements Convert {
    @Override
    public List<SaveModel> convert(List<DataModel> models,List<FLlabelDict> flLabelDictList) {
        List<SaveModel> saveModels = new ArrayList<>();
        if(CollectionUtils.isEmpty(flLabelDictList)){
            return saveModels;
        }
        FLlabelDict fLlabelDict = flLabelDictList.get(0);
        models.forEach(
                model -> {
                    try {
                        String birth = IdCardUtil.getBirthdayForIdcard(model.getIdCard());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    SaveModel saveModel = new SaveModel();
                    saveModel.setIdcard(model.getIdCard());
                    saveModel.setLabelCode(fLlabelDict.getLabelCode());
                    saveModel.setLabelType(fLlabelDict.getParentCode());
                    saveModel.setLabeName(fLlabelDict.getLabelName());
                    saveModel.setCreateTime(DateFormatUtils.format(new Date(), ConstantUtil.date_format));
                    saveModels.add(saveModel);
                }
        );
        return saveModels;
    }
}

+ 4 - 2
patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/convert/Convert.java

@ -1,6 +1,8 @@
package com.yihu.wlyy.figure.label.convert;
import com.yihu.wlyy.figure.label.model.ExtractModel;
import com.yihu.figure_label.entity.FLlabelDict;
import com.yihu.figure_label.entity.FLlabelDictJob;
import com.yihu.wlyy.figure.label.model.DataModel;
import com.yihu.wlyy.figure.label.model.SaveModel;
import java.util.List;
@ -11,5 +13,5 @@ import java.util.List;
 */
public interface Convert {
    List<SaveModel> convert(List<ExtractModel> extractModels);
    List<SaveModel> convert(List<DataModel> modelList,List<FLlabelDict> flLabelDictList);
}

+ 102 - 0
patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/convert/ConvertHelper.java

@ -0,0 +1,102 @@
package com.yihu.wlyy.figure.label.convert;
import com.yihu.figure_label.entity.FLlabelDict;
import com.yihu.figure_label.entity.FLlabelDictJob;
import com.yihu.wlyy.figure.label.dao.FLLabelDictDao;
import com.yihu.wlyy.figure.label.model.DataModel;
import com.yihu.wlyy.figure.label.model.SaveModel;
import com.yihu.wlyy.figure.label.util.ConstantUtil;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
 * Created by chenweida on 2017/6/5.
 * 维度的key值转换器
 */
@Component
@Scope("prototype")
public class ConvertHelper {
    private Logger logger = LoggerFactory.getLogger(ConvertHelper.class);
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private FLLabelDictDao flLabelDictDao;
    /**
     * 进行具体标签生成转换
     * @return
     * @throws Exception
     */
    public List<SaveModel> convert(List<DataModel> dataModels, FLlabelDictJob fLlabelDictJob) throws Exception {
        List<SaveModel> saveModels = new ArrayList<>();
            //不需要转换
            if(StringUtils.isEmpty(fLlabelDictJob.getConvertClazz())){
                return generateSaveModleWithOutConvert(dataModels);
            }
            //不需要转换
            if(StringUtils.isEmpty(fLlabelDictJob.getSql())){
                return generateSaveModleWithOutConvert(dataModels);
            }
            List<FLlabelDict> flLabelDictList = jdbcTemplate.query(fLlabelDictJob.getSql(),new BeanPropertyRowMapper(FLlabelDict.class));
            try {
                Object obj = Class.forName(fLlabelDictJob.getConvertClazz()).newInstance();
                Method method = obj.getClass().getMethod("conver",List.class);
                saveModels = (List<SaveModel>)method.invoke(obj,dataModels,flLabelDictList);
            } catch (Exception e) {
                logger.error("customized class not found:" + fLlabelDictJob.getConvertClazz());
                return saveModels;
            }
        return saveModels;
    }
    public List<SaveModel> generateSaveModleWithOutConvert(List<DataModel> dataModels){
        List<SaveModel> saveModels = new ArrayList<>();
        dataModels.forEach(
                dataModel -> {
                    SaveModel saveModel = new SaveModel();
                    saveModel.setIdcard(dataModel.getIdCard());
                    saveModel.setLabelType(dataModel.getParentCode());
                    saveModel.setLabelCode(dataModel.getLabelCode());
                    saveModel.setLabeName(dataModel.getLabelName());
                    saveModel.setCreateTime(DateFormatUtils.format(new Date(), ConstantUtil.date_format));
                    saveModels.add(saveModel);
                }
        );
        return saveModels;
    }
}

+ 14 - 0
patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/convert/HealthConditionConvert.java

@ -0,0 +1,14 @@
package com.yihu.wlyy.figure.label.convert;
import com.yihu.figure_label.entity.FLlabelDict;
import com.yihu.wlyy.figure.label.model.DataModel;
import com.yihu.wlyy.figure.label.model.SaveModel;
import java.util.List;
public class HealthConditionConvert implements Convert {
    @Override
    public List<SaveModel> convert(List<DataModel> models,List<FLlabelDict> flLabelDictList) {
        return null;
    }
}

+ 36 - 0
patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/convert/SexConvert.java

@ -0,0 +1,36 @@
package com.yihu.wlyy.figure.label.convert;
import com.yihu.figure_label.entity.FLlabelDict;
import com.yihu.wlyy.figure.label.model.DataModel;
import com.yihu.wlyy.figure.label.model.SaveModel;
import com.yihu.wlyy.figure.label.util.ConstantUtil;
import com.yihu.wlyy.figure.label.util.IdCardUtil;
import org.apache.commons.lang3.time.DateFormatUtils;
import java.util.*;
public class SexConvert implements Convert{
    @Override
    public List<SaveModel> convert(List<DataModel> models,List<FLlabelDict> flLabelDictList) {
        List<SaveModel> saveModels = new ArrayList<>();
        FLlabelDict one = flLabelDictList.get(0);
        Map<String,String> map = new HashMap<>();
        flLabelDictList.forEach(
                fLlabelDict -> {
                    map.put(fLlabelDict.getLabelCode(),fLlabelDict.getLabelName());
                }
        );
        models.forEach(
                model -> {
                    String sex = IdCardUtil.getSexForIdcard(model.getIdCard());
                    SaveModel saveModel = new SaveModel();
                    saveModel.setLabelType(one.getParentCode());
                    saveModel.setLabelCode(sex);
                    saveModel.setLabeName(map.get(sex));
                    saveModel.setCreateTime(DateFormatUtils.format(new Date(), ConstantUtil.date_format));
                    saveModels.add(saveModel);
                }
        );
        return saveModels;
    }
}

+ 56 - 0
patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/dao/FLJobConfigDao.java

@ -0,0 +1,56 @@
package com.yihu.wlyy.figure.label.dao;
import com.yihu.figure_label.entity.FLJobConfig;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
public interface FLJobConfigDao extends PagingAndSortingRepository<FLJobConfig, String>, JpaSpecificationExecutor<FLJobConfig> {
    /**
     * 根据id和状态查询job配置
     * @param code
     * @param status
     * @return
     */
    @Query(" FROM FLJobConfig a WHERE a.id=?1 and a.status=?2 and a.del='1'")
    FLJobConfig findByIdAndStatus(String code, String status);
    /**
     * 查询所有的job配置
     * @param s
     * @return
     */
    @Query(" FROM FLJobConfig a WHERE a.status=?1 and a.del='1'")
    List<FLJobConfig> findByAll(String s);
    /**
     * 根据id查询
     * @param id
     * @return
     */
    @Query(" FROM FLJobConfig a WHERE a.id=?1 and a.del='1'")
    FLJobConfig findById(String id);
    /**
     * 更新job的状态(状态为启动或停止)
     * @param id
     * @param status
     * @return
     */
    @Modifying
    @Query(" update FLJobConfig a set a.status=?2 where a.id=?1 ")
    int updateStatus(String id, String status);
    /**
     * 删除job(0 正常 1 删除)
     * @param id
     * @return
     */
    @Modifying
    @Query(" update FLJobConfig a set a.del = 1 where a.id=?1 ")
    int deleteJob(String id);
}

+ 29 - 0
patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/dao/FLLabelDictDao.java

@ -0,0 +1,29 @@
package com.yihu.wlyy.figure.label.dao;
import com.yihu.figure_label.entity.FLlabelDict;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
public interface FLLabelDictDao extends PagingAndSortingRepository<FLlabelDict, String>, JpaSpecificationExecutor<FLlabelDict> {
    /**
     * 根据父类标签查询字典信息
     * @param parentCode
     * @return
     */
    @Query(" FROM FLlabelDict a WHERE a.parentCode=?1")
    FLlabelDict findByParentCode(String parentCode);
    /**
     * 根据父类code和标签code查询标签字典信息
     * @param parentCode
     * @param labelCode
     * @return
     */
    @Query(" FROM FLlabelDict a WHERE a.parentCode=?1 and labelCode = ?2")
    FLlabelDict findByParentCodeAndLabelCode(String parentCode,String labelCode);
}

+ 29 - 0
patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/dao/FLLabelDictJobDao.java

@ -0,0 +1,29 @@
package com.yihu.wlyy.figure.label.dao;
import com.yihu.figure_label.entity.FLlabelDictJob;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
public interface FLLabelDictJobDao extends PagingAndSortingRepository<FLlabelDictJob, String>, JpaSpecificationExecutor<FLlabelDictJob> {
    /**
     * 根据jobId查询
     * @param jobId
     * @return
     */
    @Query(" FROM FLlabelDictJob a WHERE a.jobId=?1")
    FLlabelDictJob findByJobId(String jobId);
    /**
     * 根据标签类型查询
     * @param type
     * @return
     */
    @Query(" FROM FLlabelDictJob a WHERE a.labelType=?1")
    FLlabelDictJob findByLabelType(String type);
}

+ 7 - 2
patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/extract/Extracter.java

@ -1,6 +1,7 @@
package com.yihu.wlyy.figure.label.extract;
import com.yihu.wlyy.figure.label.model.ExtractModel;
import com.yihu.figure_label.entity.FLlabelDictJob;
import com.yihu.wlyy.figure.label.model.DataModel;
import java.util.List;
@ -14,5 +15,9 @@ public interface Extracter {
     *
     * @return
     */
    List<ExtractModel> extract();
//    List<ExtractModel> extract();
    List<DataModel> extractDataByJobConfigsql(String sql);
}

+ 20 - 2
patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/extract/MysqlExtracter.java

@ -1,6 +1,10 @@
package com.yihu.wlyy.figure.label.extract;
import com.yihu.wlyy.figure.label.model.ExtractModel;
import com.yihu.wlyy.figure.label.dao.FLLabelDictDao;
import com.yihu.wlyy.figure.label.model.DataModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import java.util.List;
@ -10,8 +14,22 @@ import java.util.List;
 */
@Component
public class MysqlExtracter implements Extracter {
    @Override
    @Autowired
    private FLLabelDictDao flLabelDictDao;
    @Autowired
    private JdbcTemplate jdbcTemplate;
   /* @Override
    public List<ExtractModel> extract() {
        return null;
    }*/
    @Override
    public List<DataModel> extractDataByJobConfigsql(String sql) {
        List<DataModel> datas = jdbcTemplate.query(sql,new BeanPropertyRowMapper<>());
        return datas;
    }
}

+ 121 - 7
patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/job/Mysql2ESJob.java

@ -1,11 +1,27 @@
package com.yihu.wlyy.figure.label.job;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import com.yihu.figure_label.entity.FLJobConfig;
import com.yihu.figure_label.entity.FLlabelDict;
import com.yihu.figure_label.entity.FLlabelDictJob;
import com.yihu.wlyy.figure.label.controller.JobController;
import com.yihu.wlyy.figure.label.convert.ConvertHelper;
import com.yihu.wlyy.figure.label.dao.FLJobConfigDao;
import com.yihu.wlyy.figure.label.dao.FLLabelDictDao;
import com.yihu.wlyy.figure.label.dao.FLLabelDictJobDao;
import com.yihu.wlyy.figure.label.extract.MysqlExtracter;
import com.yihu.wlyy.figure.label.model.DataModel;
import com.yihu.wlyy.figure.label.model.SaveModel;
import com.yihu.wlyy.figure.label.storage.Store2ES;
import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import java.util.ArrayList;
import java.util.List;
/**
 * Created by chenweida on 2018/3/7.
@ -14,15 +30,113 @@ import org.springframework.stereotype.Component;
@Scope("prototype")
@DisallowConcurrentExecution//防止到了执行时间点前一任务还在执行中,但是这时有空闲的线程,那么马上又会执行,这样一来就会存在同一job被并行执行
public class Mysql2ESJob implements Job {
    private Logger logger = LoggerFactory.getLogger(JobController.class);
    @Autowired
    private FLJobConfigDao flJobConfigDao;
    @Autowired
    private FLLabelDictDao flLabelDictDao;
    @Autowired
    private FLLabelDictJobDao flLabelDictJobDao;
    @Autowired
    private MysqlExtracter mysqlExtracter;
    @Autowired
    private ConvertHelper convertHelper;
    @Autowired
    Store2ES store2ES;
    private FLJobConfig flJobConfig;
    private String flJobConfigId;
    private String sqlFiledValue;
    private String sqlFiledCondition;
    private String finalSql;
    private List<DataModel> dataModelList;
    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        JobDataMap paramsMap = context.getJobDetail().getJobDataMap();
        initParams(paramsMap);
        //根据obconfig里配置的sql提取数据
        extract();
        //数据转换
        List<SaveModel> list = new ArrayList<>();
        convert(list);
        //数据保存
        save(list);
    }
    public void initParams(JobDataMap paramsMap){
        this.flJobConfigId = paramsMap.getString("jobConfig");
        this.flJobConfig = flJobConfigDao.findById(this.flJobConfigId);
        this.sqlFiledValue = paramsMap.getString("sqlFiledValue");
        //没有传增量值,以数据库配置的默认值为查询条件
        if(StringUtils.isEmpty(this.sqlFiledValue)){
            this.sqlFiledValue = this.flJobConfig.getSqlFieldValue();
        }
        this.sqlFiledCondition = paramsMap.getString("sqlFiledCondition");
        //1抽取数据
        String sql = this.flJobConfig.getSql();
        String sqlFiled = this.flJobConfig.getSqlField();
        this.finalSql = getJobConfigSql(sql,sqlFiled,sqlFiledCondition,sqlFiledValue);
    }
    /**
     * 提取数据,按数据库中配置的增量条件提取
     */
    public void extract(){
        this.dataModelList = mysqlExtracter.extractDataByJobConfigsql(this.finalSql);
    }
    /**
     * 转换
     */
    public void convert(List<SaveModel> list){
        FLlabelDictJob fLlabelDictJob = flLabelDictJobDao.findOne(this.flJobConfigId);
        try {
            list = convertHelper.convert(this.dataModelList, fLlabelDictJob);
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
    }
        //1.1数据转换
        // 如果表fl_label_dict_job中有配置convert_clazz就进行数据转换获取标签
        //2数据保存
    /**
     * 保存
     * @param list
     */
    public void save(List<SaveModel> list){
        store2ES.save(list);
    }
    /**
     * 拼凑获取增量数据的sql
     * @param sql
     * @param sqlFiledValue
     * @return
     */
    public String getJobConfigSql(String sql,String sqlFiled,String sqlFiledCondition,String sqlFiledValue){
        StringBuilder result = new StringBuilder();
        if (sqlFiledValue.contains(",")) {
            String[] sqlFiledValues = sqlFiledValue.split(",");
            result.append("where ").append(sqlFiled).append(sqlFiledCondition).append(sqlFiledValues[0]).append(sqlFiledCondition).append(sqlFiledValues[1]);
        }else{
            result.append("where ").append(sqlFiled).append(sqlFiledCondition).append(sqlFiledValue);
        }
        return result.toString();
    }
}

+ 80 - 0
patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/model/DataModel.java

@ -0,0 +1,80 @@
package com.yihu.wlyy.figure.label.model;
/**
 * jboConfig配置里sql查询出的数据
 */
public class DataModel {
    private String idCard;
    private String sex;
    private String parentCode;
    private String labelName;
    private String labelCode;
    private String convertClazz;
    private String jobId;
    private String patient;
    public String getIdCard() {
        return idCard;
    }
    public void setIdCard(String idCard) {
        this.idCard = idCard;
    }
    public String getSex() {
        return sex;
    }
    public void setSex(String sex) {
        this.sex = sex;
    }
    public String getParentCode() {
        return parentCode;
    }
    public void setParentCode(String parentCode) {
        this.parentCode = parentCode;
    }
    public String getLabelName() {
        return labelName;
    }
    public void setLabelName(String labelName) {
        this.labelName = labelName;
    }
    public String getLabelCode() {
        return labelCode;
    }
    public void setLabelCode(String labelCode) {
        this.labelCode = labelCode;
    }
    public String getConvertClazz() {
        return convertClazz;
    }
    public void setConvertClazz(String convertClazz) {
        this.convertClazz = convertClazz;
    }
    public String getJobId() {
        return jobId;
    }
    public void setJobId(String jobId) {
        this.jobId = jobId;
    }
    public String getPatient() {
        return patient;
    }
    public void setPatient(String patient) {
        this.patient = patient;
    }
}

+ 0 - 31
patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/model/ExtractModel.java

@ -1,31 +0,0 @@
package com.yihu.wlyy.figure.label.model;
/**
 * Created by chenweida on 2018/3/7.
 */
public class ExtractModel {
    /**
     *  身份证
     */
    private String idcard;
    /**
     * 数据
     */
    private String data;
    public String getIdcard() {
        return idcard;
    }
    public void setIdcard(String idcard) {
        this.idcard = idcard;
    }
    public String getData() {
        return data;
    }
    public void setData(String data) {
        this.data = data;
    }
}

+ 15 - 0
patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/model/SaveModel.java

@ -1,9 +1,15 @@
package com.yihu.wlyy.figure.label.model;
import io.searchbox.annotations.JestId;
/**
 * Created by chenweida on 2018/3/7.
 */
public class SaveModel {
    @JestId
    private String id;
    /**
     * 身份证
     */
@ -37,6 +43,15 @@ public class SaveModel {
        return labelType;
    }
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public void setLabelType(String labelType) {
        this.labelType = labelType;
    }

+ 5 - 0
patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/service/ExtractService.java

@ -0,0 +1,5 @@
package com.yihu.wlyy.figure.label.service;
public class ExtractService {
}

+ 378 - 0
patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/service/JobService.java

@ -0,0 +1,378 @@
package com.yihu.wlyy.figure.label.service;
import com.yihu.figure_label.entity.FLJobConfig;
import com.yihu.wlyy.figure.label.dao.FLJobConfigDao;
import com.yihu.wlyy.figure.label.util.QuartzHelper;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
@Service
public class JobService {
    @Value("${JobService.sleepTime}")
    private Integer sleepTime;
    @Autowired
    private QuartzHelper quartzHelper;
    @Autowired
    private FLJobConfigDao flJobConfigDao;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Transactional
    public void stopById(String id) throws Exception {
        FLJobConfig flJobConfig = flJobConfigDao.findByIdAndStatus(id, "1");
        if (flJobConfig != null) {
            for (int j = 1; j <= 2; j++) {
                quartzHelper.removeJob(flJobConfig.getId() + "-" + j);
                flJobConfigDao.updateStatus(flJobConfig.getId().toString(),"0") ;;
            }
        } else {
            throw new Exception("任务已经停止");
        }
    }
    @Transactional
    public void startById(String id) throws Exception {
        FLJobConfig FLJobConfig = flJobConfigDao.findByIdAndStatus(id, "0");
        if (FLJobConfig != null) {
            startOneJob(FLJobConfig);
        } else {
            throw new Exception("任务已经启动");
        }
    }
    @Transactional
    public void stopAll() throws Exception {
        List<FLJobConfig> FLJobConfigs = flJobConfigDao.findByAll("1");
        if (FLJobConfigs != null && FLJobConfigs.size() > 0) {
            for (FLJobConfig FLJobConfig : FLJobConfigs) {
                for (int j = 1; j <= 2; j++) {
                    quartzHelper.removeJob(FLJobConfig.getId() + "-" + j);
                    flJobConfigDao.updateStatus(FLJobConfig.getId().toString(),"0") ;;
                }
            }
        } else {
            throw new Exception("任务已经全部停止");
        }
    }
    @Transactional
    public void startAll() throws Exception {
        List<FLJobConfig> FLJobConfigs = flJobConfigDao.findByAll("0");
        if (FLJobConfigs != null && FLJobConfigs.size() > 0) {
            for (FLJobConfig FLJobConfig : FLJobConfigs) {
                startOneJob(FLJobConfig);
            }
        } else {
            throw new Exception("任务已经全部启动");
        }
    }
    /**
     * 启动单个任务
     *
     * @param FLJobConfig
     * @throws Exception
     */
    @Transactional
    public void startOneJob(FLJobConfig FLJobConfig) throws Exception {
        FLJobConfig flJobConfigVO = new FLJobConfig();
        BeanUtils.copyProperties(FLJobConfig, flJobConfigVO);
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("jobConfig", flJobConfigVO.getId());
        //表里设置的增量查询类型和增量查询初始值,如果值没有配置,以当前时间为准
        if(!StringUtils.isEmpty(flJobConfigVO.getSqlFieldValue())){
            params.put(flJobConfigVO.getSqlField(),flJobConfigVO.getSqlFieldValue());
        }else{
            params.put(flJobConfigVO.getSqlField(), DateFormatUtils.format(new Date(),"yyyy-MM-dd HH:mm:ss"));
        }
        if (!StringUtils.isEmpty(FLJobConfig.getJobClass())) {
            //往quartz框架添加任务
            quartzHelper.addJob(getRightClass(FLJobConfig), FLJobConfig.getQuartzCron(), FLJobConfig.getId().toString(), params);
            flJobConfigDao.updateStatus(FLJobConfig.getId().toString(), "1");//设置任务状态是启动 }
        }
    }
    public void startNowById(String id) throws Exception {
        FLJobConfig FLJobConfig = flJobConfigDao.findOne(id);
        FLJobConfig wlyyJobConfigVO = new FLJobConfig();
        BeanUtils.copyProperties(FLJobConfig, wlyyJobConfigVO);
        Map<String, String> params = new HashMap<String, String>();
        params.put("jobConfig", wlyyJobConfigVO.getId().toString());
        //往quartz框架添加任务
        if (!StringUtils.isEmpty(FLJobConfig.getJobClass())) {
            quartzHelper.startNow(getRightClass(FLJobConfig), FLJobConfig.getId() + UUID.randomUUID().toString().replace("-", ""), params);
            Thread.sleep(sleepTime);
        }
    }
    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 {
        String sql="select * from wlyy_job_config_new a where  a.del='1' and a.id !=11 order by a.id asc";
        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 daybefore = new SimpleDateFormat("yyyy-MM-dd").format(nowDate.getTime());
        List<FLJobConfig> FLJobConfigs = jdbcTemplate.query(sql,new BeanPropertyRowMapper(FLJobConfig.class));
        for (FLJobConfig FLJobConfig : FLJobConfigs) {
            FLJobConfig flJobConfig = new FLJobConfig();
            BeanUtils.copyProperties(FLJobConfig, flJobConfig);
            Map<String, String> params = new HashMap<String, String>();
            params.put("jobConfig", flJobConfig.getId().toString());
            //往quartz框架添加任务
            params.put("sqlFiledValue", daybefore+","+yesterday);
            params.put("sqlFiledCondition", "<");
            if (!StringUtils.isEmpty(FLJobConfig.getJobClass())) {
                quartzHelper.startNow(getRightClass(FLJobConfig), FLJobConfig.getId() + UUID.randomUUID().toString().replace("-", ""), params);
                Thread.sleep(sleepTime);
            }
        }
    }
    /**
     * @param FLJobConfig
     * @return
     * @throws ClassNotFoundException
     */
    private Class getRightClass(FLJobConfig FLJobConfig) throws ClassNotFoundException {
        return Class.forName(FLJobConfig.getJobClass());
    }
    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 daybefore = new SimpleDateFormat("yyyy-MM-dd").format(nowDate.getTime());
        FLJobConfig FLJobConfig = flJobConfigDao.findById(id);
        if (FLJobConfig == null) {
            throw new Exception("id不存在");
        }
        FLJobConfig flJobConfigVO = new FLJobConfig();
        BeanUtils.copyProperties(FLJobConfig, flJobConfigVO);
        Map<String, String> params = new HashMap<String, String>();
        params.put("jobConfig", flJobConfigVO.getId().toString());
        //往quartz框架添加任务
        params.put("sqlFiledValue", daybefore + "," + yesterday);
        params.put("sqlFiledCondition", "<");
        if (!StringUtils.isEmpty(FLJobConfig.getJobClass())) {
            quartzHelper.startNow(getRightClass(FLJobConfig), FLJobConfig.getId() + UUID.randomUUID().toString().replace("-", ""), params);
            Thread.sleep(sleepTime);
        }
    }
    public void productDataByDayAndId(Integer day, String id) throws Exception {
        FLJobConfig FLJobConfig = flJobConfigDao.findById(id);
        if (FLJobConfig == null) {
            throw new Exception("id不存在");
        }
        FLJobConfig flJobConfigVO = new FLJobConfig();
        BeanUtils.copyProperties(FLJobConfig, flJobConfigVO);
        Map<String, String> params = new HashMap<String, String>();
        params.put("jobConfig", flJobConfigVO.getId().toString());
        for (int i = 1; i <= day; i++) {
            //往quartz框架添加任务
            params.put("sqlFiledValue",  getYesterday(0 - i - 1)+","+getYesterday(0 - i));
            params.put("sqlFiledCondition", "<");
            if (!StringUtils.isEmpty(FLJobConfig.getJobClass())) {
                quartzHelper.startNow(getRightClass(FLJobConfig), FLJobConfig.getId() + UUID.randomUUID().toString().replace("-", ""), params);
                Thread.sleep(sleepTime);
            }
        }
    }
    public void productDataByDayToDay(String start, String end) throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date startDate = sdf.parse(start);
        Date endDate = sdf.parse(end);
        if (startDate.after(endDate)) {
            throw new Exception("日期参数错误");
        }
        int day = daysBetween(startDate, endDate);
        for (int i = 0; i < day; i++) {
            productDataByOneDay(getYesterday(i, startDate));
        }
    }
    public static String getYesterday(Integer day, Date startDate) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(startDate);
        cal.add(Calendar.DAY_OF_MONTH, day);
        String yesterday = new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime());
        return yesterday;
    }
    public static int daysBetween(Date smdate, Date bdate) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        smdate = sdf.parse(sdf.format(smdate));
        bdate = sdf.parse(sdf.format(bdate));
        Calendar cal = Calendar.getInstance();
        cal.setTime(smdate);
        long time1 = cal.getTimeInMillis();
        cal.setTime(bdate);
        long time2 = cal.getTimeInMillis();
        long between_days = (time2 - time1) / (1000 * 3600 * 24);
        return Integer.parseInt(String.valueOf(between_days));
    }
    public void productDataByDayToDayAndId(String start, String end, String ids) throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date startDate = sdf.parse(start);
        Date endDate = sdf.parse(end);
        if (startDate.after(endDate)) {
            throw new Exception("日期参数错误");
        }
        int day = daysBetween(startDate, endDate);
        String [] idStr=ids.split(",");
        for (int i = 0; i < day; i++) {
            for(String id:idStr){
                productDataByOneDayWithId(getYesterday(i, startDate), id);
            }
        }
    }
    //================================================没有休眠时间=============================================================
    public void productDataByDayToDayAndIdNoSleep(String start, String end, String id,Long sleepTime) throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date startDate = sdf.parse(start);
        Date endDate = sdf.parse(end);
        if (startDate.after(endDate)) {
            throw new Exception("日期参数错误");
        }
        int day = daysBetween(startDate, endDate);
        for (int i = 0; i < day; i++) {
            productDataByOneDayWithIdNoSleep(getYesterday(i, startDate), id,sleepTime);
        }
    }
    public void productDataByOneDayWithIdNoSleep(String yesterday, String id,Long sleepTime) 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 daybefore = new SimpleDateFormat("yyyy-MM-dd").format(nowDate.getTime());
        FLJobConfig FLJobConfig = flJobConfigDao.findById(id);
        if (FLJobConfig == null) {
            throw new Exception("id不存在");
        }
        FLJobConfig flJobConfigVO = new FLJobConfig();
        BeanUtils.copyProperties(FLJobConfig, flJobConfigVO);
        Map<String, String> params = new HashMap<String, String>();
        params.put("jobConfig", flJobConfigVO.getId().toString());
        //往quartz框架添加任务
        params.put("sqlFiledValue", daybefore + "," + yesterday);
        params.put("sqlFiledCondition", "<");
        if (!StringUtils.isEmpty(FLJobConfig.getJobClass())) {
            quartzHelper.startNow(getRightClass(FLJobConfig), FLJobConfig.getId() + UUID.randomUUID().toString().replace("-", ""), params);
        }
        Thread.sleep(sleepTime * 1000L);
    }
    public void productDataByOneDayNoSleep(String yesterday,Long sleepTime) throws Exception {
        String sql="select * from wlyy_job_config_new a where  a.del='1' and a.id !=11 order by a.id asc";
        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 daybefore = new SimpleDateFormat("yyyy-MM-dd").format(nowDate.getTime());
        List<FLJobConfig> FLJobConfigs = jdbcTemplate.query(sql,new BeanPropertyRowMapper(FLJobConfig.class));
        for (FLJobConfig FLJobConfig : FLJobConfigs) {
            FLJobConfig flJobConfigVO = new FLJobConfig();
            BeanUtils.copyProperties(FLJobConfig, flJobConfigVO);
            Map<String, String> params = new HashMap<String, String>();
            params.put("jobConfig", flJobConfigVO.getId().toString());
            //往quartz框架添加任务
            params.put("sqlFiledValue", daybefore + "," + yesterday);
            params.put("sqlFiledCondition", "<");
            if (!StringUtils.isEmpty(FLJobConfig.getJobClass())) {
                quartzHelper.startNow(getRightClass(FLJobConfig), FLJobConfig.getId() + UUID.randomUUID().toString().replace("-", ""), params);
            }
            Thread.sleep(sleepTime * 1000L);
        }
    }
   /* public void startCleanCacheJob() throws Exception {
        if (!quartzHelper.isExistJob(CacheCleanJob.jobKey)) {
            quartzHelper.addJob(CacheCleanJob.class, CacheCleanJob.cron, CacheCleanJob.jobKey, new HashMap<>());
        } else {
            throw new Exception("已经启动");
        }
    }
    public void stopCleanCacheJob() throws Exception {
        if (quartzHelper.isExistJob(CacheCleanJob.jobKey)) {
            quartzHelper.removeJob(CacheCleanJob.jobKey);
        } else {
            throw new Exception("已经停止");
        }
    }*/
}

+ 27 - 0
patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/storage/Store2ES.java

@ -0,0 +1,27 @@
package com.yihu.wlyy.figure.label.storage;
import com.yihu.base.es.config.ElastricSearchHelper;
import com.yihu.wlyy.figure.label.model.SaveModel;
import com.yihu.wlyy.figure.label.util.ConstantUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
@Component
public class Store2ES implements Storager {
    @Autowired
    private ElastricSearchHelper elastricSearchHelper;
    @Override
    public void save(List<SaveModel> modelList) {
        List<Object> list = new ArrayList<>();
        modelList.forEach(
                obj-> list.add(obj)
        );
        elastricSearchHelper.save(ConstantUtil.figure_label_es_index, ConstantUtil.figure_label_es_type, list);
    }
}

+ 12 - 0
patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/storage/Store2Hbase.java

@ -0,0 +1,12 @@
package com.yihu.wlyy.figure.label.storage;
import com.yihu.wlyy.figure.label.model.SaveModel;
import java.util.List;
public class Store2Hbase implements Storager {
    @Override
    public void save(List<SaveModel> modelList) {
    }
}

+ 7 - 0
patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/util/ConstantUtil.java

@ -0,0 +1,7 @@
package com.yihu.wlyy.figure.label.util;
public class ConstantUtil {
    public static final String figure_label_es_index = "figure_label_index";
    public static final String figure_label_es_type = "figure_label_type";
    public static final String date_format = "yyyy-MM-dd HH:mm:ss";
}

+ 114 - 0
patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/util/IdCardUtil.java

@ -0,0 +1,114 @@
package com.yihu.wlyy.figure.label.util;
import org.apache.commons.lang3.StringUtils;
import java.util.Calendar;
/***
 * 根据居民身份证提取相对应的信息
 */
public class IdCardUtil {
    /**
     * 根据身份证的号码算出当前身份证持有者的性别
     * 1 女 2 男 3未知
     *
     * @return
     * @throws Exception
     */
    public static String getSexForIdcard(String idCard){
        if(StringUtils.isEmpty(idCard)){
            return "未知";
        }
        try {
            String sex = "2";
            if (idCard.length() == 18) {
                if (Integer.parseInt(idCard.substring(16).substring(0, 1)) % 2 == 0) {// 判断性别
                    sex = "1";
                } else {
                    sex = "2";
                }
            } else if (idCard.length() == 15) {
                String usex = idCard.substring(14, 15);// 用户的性别
                if (Integer.parseInt(usex) % 2 == 0) {
                    sex = "1";
                } else {
                    sex = "2";
                }
            }
            return sex;
        } catch (Exception e) {
            return "1";
        }
    }
    /**
     * 根据身份证的号码算出当前身份证持有者的年龄
     *
     * @param
     * @throws Exception
     */
    public static int getAgeForIdcard(String idCard) {
        int age = 0;
        if(StringUtils.isEmpty(idCard)){
            return age;
        }
        try {
            if (org.springframework.util.StringUtils.isEmpty(idCard)) {
                return age;
            }
            String birth = "";
            if (idCard.length() == 18) {
                birth = idCard.substring(6, 14);
            } else if (idCard.length() == 15) {
                birth = "19" + idCard.substring(6, 12);
            } else {
                return age;
            }
            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 idCard
     * @return
     * @throws Exception
     */
    public static String getBirthdayForIdcard(String idCard) throws Exception {
        if(StringUtils.isEmpty(idCard)){
            return "";
        }
        String birthday = null;
        if (idCard.length() == 18) {
            birthday = idCard.substring(6,14);
        } else if (idCard.length() == 15) {
            birthday = "19" + idCard.substring(7,12);
        }
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(birthday.substring(0,4)).append("-");
        stringBuilder.append(birthday.substring(4,6)).append("-");
        stringBuilder.append(birthday.substring(6,8));
        return stringBuilder.toString();
    }
    public static void main(String args[]) throws Exception {
//        System.out.println(getBirthdayForIdcard("411321198004273615"));
//        System.out.println(getSexForIdcard("411321198004273615"));
        System.out.println(getAgeForIdcard("411321198004273615"));
    }
}

+ 124 - 0
patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/util/QuartzHelper.java

@ -0,0 +1,124 @@
package com.yihu.wlyy.figure.label.util;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.util.Date;
import java.util.Map;
import static org.quartz.SimpleScheduleBuilder.simpleSchedule;
@Configuration
public class QuartzHelper {
    @Autowired
    private SchedulerFactoryBean schedulerFactoryBean;
    private Scheduler scheduler = null;
    @Bean
    public SchedulerFactoryBean getSchedulerFactoryBean(){
        return new SchedulerFactoryBean();
    }
    @PostConstruct
    public void init() {
        try {
            scheduler = schedulerFactoryBean.getScheduler();
            scheduler.start();
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }
    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)
                                    //——以错过的第一个频率时间立刻开始执行
                                    //——重做错过的所有频率周期后
                                    //——当下一次触发频率发生时间大于当前时间后,再按照正常的Cron频率依次执行
                                    .withMisfireHandlingInstructionIgnoreMisfires()
                    )
                    .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-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, String> 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, String> 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, "trigger-group:" + id)
                .startAt(time)
                .withSchedule(
                        simpleSchedule()
                                .withIntervalInSeconds(10)
                                .withRepeatCount(0)
                                .withMisfireHandlingInstructionIgnoreMisfires()
                )
                .build();
        scheduler.scheduleJob(job, trigger);
        scheduler.start();
    }
}

+ 17 - 5
patient-co/patient-co-figure-label/src/main/resources/application-dev.yml

@ -3,12 +3,24 @@ spring:
  profiles: dev
  datasource:
#    wlyy:
#      url: jdbc:mysql://172.19.103.85/figure_lable?useUnicode:true&amp;characterEncoding=utf-8&amp;autoReconnect=true
#      username: linzhou
#      password: linzhou
    wlyy:
      url: jdbc:mysql://172.19.103.85/figure_lable?useUnicode:true&amp;characterEncoding=utf-8&amp;autoReconnect=true
      username: linzhou
      password: linzhou
      url: jdbc:mysql://172.19.103.77/figure_lable?useUnicode:true&amp;characterEncoding=utf-8&amp;autoReconnect=true
      username: root
      password: 123456
  data:
    elasticsearch:
      cluster-nodes-jest: http://172.19.103.45:9200,http://172.19.103.68:9200  #多个逗号分割
      repositories:
        enabled: true
quartz:
  namespace: patient-co-figure-label ##quartz的命名空间,名称一样实现消费负载
  overwriteExistingJobs: false ##是否覆盖job
  overwriteExistingJobs: false ##是否覆盖job
JobService:
  sleepTime: 40000