Commit 6ae99059 authored by tianbo's avatar tianbo

隐患修改提交

parent da3cd2bf
<?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>
<artifactId>amos-boot-module-api</artifactId>
<groupId>com.amosframework.boot</groupId>
<version>1.0.0</version>
</parent>
<artifactId>amos-boot-module-latentdanger-api</artifactId>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
<exclusions>
<exclusion>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-jdbc</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-base</artifactId>
<version>3.0.3</version>
</dependency>
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-web</artifactId>
<version>3.0.3</version>
</dependency>
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-annotation</artifactId>
<version>3.0.3</version>
</dependency>
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.11.2</version>
</dependency>
<dependency>
<groupId>com.amosframework.boot</groupId>
<artifactId>amos-boot-module-common-api</artifactId>
<version>${amos-biz-boot.version}</version>
</dependency>
<dependency>
<groupId>com.amosframework.boot</groupId>
<artifactId>amos-boot-biz-common</artifactId>
<version>${amos-biz-boot.version}</version>
</dependency>
</dependencies>
</project>
package com.yeejoin.amos.latentdanger.common.enums;
import lombok.AllArgsConstructor;
import lombok.Getter;
/**
* @author DELL
*/
@Getter
@AllArgsConstructor
public enum DangerHandleStateEnum {
/**
* 隐患治理中
*/
HANDLE("隐患治理中", 0),
/**
* 隐患治理完成
*/
COMPLETED("隐患治理完成", 1);
/**
* 名称,描述
*/
private String name;
/**
* 编码
*/
private Integer code;
}
package com.yeejoin.amos.latentdanger.common.enums;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 字典枚举对象
* @author maoying
*
*/
public enum DictTypeEnum {
/**
* 隐患等级
*/
DANGERLEVEL("隐患等级", "DANGER_LEVEL");
/**
* 名称,描述
*/
private String name;
/**
* 编码
*/
private String code;
private DictTypeEnum(String name, String code){
this.name = name;
this.code = code;
}
public static DictTypeEnum getEnum(String code) {
DictTypeEnum instance = null;
for(DictTypeEnum type: DictTypeEnum.values()) {
if (type.getCode().equals(code)) {
instance = type;
break;
}
}
return instance;
}
public static List<Map<String,String>> getEnumList() {
List<Map<String,String>> list = new ArrayList<>();
for(DictTypeEnum e : DictTypeEnum.values()) {
Map<String, String> map = new HashMap<String, String>();
map.put("code", e.getCode());
map.put("name", e.getName());
list.add(map);
}
return list;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
}
package com.yeejoin.amos.latentdanger.common.enums;
public enum ExecuteStateEnum {
未执行("未执行", 1, ""),
通过("通过", 2, "{\"action\": \"complete\",\"variables\": [{\"name\": \"rejected\",\"value\": false}]}"),
驳回("驳回", 3, "{\"action\": \"complete\",\"variables\": [{\"name\": \"rejected\",\"value\": true}]}"),
已确认("已确认", 4, ""),
停止执行("停止执行", 5, ""),
作业开始执行("作业开始执行", 6, ""),
作业完成("作业完成", 7, "");
/**
* 名称,描述
*/
private String name;
/**
* 编码
*/
private Integer code;
private String requestBody;
ExecuteStateEnum(String name, Integer code, String requestBody) {
this.name = name;
this.code = code;
this.requestBody = requestBody;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getRequestBody() {
return requestBody;
}
public void setRequestBody(String requestBody) {
this.requestBody = requestBody;
}
public static ExecuteStateEnum getByCode(Integer code) {
for (ExecuteStateEnum e : ExecuteStateEnum.values()) {
if (code.equals(e.getCode())) {
return e;
}
}
return null;
}
}
package com.yeejoin.amos.latentdanger.common.enums;
import lombok.AllArgsConstructor;
import lombok.Getter;
/**
* 规则请求枚举
* @author WJK
*
*/
@Getter
@AllArgsConstructor
public enum InstanceKeyEnum {
NORMAL("无码无计划隐患","normalHazardManagement"),
PATROL("巡检隐患","hazardManagement" );
/**
* 名称,描述
*/
private String name;
/**
* 编码
*/
private String code;
}
package com.yeejoin.amos.latentdanger.common.enums;
/**
* 业务配置枚举
*
* @author DELL
*/
public enum LatentDangerBizTypeEnum {
/**
* 防火监督
*/
防火监督("防火监督", "supervision", "fire_supervision_hazard_management"),
/**
* 巡检
*/
巡检("巡检", "patrol", "");
/**
* 业务名称
*/
String name;
/**
* 业务code
*/
String code;
/**
* 业务对应工作流定义key
*/
String workflowDefKey;
LatentDangerBizTypeEnum(String name, String code, String workflowDefKey) {
this.name = name;
this.code = code;
this.workflowDefKey = workflowDefKey;
}
public static LatentDangerBizTypeEnum getByCode(String code) {
for (LatentDangerBizTypeEnum l : LatentDangerBizTypeEnum.values()) {
if (l.getCode().equals(code)) {
return l;
}
}
return null;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
}
package com.yeejoin.amos.latentdanger.common.enums;
/**
* @author Dell
*/
public enum LatentDangerExecuteTypeEnum {
填写隐患完成("填写隐患完成", 1, ExecuteStateEnum.通过, LatentDangerStateEnum.待评审,
"{\"action\": \"complete\"}"),
隐患评审通过("隐患评审通过", 2, ExecuteStateEnum.通过, LatentDangerStateEnum.待治理,
"{\"reviewResult\": \"通过\"}"),
隐患评审拒绝("隐患评审拒绝", 3, ExecuteStateEnum.驳回, LatentDangerStateEnum.已撤销,
"{\"reviewResult\": \"不通过\"}"),
隐患常规治理("隐患常规治理", 4, ExecuteStateEnum.通过, LatentDangerStateEnum.待验证,
"{\"rectifyResult\": \"常规整改\"}"),
隐患安措计划("隐患安措计划", 5, ExecuteStateEnum.通过, LatentDangerStateEnum.安措计划中,
"{\"action\": \"complete\",\"variables\": [{\"name\": \"rectification\",\"value\": \"plan\"}]}"),
隐患延期治理("隐患延期治理", 15, ExecuteStateEnum.通过, LatentDangerStateEnum.延期治理申请待车间部门审核,
"{\"rectifyResult\": \"延期\"}"),
隐患延期治理车间部门审核通过("隐患延期治理车间部门审核通过", 16, ExecuteStateEnum.通过, LatentDangerStateEnum.待治理,
"{\"approveResult\": \"通过\"}"),
隐患延期治理车间部门审核拒绝("隐患延期治理车间部门审核拒绝", 17, ExecuteStateEnum.驳回, LatentDangerStateEnum.待治理,
"{\"approveResult\": \"不通过\"}"),
隐患延期治理公司审核通过("隐患延期治理公司审核通过", 18, ExecuteStateEnum.通过, LatentDangerStateEnum.待治理,
"{\"approveResult\": true}"),
隐患延期治理公司审核拒绝("隐患延期治理公司审核拒绝", 19, ExecuteStateEnum.驳回, LatentDangerStateEnum.延期治理申请待车间部门审核,
"{\"approveResult\": false}"),
填写安措计划完成("填写安措计划完成", 6, ExecuteStateEnum.通过, LatentDangerStateEnum.安措计划中,
"{\"action\": \"complete\"}"),
车间部门审核通过("车间部门审核通过", 7, ExecuteStateEnum.通过, LatentDangerStateEnum.安措计划中,
"{\"action\": \"complete\",\"variables\": [{\"name\": \"rejected\",\"value\": false}]}"),
车间部门审核拒绝("车间部门审核拒绝", 8, ExecuteStateEnum.驳回, LatentDangerStateEnum.待治理,
"{\"action\": \"complete\",\"variables\": [{\"name\": \"rejected\",\"value\": true}]}"),
总工程师审核通过("总工程师审核通过", 9, ExecuteStateEnum.通过, LatentDangerStateEnum.安措计划中,
"{\"action\": \"complete\",\"variables\": [{\"name\": \"rejected\",\"value\": false}]}"),
总工程师审核拒绝("总工程师审核拒绝", 10, ExecuteStateEnum.驳回, LatentDangerStateEnum.待治理,
"{\"action\": \"complete\",\"variables\": [{\"name\": \"rejected\",\"value\": true}]}"),
公司负责人审核通过("公司负责人审核通过", 11, ExecuteStateEnum.通过, LatentDangerStateEnum.待验证,
"{\"action\": \"complete\",\"variables\": [{\"name\": \"rejected\",\"value\": false}]}"),
公司负责人审核拒绝("公司负责人审核拒绝", 12, ExecuteStateEnum.驳回, LatentDangerStateEnum.待治理,
"{\"action\": \"complete\",\"variables\": [{\"name\": \"rejected\",\"value\": true}]}"),
隐患验证通过("隐患验证通过", 13, ExecuteStateEnum.通过, LatentDangerStateEnum.治理完毕,
"{\"validationResult\": \"通过\"}"),
隐患验证拒绝("隐患验证拒绝", 14, ExecuteStateEnum.驳回, LatentDangerStateEnum.待治理,
"{\"validationResult\": \"不通过\"}");
/**
* 名称,描述
*/
private String name;
/**
* 编码
*/
private Integer code;
/**
* 执行状态
*/
private ExecuteStateEnum executeState;
private String requestBody;
private LatentDangerStateEnum nextState;
LatentDangerExecuteTypeEnum(String name, Integer code, ExecuteStateEnum executeState, LatentDangerStateEnum nextState, String requestBody) {
this.name = name;
this.code = code;
this.executeState = executeState;
this.requestBody = requestBody;
this.nextState = nextState;
}
public static LatentDangerExecuteTypeEnum getByCode(Integer code) {
for (LatentDangerExecuteTypeEnum e : LatentDangerExecuteTypeEnum.values()) {
if (code.equals(e.getCode())) {
return e;
}
}
return null;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public ExecuteStateEnum getExecuteState() {
return executeState;
}
public void setExecuteState(ExecuteStateEnum executeState) {
this.executeState = executeState;
}
public String getRequestBody() {
return requestBody;
}
public void setRequestBody(String requestBody) {
this.requestBody = requestBody;
}
public LatentDangerStateEnum getNextState() {
return nextState;
}
public void setNextState(LatentDangerStateEnum nextState) {
this.nextState = nextState;
}
}
package com.yeejoin.amos.latentdanger.common.enums;
import com.yeejoin.amos.boot.biz.common.utils.DynamicEnumUtil;
import java.util.HashMap;
import java.util.Map;
/**
* @author DELL
*/
public enum LatentDangerLevelEnum {
/**
* 安全问题
*/
安全问题("安全问题", "0", "0", 1),
/**
* 一般隐患
*/
一般隐患("一般隐患", "1", "1", 2),
/**
* 重大隐患
*/
重大隐患("重大隐患", "2", "2", 3);
/**
* 枚举缓存
*/
public static Map<String, LatentDangerLevelEnum> enumMap = new HashMap<>();
public static final String dictCode = "_DANGER_LEVEL";
/**
* 名称,描述
*/
private String name;
/**
* 编码
*/
private String code;
/**
* 风险源等级
*/
private String riskSourceDangerLevelCode;
/**
* 排序
*/
private Integer order;
// static {
// EnumSet<LatentDangerLevelEnum> set = EnumSet.allOf(LatentDangerLevelEnum.class);
// for (LatentDangerLevelEnum each : set) {
// // 增加一个缓存 减少对枚举的修改
// enumMap.put(each.code, each);
// }
// }
LatentDangerLevelEnum(String name, String code, String riskSourceDangerLevelCode, Integer order) {
this.name = name;
this.code = code;
this.riskSourceDangerLevelCode = riskSourceDangerLevelCode;
this.order = order;
}
public static LatentDangerLevelEnum getByRiskSourceDangerLevelCode(String riskSourceDangerLevelCode) {
for (LatentDangerLevelEnum l : LatentDangerLevelEnum.values()) {
if (riskSourceDangerLevelCode.equals(l.getRiskSourceDangerLevelCode())) {
return l;
}
}
return null;
}
public static LatentDangerLevelEnum getEnumByOrder(Integer order) {
for (LatentDangerLevelEnum l : enumMap.values()) {
if (order.equals(l.getOrder())) {
return l;
}
}
return null;
}
/**
* 根据关键字段获取枚举值 可以在这里做一些修改 来达到动态添加的效果
*
* @param code
*/
public static LatentDangerLevelEnum getEnumByCode(String code) {
// 这里可以做一些修改 比如若从 enumMap 中没有取得 则加载配置动态添加
return enumMap.get(code);
}
public static LatentDangerLevelEnum addEnumDynamic(String enumName, String name, String code,
String riskSourceDangerLevelCode, Integer order) {
LatentDangerLevelEnum dangerLevelEnum = DynamicEnumUtil.addEnum(LatentDangerLevelEnum.class, enumName,
new Class[]{String.class, String.class, String.class, Integer.class}, new Object[]{name, code,
riskSourceDangerLevelCode, order});
enumMap.put(code, dangerLevelEnum);
return dangerLevelEnum;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getRiskSourceDangerLevelCode() {
return riskSourceDangerLevelCode;
}
public void setRiskSourceDangerLevelCode(String riskSourceDangerLevelCode) {
this.riskSourceDangerLevelCode = riskSourceDangerLevelCode;
}
public Integer getOrder() {
return order;
}
public void setOrder(Integer order) {
this.order = order;
}
}
package com.yeejoin.amos.latentdanger.common.enums;
public enum LatentDangerOvertimeStateEnum {
未超时("未超时", 0),
已超时("已超时", 1);
/**
* 名称,描述
*/
private String name;
/**
* 编码
*/
private Integer code;
LatentDangerOvertimeStateEnum(String name, Integer code) {
this.name = name;
this.code = code;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public static LatentDangerOvertimeStateEnum getByCode(Integer code) {
for (LatentDangerOvertimeStateEnum l : LatentDangerOvertimeStateEnum.values()) {
if (code.equals(l.getCode())) {
return l;
}
}
return null;
}
}
package com.yeejoin.amos.latentdanger.common.enums;
import com.yeejoin.amos.boot.biz.common.utils.DynamicEnumUtil;
import java.util.HashMap;
import java.util.Map;
/**
* 隐患治理方式枚举
*
* @author DELL
*/
public enum LatentDangerReformTypeEnum {
/**
* 常规整改
*/
常规整改("常规整改", "1"),
/**
* 安措计划
*/
安措计划("安措计划", "2"),
/**
* 延期治理
*/
延期治理("延期治理", "3");
/**
* 名称,描述
*/
private String name;
/**
* 编码
*/
private String code;
/**
* 枚举缓存
*/
public static Map<String, LatentDangerReformTypeEnum> enumMap = new HashMap<>();
public static final String dictCode = "_GOVERNANCE";
LatentDangerReformTypeEnum(String name, String code) {
this.name = name;
this.code = code;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
/**
* 根据关键字段获取枚举值 可以在这里做一些修改 来达到动态添加的效果
*
* @param code
*/
public static LatentDangerReformTypeEnum getEnumByCode(String code) {
// 这里可以做一些修改 比如若从 enumMap 中没有取得 则加载配置动态添加
return enumMap.get(code);
}
public static LatentDangerReformTypeEnum addEnumDynamic(String enumName, String name, String code) {
LatentDangerReformTypeEnum dangerReformTypeEnum = DynamicEnumUtil.addEnum(LatentDangerReformTypeEnum.class, enumName,
new Class[]{String.class, String.class}, new Object[]{name, code});
enumMap.put(code, dangerReformTypeEnum);
return dangerReformTypeEnum;
}
}
package com.yeejoin.amos.latentdanger.common.enums;
import com.yeejoin.amos.boot.biz.common.utils.DynamicEnumUtil;
import java.util.HashMap;
import java.util.Map;
public enum LatentDangerStateEnum {
待评审("待评审", "1"),
待治理("待治理", "2"),
安措计划中("安措计划中", "3"),
待验证("待验证", "4"),
治理完毕("治理完毕", "5"),
已撤销("已撤销", "6"),
延期治理申请("延期治理中", "7"),
延期治理申请待车间部门审核("延期治理待车间部门审核", "8"),
延期治理申请待公司审核("延期治理待公司审核", "9");
/**
* 名称,描述
*/
private String name;
/**
* 编码
*/
private String code;
/**
* 枚举缓存
*/
public static Map<String, LatentDangerStateEnum> enumMap = new HashMap<>();
public static final String dictCode = "_GOVERNANCE_PROGRESS";
LatentDangerStateEnum(String name, String code) {
this.name = name;
this.code = code;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public static String getEnumName(String code) {
return enumMap.get(code).getName();
}
public static LatentDangerStateEnum getByCode(String code) {
return enumMap.get(code);
}
public static LatentDangerStateEnum addEnumDynamic(String enumName, String name, String code) {
LatentDangerStateEnum dangerStateEnum = DynamicEnumUtil.addEnum(LatentDangerStateEnum.class, enumName,
new Class[]{String.class, String.class}, new Object[]{name, code});
enumMap.put(code, dangerStateEnum);
return dangerStateEnum;
}
}
package com.yeejoin.amos.latentdanger.common.enums;
/**
* 隐患来源类型枚举
*
* @author DELL
*/
public enum LatentDangerTypeEnum {
/**
* 无码检查
*/
无码检查("无码检查", "1"),
/**
* 计划检查
*/
计划检查("计划检查", "2"),
/**
* 无计划检查
*/
无计划检查("无计划检查", "3"),
/**
* 随手拍
*/
随手拍("随手拍", "4");
/**
* 名称,描述
*/
private String name;
/**
* 编码
*/
private String code;
LatentDangerTypeEnum(String name, String code) {
this.name = name;
this.code = code;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public static String getEnumName(String code) {
String name = "";
for(LatentDangerTypeEnum type: LatentDangerTypeEnum.values()) {
if (type.getCode()==code) {
name = type.getName();
break;
}
}
return name;
}
public static LatentDangerTypeEnum getByCode(String code) {
for (LatentDangerTypeEnum l : LatentDangerTypeEnum.values()) {
if (code.equals(l.getCode())) {
return l;
}
}
return null;
}
}
package com.yeejoin.amos.latentdanger.common.enums;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import java.util.List;
import java.util.Map;
/**
* @author DELL
*/
public enum MsgSubscribeEnum {
/**
* 风险评价提醒推送
*/
风险评价提醒推送("riskFatorApp", "风险评价提醒", "风险评价提醒", false, "default"),
/**
* 隐患治理推送
*/
隐患治理推送("latentDangerApp", "隐患治理", "隐患治理移动端推送", false, "default");
private String msgType;
private String title;
private String desc;
private Boolean canConfig;
private String type;
MsgSubscribeEnum(String msgType, String title, String desc, Boolean canConfig, String type) {
this.msgType = msgType;
this.title = title;
this.desc = desc;
this.canConfig = canConfig;
this.type = type;
}
public static List<Map<String, String>> getEnumList() {
List<Map<String, String>> list = Lists.newArrayList();
for (MsgSubscribeEnum e : MsgSubscribeEnum.values()) {
if (e.canConfig && !e.getMsgType().equals("checkRecordNoPushApp") && !e.getType().equals("email")) {
Map<String, String> msgType = Maps.newHashMap();
msgType.put(e.getMsgType(), e.getTitle());
list.add(msgType);
}
}
return list;
}
public static MsgSubscribeEnum getByMsgType(String msgType) {
for (MsgSubscribeEnum typeEnum : MsgSubscribeEnum.values()) {
if (msgType.equals(typeEnum.msgType)) {
return typeEnum;
}
}
return null;
}
public String getMsgType() {
return msgType;
}
public void setMsgType(String msgType) {
this.msgType = msgType;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public Boolean getCanConfig() {
return canConfig;
}
public void setCanConfig(Boolean canConfig) {
this.canConfig = canConfig;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
package com.yeejoin.amos.latentdanger.common.enums;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author DELL
*/
public enum MsgTypeEnum {
/**
* 隐患排查
*/
CHECK("隐患排查", "check");
/**
* 名称,描述
*/
private String name;
/**
* 编码
*/
private String code;
private MsgTypeEnum(String name, String code) {
this.name = name;
this.code = code;
}
public static MsgTypeEnum getEnum(String code) {
MsgTypeEnum MsgTypeEnum = null;
for (MsgTypeEnum type : MsgTypeEnum.values()) {
if (type.getCode().equals(code)) {
MsgTypeEnum = type;
break;
}
}
return MsgTypeEnum;
}
public static List<Map<String, String>> getEnumList() {
List<Map<String, String>> list = new ArrayList<>();
for (MsgTypeEnum e : MsgTypeEnum.values()) {
Map<String, String> msgType = new HashMap<>();
msgType.put(e.getCode(), e.getName());
list.add(msgType);
}
return list;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
}
package com.yeejoin.amos.latentdanger.common.enums;
/**
* @author DELL
*/
public enum WorkFlowRiskFactorUriEnum {
/**
* 隐患治理结果推送
*/
隐患治理结果推送("隐患治理结果推送", "/api/protal/hiddentrouble", "");
private String desc;
private String uri;
private String params;
WorkFlowRiskFactorUriEnum(String desc, String uri, String params) {
this.desc = desc;
this.uri = uri;
this.params = params;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public String getUri() {
return uri;
}
public void setUri(String uri) {
this.uri = uri;
}
public String getParams() {
return params;
}
public void setParams(String params) {
this.params = params;
}
}
package com.yeejoin.amos.latentdanger.common.enums;
public enum WorkFlowUriEnum {
启动流程("启动流程", "/workflow/task/startTask", ""),
流程详情("流程详情", "/workflow/task/{taskId}", "taskId"),
合并启动流程("合并启动流程", "/workflow/task/startProcess", ""),
所有已执行任务详情("所有已执行任务详情","/workflow/activitiHistory/task/detail/{taskId}","taskId"),
流程任务("流程任务", "/workflow/task?processInstanceId={processInstanceId}", "processInstanceId"),
我的代办("我的代办", "/workflow/task/all-list?processDefinitionKey={processDefinitionKey}", "processDefinitionKey"),
我的代办有ID("我的代办有ID", "/workflow/task/all-list?processDefinitionKey={processDefinitionKey}&userId={userId}", "processDefinitionKey,userId"),
已执行任务("已执行任务", "/workflow/activitiHistory/all-historytasks?processDefinitionKey={processDefinitionKey}", "processDefinitionKey"),
已执行任务有ID("已执行任务有ID", "/workflow/activitiHistory/all-historytasks?processDefinitionKey={processDefinitionKey}&userId={userId}", "processDefinitionKey,userId"),
启动免登录流程("启动免登录流程", "/processes/{appKey}", "appKey"),
当前节点("当前节点", "/wf/taskstodo?processInstanceId={processInstanceId}", "processInstanceId"),
执行流程("执行流程", "/workflow/task/pickupAndCompleteTask/{taskId}", "taskId"),
终止流程("终止流程", "/wf/processes/{processInstanceId}?deleteReason={deleteReason}", "processInstanceId,deleteReason"),
当前子节点("当前子节点", "/wf/processes/{processInstanceId}/tasks?taskDefinitionKey={taskDefinitionKey}", "processInstanceId,taskDefinitionKey"),
工作流流水("工作流流水","/wf/processes/{processInstanceId}/tasks", "processInstanceId"),
子节点信息("子节点信息","/workflow/task/list/all/{instanceId}", "instanceId");
private String desc;
private String uri;
private String params;
WorkFlowUriEnum(String desc, String uri, String params) {
this.desc = desc;
this.uri = uri;
this.params = params;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public String getUri() {
return uri;
}
public void setUri(String uri) {
this.uri = uri;
}
public String getParams() {
return params;
}
public void setParams(String params) {
this.params = params;
}
}
package com.yeejoin.amos.latentdanger.common.enums;
/**
* 是否枚举
* @author WJK
*
*/
public enum YesOrNoEnum {
NO("否","0"),
YES("是","1" );
/**
* 名称,描述
*/
private String name;
/**
* 编码
*/
private String code;
private YesOrNoEnum(String name, String code){
this.name = name;
this.code = code;
}
public static YesOrNoEnum getEnum(String code) {
YesOrNoEnum jPushTypeEnum = null;
for(YesOrNoEnum type: YesOrNoEnum.values()) {
if (type.getCode().equals(code)) {
jPushTypeEnum = type;
break;
}
}
return jPushTypeEnum;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
}
package com.yeejoin.amos.latentdanger.core.common.request;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
/**
* <pre>
* 分页实体
* </pre>
*
* @author as-chenjiajun
* @version $Id: CommonPageable.java, v 0.1 2016-12-14 上午10:42:44 as-chenjiajun
* Exp $
*/
public class CommonPageable implements Pageable {
/**
* 页号(大于等于0)
*/
protected int pageNumber = 0;
/**
* 每页大小(大于等于0)
*/
protected int pageSize = 10;
/**
* 起始索引
*/
protected int offset = 0;
/**
* 排序
*/
protected Sort sort = null;
public CommonPageable() {
this.pageNumber = 0;
this.pageSize = 10;
this.offset = pageSize * pageNumber;
}
public CommonPageable(int pageNumber, int pageSize) {
this.pageNumber = pageNumber;
this.pageSize = pageSize;
this.offset = pageSize * pageNumber;
}
public CommonPageable(int pageNumber, int pageSize, Sort sort) {
this.pageNumber = pageNumber;
this.pageSize = pageSize;
this.sort = sort;
this.offset = pageSize * pageNumber;
}
public int getPageNumber() {
return this.pageNumber;
}
public void setPageNumber(int pageNumber) {
this.pageNumber = pageNumber;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public long getOffset() {
offset = pageSize * pageNumber;
return offset;
}
public void setOffset(int offset) {
this.offset = offset;
}
public Sort getSort() {
return sort;
}
public void setSort(Sort sort) {
this.sort = sort;
}
public Pageable next() {
return null;
}
public Pageable previousOrFirst() {
return null;
}
public Pageable first() {
return null;
}
public boolean hasPrevious() {
return false;
}
}
package com.yeejoin.amos.patrol.core.common.request;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
/**
*
* <pre>
* 公共请求对象
* </pre>
*
* @author as-shibaobao
* @version $Id: CommonRequest.java, v 0.1 2018年1月26日 上午10:59:19 as-shibaobao Exp $
*/
@ApiModel
public class CommonRequest {
/**
* 字段名称
*/
@ApiModelProperty(value="字段名称",required=true)
private String name;
/**
* 字段值
*/
@ApiModelProperty(value="字段值",required=true)
private Object value;
/**
* 查询类型
*/
@ApiModelProperty(value="查询类型",notes="空值时,默认为等于;其它类型按QueryOperatorEnum",required=false)
private String type;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Object getValue() {
return value;
}
public void setValue(Object value) {
this.value = value;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
package com.yeejoin.amos.latentdanger.core.common.request;
import java.util.List;
/**
* @author DELL
*/
public class LatentDangerResultPushSpcRequest {
/**
* 隐患状态
*/
private String hiddenTroubleStatus;
/**
* 处理时间
*/
private String processingTime;
/**
* 隐患名称
*/
private String hiddenTroubleName;
/**
* 风险点id
*/
private String riskSourceId;
/**
* 所有隐患的状态集合
*/
private List<String> troubleList;
public String getHiddenTroubleStatus() {
return hiddenTroubleStatus;
}
public void setHiddenTroubleStatus(String hiddenTroubleStatus) {
this.hiddenTroubleStatus = hiddenTroubleStatus;
}
public String getProcessingTime() {
return processingTime;
}
public void setProcessingTime(String processingTime) {
this.processingTime = processingTime;
}
public String getHiddenTroubleName() {
return hiddenTroubleName;
}
public void setHiddenTroubleName(String hiddenTroubleName) {
this.hiddenTroubleName = hiddenTroubleName;
}
public String getRiskSourceId() {
return riskSourceId;
}
public void setRiskSourceId(String riskSourceId) {
this.riskSourceId = riskSourceId;
}
public List<String> getTroubleList() {
return troubleList;
}
public void setTroubleList(List<String> troubleList) {
this.troubleList = troubleList;
}
}
package com.yeejoin.amos.patrol.core.common.request;
/**
* 线路巡检点巡检项查询条件
* @author Administrator
*
*/
public class RoutePointInputItemRequest {
/**
* 巡检点id
*/
private Long pointId;
/**
* 是否绑定
*/
private String isBound;
/**
* 路线id
*/
private Long routeId;
/**
* 分类id
*/
private Long classifyId;
/**
* 巡检项等级
*/
private String level;
/**
* 巡检项名称
*/
private String inputName;
public Long getPointId() {
return pointId;
}
public void setPointId(Long pointId) {
this.pointId = pointId;
}
public Long getRouteId() {
return routeId;
}
public void setRouteId(Long routeId) {
this.routeId = routeId;
}
public Long getClassifyId() {
return classifyId;
}
public void setClassifyId(Long classifyId) {
this.classifyId = classifyId;
}
public String getLevel() {
return level;
}
public void setLevel(String level) {
this.level = level;
}
public String getInputName() {
return inputName;
}
public void setInputName(String inputName) {
this.inputName = inputName;
}
public String getIsBound() {
return isBound;
}
public void setIsBound(String isBound) {
this.isBound = isBound;
}
}
/**
* NewHeight.com Inc.
* Copyright (c) 2008-2010 All Rights Reserved.
*/
package com.yeejoin.amos.patrol.core.common.response;
import java.util.List;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
/**
* <pre>
* 分页数据
* </pre>
*
* @author as-youjun
* @version $Id: CompanyPage.java, v 0.1 2017年4月13日 上午11:35:25 as-youjun Exp $
*/
public final class CommonPage<T> extends PageImpl<T> {
/**
* <pre>
* uid
* </pre>
*/
private static final long serialVersionUID = -5533124806408380886L;
/**
*
*/
private String message;
/**
* 返回结果状态
*/
private String result;
public CommonPage(List<T> content, Pageable pageable, long total) {
super(content, pageable, total);
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getResult()
{
return result;
}
public void setResult(String result)
{
this.result = result;
}
}
package com.yeejoin.amos.latentdanger.core.common.response;
import cn.afterturn.easypoi.excel.annotation.Excel;
import lombok.Data;
import java.util.Date;
@Data
public class DangerListResponse {
/**
* 隐患id
*/
private Long dangerId;
@Excel(name = "治理进度", orderNum = "1")
private String dangerState;// 治理进度
@Excel(name = "隐患名称", width = 20, orderNum = "2")
private String dangerName;// 隐患名称
@Excel(name = "隐患地点", width = 20, orderNum = "3")
private String structureName;// 隐患地点
private String dangerPosition;// 详细地址
private String structureId;// 建筑Id
@Excel(name = "隐患级别", orderNum = "4")
private String dangerLevel;// 隐患级别
@Excel(name = "治理方式", orderNum = "5")
private String reformType;// 治理方式
private Date deadlineDate;
@Excel(name = "整改期限", width = 20, orderNum = "6")
private String deadline;// 整改期限
@Excel(name = "是否逾期", orderNum = "7")
private String overtimeState;// 是否逾期
@Excel(name = "隐患来源名称", width = 15, orderNum = "8")
private String dangerTypeName;//隐患来源名称
private String dangerType;//隐患来源
/**
* 隐患流程id
*/
private String processInstanceId;
/**
* 可执行人
*/
private String canExecuteUser;
/**
* 隐患发现人
*/
private String discoverUser;
/**
* 执行人
*/
private String executeUser;
/**
* 问题描述
*/
@Excel(name = "问题描述", width = 35, orderNum = "9")
private String problemDescription;
/**
* 原因分析
*/
@Excel(name = "原因分析", width = 35, orderNum = "10")
private String reasonAnalysis;
/**
* 举一反三
*/
@Excel(name = "举一反三", width = 35, orderNum = "11")
private String inferOtherThings;
/**
* 备注
*/
@Excel(name = "备注", width = 35, orderNum = "12")
private String remark;
}
package com.yeejoin.amos.latentdanger.core.common.response;
import lombok.Data;
@Data
public class WebStockResponse {
/**
* 消息类型
*/
private String type;
/**
* 内容
*/
private String content;
}
package com.yeejoin.amos.latentdanger.dao.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import lombok.Data;
import org.springframework.data.annotation.CreatedDate;
import javax.persistence.Column;
import javax.persistence.Id;
import java.io.Serializable;
import java.util.Date;
/**
* <pre>
* 基本实体类
* </pre>
* @author DELL
*/
@Data
public class BasicEntity implements Serializable {
private static final long serialVersionUID = -5464322936854328207L;
/**
* id
*/
@TableId(type = IdType.ID_WORKER)
private Long id;
// @CreatedDate
@Column(name = "create_date")
private Date createDate;
// @Id
// @GeneratedValue(strategy = GenerationType.IDENTITY)
// @Column(name = "ID", nullable = false, unique = true)
// public long getId() {
// return id;
// }
//
// public void setId(long id) {
// this.id = id;
// }
public Date getCreateDate() {
return createDate;
}
public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
}
package com.yeejoin.amos.latentdanger.dao.entity;
import com.baomidou.mybatisplus.annotation.TableName;
import io.swagger.annotations.ApiModel;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
import org.hibernate.annotations.Where;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import java.util.Date;
/**
* @author keyong
* @title: LatentDanger
* <pre>
* @description: 隐患表
* </pre>
* @date 2021/1/26 14:03
*/
@Data
@EqualsAndHashCode(callSuper = true)
@Accessors(chain = true)
@TableName("cb_latent_danger")
@ApiModel(value="LatentDanger", description="隐患信息")
public class LatentDanger extends BasicEntity {
private static final long serialVersionUID = 1L;
/**
* 业务唯一标识
*/
@Column(name = "business_key")
private String businessKey;
/**
* 公司组织机构
*/
@Column(name = "org_code")
private String orgCode;
/**
* 隐患名称
*/
@Column(name = "danger_name")
private String dangerName;
@Column(name = "instance_id")
private String instanceId;
@Column(name = "current_flow_record_id")
private Long currentFlowRecordId;
/**
* 隐患等级(1:一般隐患;2:重大隐患;0:安全问题)
*/
@Column(name = "danger_level")
private String dangerLevel;
/**
* 隐患等级名称
*/
@Column(name = "danger_level_name")
private String dangerLevelName;
/**
* 隐患地点
*/
@Column(name = "danger_position")
private String dangerPosition;
/**
* 隐患类型(1:普通隐患;2:巡检隐患)
*/
@Column(name = "danger_type")
private String dangerType;
/**
* 隐患类型名称
*/
@Column(name = "danger_type_name")
private String dangerTypeName;
/**
* 备注
*/
@Column(name = "remark")
private String remark;
/**
* 整改类型(1:常规整改;2:安措计划;3:延期整改)
*/
@Column(name = "reform_type")
private String reformType;
/**
* 整改类型名称
*/
@Column(name = "reform_type_name")
private String reformTypeName;
/**
* 限制时间
*/
@Column(name = "reform_limit_date")
private Date reformLimitDate;
@Column(name = "overtime_state")
private Integer overtimeState;
@Column(name = "reform_json")
private String reformJson;
/**
* 隐患状态(1:待评审;2:待治理;3:安措计划中;4:逾期未治理;5:待验证;6:治理完毕;7:已撤销)
*/
@Column(name = "danger_state")
private String dangerState;
/**
* 隐患状态名称
*/
@Column(name = "danger_state_name")
private String dangerStateName;
/**
* 发现人
*/
@Column(name = "discoverer_user_id")
private String discovererUserId;
@Column(name = "discoverer_department_id")
private String discovererDepartmentId;
@Column(name = "photo_urls")
private String photoUrls;
/**
* 是否删除(0:否;1:是)
*/
@Column(name = "deleted")
private Boolean deleted;
/**
* 记录修改时间
*/
@Column(name = "update_date")
private Date updateDate;
/**
* 延期治理时间
*/
@Column(name = "delay_limit_date")
private Date delayLimitDate;
/**
* 问题描述
*/
@Column(name = "problem_description")
private String problemDescription;
/**
* 原因分析
*/
@Column(name = "reason_analysis")
private String reasonAnalysis;
/**
* 举一反三
*/
@Column(name = "infer_other_things")
private String inferOtherThings;
/**
* 检查记录创建的隐患检查项对应id
*/
@Column(name = "biz_id")
private Long bizId;
/**
* 建筑id
*/
@Column(name = "structure_id")
private Long structureId;
/**
* 建筑名称
*/
@Column(name = "structure_name")
private String structureName;
@Column(name = "instance_key")
private String instanceKey;
/**
* 业务类型(不同业务创建的隐患以此区分:巡检隐患、防火监督隐患、其他隐患。。。)
*/
@Column(name = "biz_type")
private String bizType;
/**
* 经度
*/
private String longitude;
/**
* 纬度
*/
private String latitude;
}
package com.yeejoin.amos.latentdanger.dao.entity;
import com.baomidou.mybatisplus.annotation.TableName;
import io.swagger.annotations.ApiModel;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
import org.hibernate.annotations.Where;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import java.util.Date;
/**
* @author keyong
* @title: LatentDangerFlowRecord
* <pre>
* @description: 隐患工作流记录表
* </pre>
* @date 2021/1/26 14:18
*/
@Data
@EqualsAndHashCode(callSuper = true)
@Accessors(chain = true)
@TableName("cb_latent_danger_flow_record")
@ApiModel(value="LatentDangerFlowRecord", description="隐患工作流记录信息")
public class LatentDangerFlowRecord extends BasicEntity {
private static final long serialVersionUID = 1L;
@Column(name = "danger_id")
private Long dangerId;
@Column(name = "action_flag")
private String actionFlag;
@Column(name = "flow_task_name")
private String flowTaskName;
@Column(name = "flow_task_user_ids")
private String flowTaskUserIds;
@Column(name = "flow_task_id")
private String flowTaskId;
@Column(name = "execute_state")
private Integer executeState;
@Column(name = "execute_user_id")
private String executeUserId;
@Column(name = "execute_result")
private String executeResult;
@Column(name = "remark")
private String remark;
@Column(name = "flow_json")
private String flowJson;
/**
* 是否删除(0:否;1:是)
*/
@Column(name = "deleted")
private Boolean deleted = false;
/**
* 记录修改时间
*/
@Column(name = "update_date")
private Date updateDate;
@Column(name = "execute_department_id")
private String executeDepartmentId;
}
package com.yeejoin.amos.latentdanger.dao.entity;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import org.hibernate.annotations.Where;
import org.springframework.data.annotation.Transient;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import java.util.Date;
/**
* @author keyong
* @title: LatentDangerPatrol
* <pre>
* @description: 隐患巡检关系表
* </pre>
* @date 2021/1/26 14:51
*/
@TableName("cb_latent_danger_patrol")
@Data
public class LatentDangerPatrol extends BasicEntity {
private static final long serialVersionUID = 1L;
@Column(name = "latent_danger_id")
private Long latentDangerId;
@Column(name = "point_classify_id")
private Long pointClassifyId;
@Column(name = "check_id")
private Long checkId;
@Column(name = "item_id")
private Long itemId;
@Column(name = "point_id")
private Long pointId;
@Column(name = "route_id")
private Long routeId;
@Column(name = "risk_factor_flow_id")
private String riskFactorFlowId;
@Column(name = "route_point_item_id")
private Long routePointItemId;
/**
* 是否删除(0:否;1:是)
*/
@Column(name = "deleted")
private Integer deleted;
/**
* 检查类型-交大字段,只是前段显示用
*/
@Transient
private String checkType;
/**
* 记录修改时间
*/
@Column(name = "update_date")
private Date updateDate;
}
package com.yeejoin.amos.latentdanger.dao.entity;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import org.hibernate.annotations.Where;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
/**
* @author keyong
* @title: LatentDangerPhoto
* <pre>
* @description: 隐患图片
* </pre>
* @date 2021/1/26 14:50
*/
@TableName("cb_latent_danger_photo")
@Data
public class LatentDangerPhoto extends BasicEntity {
private static final long serialVersionUID = 1L;
@Column(name = "biz_code")
private String bizCode;
@Column(name = "url")
private String url;
@Column(name = "biz_id")
private Long bizId;
@Column(name = "deleted")
private String deleted;
@Column(name = "update_date")
private String updateDate;
}
package com.yeejoin.amos.latentdanger.dao.entity;
import com.baomidou.mybatisplus.annotation.TableName;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Lob;
import javax.persistence.Table;
import javax.persistence.Transient;
import java.util.Date;
/**
* 消息
*
* @author Administrator
*/
@TableName("p_msg")
public class Msg extends BasicEntity {
/**
*
*/
private static final long serialVersionUID = 1L;
/**
* 标题
*/
@Column(name = "title")
private String title;
/**
* 消息
*/
@Lob
@Column(name = "body")
private String body;
private String pushBody;
/**
* 接收人名称
*/
@Column(name = "reciver_name")
private String reciverName;
/**
* 接收人ID
*/
@Column(name = "user_id")
private String userId;
/**
* 消息类型:对应MsgTypeEnum类,
*/
@Column(name = "msg_type")
private String msgType;
/**
* 发送状态0:未发送;1:已发送
*/
@Column(name = "status")
private int status = 1;
/**
* 发送时间
*/
@Column(name = "send_time")
private Date sendTime;
/**
* 关联id:巡检点;任务;计划
*/
@Column(name = "relation_id")
private Long relationId;
/**
* 发送方式true 按用户设置时间发送(主要针对任务提醒和消息发送),false 定时器发送
*/
@Column(name = "is_immediately")
private boolean isImmediately = true;
/**
* 定点发送时间
*/
@Column(name = "fixed_time")
private Date fixedTime;
/**
* 组织机构
*/
@Column(name = "org_code")
private String orgCode;
/**
* 是否已读
*/
@Column(name = "is_read")
private boolean isRead = false;
/**
* 接收消息电话号码
*/
@Column(name = "target_tel")
private String targetTel;
/**
* 创建者
*/
@Column(name = "create_by")
private Long createBy;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
public String getMsgType() {
return msgType;
}
public void setMsgType(String msgType) {
this.msgType = msgType;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public Date getSendTime() {
return sendTime;
}
public void setSendTime(Date sendTime) {
this.sendTime = sendTime;
}
public Long getRelationId() {
return relationId;
}
public void setRelationId(Long relationId) {
this.relationId = relationId;
}
public boolean getIsImmediately() {
return isImmediately;
}
public void setIsImmediately(boolean isImmediately) {
this.isImmediately = isImmediately;
}
public Date getFixedTime() {
return fixedTime;
}
public void setFixedTime(Date fixedTime) {
this.fixedTime = fixedTime;
}
public String getOrgCode() {
return orgCode;
}
public void setOrgCode(String orgCode) {
this.orgCode = orgCode;
}
public boolean getIsRead() {
return isRead;
}
public void setIsRead(boolean isRead) {
this.isRead = isRead;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getTargetTel() {
return targetTel;
}
public void setTargetTel(String targetTel) {
this.targetTel = targetTel;
}
public Long getCreateBy() {
return createBy;
}
public void setCreateBy(Long createBy) {
this.createBy = createBy;
}
@Transient
public String getPushBody() {
return pushBody;
}
public void setPushBody(String pushBody) {
this.pushBody = pushBody;
}
public String getReciverName() {
return reciverName;
}
public void setReciverName(String reciverName) {
this.reciverName = reciverName;
}
}
package com.yeejoin.amos.latentdanger.dao.entity;
import com.baomidou.mybatisplus.annotation.TableName;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
/**
* 消息订阅设置实体
*
* @author gaodongdong
*/
@TableName("p_msg_subscribe")
public class MsgSubscribe extends BasicEntity {
/**
*
*/
private static final long serialVersionUID = -3679029984718140789L;
@Column(name = "org_code")
private String orgCode; // 公司ID
@Column(name = "user_id")
private String userId; // 用户ID
@Column(name = "msg_type")
private String msgType; // 消息类型
@Column(name = "attribute1")
private String attribute1; // 消息属性
@Column(name = "attribute2")
private String attribute2;
@Column(name = "attribute3")
private String attribute3;
@Column(name = "attribute4")
private String attribute4;
@Column(name = "attribute5")
private String attribute5;
public String getOrgCode() {
return orgCode;
}
public void setOrgCode(String orgCode) {
this.orgCode = orgCode;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getMsgType() {
return msgType;
}
public void setMsgType(String msgType) {
this.msgType = msgType;
}
public String getAttribute1() {
return attribute1;
}
public void setAttribute1(String attribute1) {
this.attribute1 = attribute1;
}
public String getAttribute2() {
return attribute2;
}
public void setAttribute2(String attribute2) {
this.attribute2 = attribute2;
}
public String getAttribute3() {
return attribute3;
}
public void setAttribute3(String attribute3) {
this.attribute3 = attribute3;
}
public String getAttribute4() {
return attribute4;
}
public void setAttribute4(String attribute4) {
this.attribute4 = attribute4;
}
public String getAttribute5() {
return attribute5;
}
public void setAttribute5(String attribute5) {
this.attribute5 = attribute5;
}
}
<?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>
<artifactId>amos-boot-module-biz</artifactId>
<groupId>com.amosframework.boot</groupId>
<version>1.0.0</version>
</parent>
<artifactId>amos-boot-module-latentdanger-biz</artifactId>
<dependencies>
<dependency>
<groupId>com.amosframework.boot</groupId>
<artifactId>amos-boot-module-latentdanger-api</artifactId>
<version>${amos-biz-boot.version}</version>
</dependency>
<dependency>
<groupId>com.amosframework.boot</groupId>
<artifactId>amos-boot-module-common-api</artifactId>
<version>${amos-biz-boot.version}</version>
</dependency>
<dependency>
<groupId>com.yeejoin</groupId>
<artifactId>amos-component-rule</artifactId>
<exclusions>
<exclusion>
<groupId>org.typroject</groupId>
<artifactId>tyboot-core-auth</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
<exclusions>
<exclusion>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-jdbc</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- 添加fastjson 依赖包. -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.15</version>
</dependency>
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/com.google.zxing/core -->
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.3.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.google.zxing/javase -->
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.3.0</version>
</dependency>
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
<classifier>jdk15</classifier>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>3.11.1</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-scratchpad</artifactId>
<version>3.15</version>
</dependency>
<dependency>
<groupId>fr.opensagres.xdocreport</groupId>
<artifactId>xdocreport</artifactId>
<version>1.0.6</version>
</dependency>
<dependency>
<groupId>org.apache.tika</groupId>
<artifactId>tika-core</artifactId>
<version>1.13</version>
</dependency>
<dependency>
<groupId>org.apache.tika</groupId>
<artifactId>tika-parsers</artifactId>
<version>1.13</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<dependency>
<groupId>cn.jpush.api</groupId>
<artifactId>jpush-client</artifactId>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.5.1</version>
</dependency>
<dependency>
<groupId>org.liquibase</groupId>
<artifactId>liquibase-core</artifactId>
</dependency>
</dependencies>
</project>
/**
*
*/
package com.yeejoin.amos.latentdanger.business.constants;
import org.slf4j.LoggerFactory;
/**
* 常量
* @author DELL
*/
public class Constants {
public static final String CHECK_TYPE = "CHECK_TYPE";
public static final String DANGER_BIZ_TYPE_KEY= "danger_biz_type_key";
/**
* 构造方法
*/
private Constants() {
LoggerFactory.getLogger(this.getClass()).debug(Constants.CONSTRUCTOR);
}
/**
* 请求头key
*/
public static final String TOKEN_KEY = "token";
/**
* 请求头key
*/
public static final String PRODUCT = "product";
/**
* 请求头key
*/
public static final String APPKEY = "appKey";
/**
* 构造方法字符串
*/
public static final String CONSTRUCTOR = "constructor...";
/**
* amos线程池数量
*/
public static final int AMOS_THREAD_NUM = 20;
/**
* bar
*/
public static final String BAR = "-";
/**
* Underline
*/
public static final String UNDERLINE = "_";
/**
* user
*/
public static final String USER = "user";
/**
* token
*/
public static final String TOKEN = "token";
/**
* loginType
*/
public static final String LOGIN_TYPE = "loginType";
/**
* subGraphId
*/
public static final String SUB_GRAPH_ID = "subGraphId";
public static final String ADMIN_ID = "1";
/**
* 帧报文异常
*/
public static final String FRAME_EXECPTION = "FRAME";
/**
* 性能指标
*/
public static final String METRIC = "METRIC";
/**
* 报文通道
*/
public static final String CHANNEL = "CHANNEL";
/**
* 设备状态(掉线)告警
*/
public static final String EQUIPMENT_STATUS = "EQUIPMENT_STATUS";
/**
* 设备连通性告警告警
*/
public static final String EQUIPMENT_CONNECTION = "EQUIPMENT_CONNECTION";
/**
* 通道注册
*/
public static final String REGISTER = "REGISTER";
/**
* 通道注销
*/
public static final String UNREGISTER = "UNREGISTER";
/**
* 报文正常
*/
public static final String NORMAL = "NORMAL";
/**
* 报文异常
*/
public static final String UNNORMAL = "UNNORMAL";
/**
* 告警socket类型
*/
public static final String ALARM_SOCKET = "ALARM_SOCKET";
/**
* 数据socket类型
*/
public static final String METRIC_SOCKET = "METRIC_SOCKET";
/**
* 数据socket类型
*/
public static final String MORPHIC_SOCKET = "MORPHIC_SOCKET";
/**
* false
*/
public static final Boolean FAIL_BOOLEAN_VALUE = Boolean.FALSE;
/**
* 0
*/
public static final Integer ZERO_INT_VALUE = Integer.parseInt("0");
/**
* -1
*/
public static final Integer FAIL_INT_VALUE = Integer.parseInt("-1");
/**
* -1
*/
public static final Long FAIL_LONG_VALUE = Long.parseLong("-1");
/**
* -1
*/
public static final Short FAIL_SHORT_VALUE = Short.parseShort("-1");
/**
*
*/
public static final Float FAIL_FLOAT_VALUE = Float.parseFloat("-1");
/**
* -1
*/
public static final Double FAIL_DOUBLE_VALUE = Double.parseDouble("-1");
/**
* 空格
*/
public static final Character FAIL_CHARACTER_VALUE = Character.valueOf(' ');
/**
* 失败
*/
public static final int FAILURE = 0;
/**
* 成功
*/
public static final int SUCCESS = 1;
/**
* 在线
*/
public static final String ONLINE = "在线";
/**
* 掉线
*/
public static final String OFFLINE = "掉线";
/**
* 通
*/
public static final String OPEN = "通";
/**
* 不通
*/
public static final String OFF = "不通";
/**
* ip
*/
public static final String IP = "ip";
/**
* #
*/
public static final String SHARP = "#";
/**
* TCP
*/
public static final String TCP = "TCP";
public static final String PIE_CHAR = "pieChar";
public static final String BAR_CHAR = "barChar";
public static final String HBAR_CHAR = "hbarChar";
public static final String LINE_CHAR = "lineChar";
public static final String DOUGHUNT_CHAR = "doughuntChar";
public static final String ROSE_CHAR = "roseChar";
public static final String AREA_CHAR = "areaChar";
public static final String DIMENSION = "dimension";
public static final String MEASURE = "measure";
/**
* xunjian
*/
public static final String TABLE_USERS = "Users";
public static final String EDIT_PWD = "editPassword";
public static final String EDIT_NOT_PWD = "editUsersInfo";
public static final String SAVE_USERS = "saveTableById";
public static final String SAVE_COM_USER = "saveComUserInfo";
public static final String EDIT_COM_USER = "editComUserInfo";
public static final String TABLE_CHECK = "Check";
public static final String TABLE_COM_USER = "companyUser";
public static final int FINISH_YES = 2;
public static final int FINISH_ING = 1;
public static final int FINISH_NO = 0;
public static final String SAVE_DEPART = "saveDepartMent";
public static final String EDIT_DEPART = "editsDepartMent";
public static final String TABLE_DEPART = "Group";
public static final String TABLE_ERROR = "Error";//隐患表
public static final String SAVE_ERROR = "saveErrorByID";//更新隐患表
public static final int XJ_ADMIN_ROLE = 9;//巡检管理员角色ID
public static final int XJ_USER_ROLE = 0;//巡检普通用户角色ID
public static final int TASK_STATUS_TIMEOUT = 3;//已超时
public static final int TASK_STATUS_FINISH = 2;//已结束
public static final int TASK_STATUS_DEAL = 1;//进行中
public static final int TASK_STATUS_NO_START = 0;//未开始
public static final String PLAN_TASK_DET_FINISH_NO = "0";//任务明细状态:未完成
public static final String PLAN_TASK_DET_FINISH_YES = "1";//任务明细状态:完成
public static final String PLAN_TASK_DET_FINISH_OUT = "2";//任务明细状态:超时漏检
public static final String USER_DATA_ADMIN = "全部可见"; //用户数据可见范围
public static final String USER_DATA_DEPART = "部门可见"; //用户数据可见范围
public static final String USER_DATA_PERSON = "个人可见"; //用户数据可见范围
public static final String USER_ROLE_SUPERADMIN = "1"; //权限id-超级管理员
public static final String USER_ROLE_ADMIN = "2"; //权限id-管理员
public static final String USER_ROLE_DEPART = "3"; //权限id-部门管理
public static final String USER_ROLE_PERSON = "4"; //权限id-普通用户
public static final String ROLE_NAME_SUPERADMIN = "SUPERADMIN"; //数据权限-超级管理员
public static final String ROLE_NAME_ADMIN = "ADMIN"; //数据权限-超级管理员
public static final String ROLE_NAME_DEPTADMIN = "DEPTADMIN"; //数据权限-部门
public static final String ROLE_NAME_PERSON = "PERSONAL"; //数据权限-个人
public static final String ADMIN_FLAG = "2"; //权限标记
public static final String DEPART_FLAG = "1"; //权限标记
public static final String PERSON_FLAG = "0";//权限标记
public static final String ADMIN_FLAG_NO = "0"; //标记 0-无关
public static final String ADMIN_FLAG_UP = "1"; //1-上级admin
public static final String ADMIN_FLAG_THIS = "2"; //2-本级admin
public static final String UNCLASSIFIED = "Unclassifed"; //巡检点未分类
public static final String ADMIN_ORG_CODE = "2";
public static final String CHECK_CHANGE_NO = "0";//是否记为合格:否
public static final String CHECK_CHANGE_YES = "1";//是否记为合格:是
public static final String SCHED_FLAG = "99";//自动任务标记
public static final String REGEN_FLAG = "98";//重做任务标记
public static final String FIX_DATE_NO = "0";//不固定日期(区间)
public static final String FIX_DATE_YES = "1";//固定日期
//计划类型
public static final String PLAN_TYPE_DAY = "1";//日计划
public static final String PLAN_TYPE_WEEK = "2";//周计划
public static final String PLAN_TYPE_MONTH = "3";//月计划
public static final String PLAN_TYPE_YEAR = "4";//年计划
//月类型
public static final String MONTH_TYPE_DAY = "1";//第几天
public static final String MONTH_TYPE_AT = "2";//在第几周的第几天
public static final String INTERVAL_UNIT_HOUR = "1";//执行间隔小时
public static final String INTERVAL_UNIT_MINUTE = "2";//执行间隔分钟
public static final String INTERVAL_UNIT_SECOND = "3";//执行间隔秒
public static final String ZERO_TIME = "00:00:00";//time
public static final String PLAN_STATUS_START = "0";//计划状态:正常
public static final String PLAN_STATUS_STOP = "1";//计划状态:已停用
public static final int PLAN_FIRST_STATUS_YES = 0;//计划:初始状态
public static final int PLAN_FIRST_STATUS_NO = 1;//计划:非初始状态
public static final String UPD_PLAN_GEN_DATE = "1";//更新plan表日期
public static final String UPD_PLAN_STATUS = "2";//更新plan表next_gen_status
public static final int DAY_RATE_ONE = 0;//0-1次
public static final int DAY_RATE_MANY = 1;//1-多次
public static final int IS_DETETE_NO = 0;//未删除
public static final int IS_DETETE_YES = 1;//删除
public static final String UPLOAD_ROOT_PATH = "upload";
public static final String INPUT_ITEM_TEXT = "文本";
public static final String INPUT_ITEM_NUMBER = "数字";
public static final String INPUT_ITEM_SELECT = "选择";
public static final String CHECK_TYPE_ALWAYS_OK = "始终合格";
public static final String CHECK_TYPE_ALWAYS_NO = "始终不合格";
public static final String CHECK_TYPE_NO_CONTEXT_OK = "无内容合格";
public static final String CHECK_TYPE_CONTEXT_OK = "有内容合格";
public static final String OK = "合格";
public static final String NO = "不合格";
public static final String YES = "是";
public static final String NOT = "否";
public static final String INPUT_ITEM_OK_SCORE = "OkScore";
public static final String INPUT_ITEM_NOT_SCORE = "NoScore";
public static final String POINT_OK_SCORE = "1";
public static final String POINT_NOT_SCORE = "0";
/**
* 任务是否发送消息状态
*/
public static final String TASK_WARN = "是";
public static final String TASK_NOT_WARN = "否";
/**
* 系统定时任务类型
*/
public static final String STATUS_MONITOR_START = "statusMonitorStart"; //状态监控是否开始
public static final String STATUS_MONITOR_END = "statusMonitorEnd"; //状态监控是否结束
public static final String PLAN_TASK_WARN_MSG_PUSH = "planTaskWarnMsgPush"; //计划即将开始消息提醒推送
public static final String PLAN_TASK_BEGIN_MSG_PUSH = "planTaskBeginMsgPush"; //计划已经开始消息提醒推送
public static final String PLAN_TASK_END_MSG_PUSH = "planTaskEndMsgPush"; //计划已经开始消息提醒推送
public static final String MESSAGE_PUSH = "messagePush"; //消息推送
public static final int IS_SENT = 1; //已发送
public static final int NOT_SENT = 0; //未发送
public static final String IS_FIXED_YES = "1"; //固定点
}
package com.yeejoin.amos.latentdanger.business.controller;
import com.alibaba.fastjson.JSONObject;
import com.yeejoin.amos.boot.biz.common.bo.ReginParams;
import com.yeejoin.amos.boot.biz.common.bo.RoleBo;
import com.yeejoin.amos.boot.biz.common.controller.BaseController;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;
import com.yeejoin.amos.latentdanger.business.dto.DangerExecuteSubmitDto;
import com.yeejoin.amos.latentdanger.business.param.LatentDangerDto;
import com.yeejoin.amos.latentdanger.business.param.LatentDangerExecuteParam;
import com.yeejoin.amos.latentdanger.business.param.LatentDangerListParam;
import com.yeejoin.amos.latentdanger.business.param.LatentDangerNormalParam;
import com.yeejoin.amos.latentdanger.business.param.PageParam;
import com.yeejoin.amos.latentdanger.business.service.intfc.ILatentDangerService;
import com.yeejoin.amos.latentdanger.business.util.CommonResponse;
import com.yeejoin.amos.latentdanger.business.util.CommonResponseUtil;
import com.yeejoin.amos.latentdanger.business.util.FileHelper;
import com.yeejoin.amos.latentdanger.business.vo.DangerTimeAxisVo;
import com.yeejoin.amos.latentdanger.core.common.response.DangerListResponse;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang.StringUtils;
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.ObjectUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.typroject.tyboot.core.foundation.enumeration.UserType;
import org.typroject.tyboot.core.restful.doc.TycloudOperation;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;
/**
* @author DELL
*/
@RestController
@RequestMapping(value = "/api/latent/danger")
@Api(tags = "隐患接口api")
public class LatentDangerController extends BaseController {
private final Logger logger = LoggerFactory.getLogger(LatentDangerController.class);
@Autowired
private ILatentDangerService iLatentDangerService;
@ApiOperation(value = "创建无码无计划隐患", notes = "创建无码无计划隐患")
@PostMapping(value = "/normal/save")
@TycloudOperation(ApiLevel = UserType.AGENCY)
public CommonResponse saveNormal(@ApiParam(value = "隐患对象", required = true) @RequestBody LatentDangerNormalParam latentDangerParam) {
try {
AgencyUserModel user = getUserInfo();
if (ObjectUtils.isEmpty(user)) {
return CommonResponseUtil.failure("登录过期,请重新登录");
}
ReginParams reginParams = getSelectedOrgInfo();
String loginOrgCode = getOrgCode(reginParams);
String deptId = getDepartmentId(reginParams);
String companyId = getCompanyId(reginParams);
String departmentName = getDepartmentName(reginParams);
RoleBo role = reginParams.getRole();
return iLatentDangerService.saveNormal(latentDangerParam, user.getUserId(),
user.getRealName(), deptId, departmentName, companyId, loginOrgCode, role);
} catch (Exception e) {
logger.error("创建普通隐患异常", e.getMessage());
return CommonResponseUtil.failure("系统繁忙,请稍后再试");
}
}
@ApiOperation(value = "创建巡检隐患", notes = "创建巡检隐患")
@PostMapping(value = "/patrol/save")
@TycloudOperation(ApiLevel = UserType.AGENCY)
public CommonResponse savePatrol(@ApiParam(value = "隐患对象", required = true) @RequestBody List<LatentDangerDto> latentDangerDtoList) {
try {
AgencyUserModel user = getUserInfo();
if (ObjectUtils.isEmpty(user)) {
return CommonResponseUtil.failure("登录过期,请重新登录");
}
ReginParams reginParams = getSelectedOrgInfo();
String loginOrgCode = getOrgCode(reginParams);
String deptId = getDepartmentId(reginParams);
String companyId = getCompanyId(reginParams);
String departmentName = getDepartmentName(reginParams);
RoleBo role = reginParams.getRole();
return iLatentDangerService.savePatrol(latentDangerDtoList, user.getUserId(),
user.getRealName(), deptId, departmentName, companyId, loginOrgCode, role);
} catch (Exception e) {
logger.error("创建巡检隐患异常", e.getMessage());
return CommonResponseUtil.failure("系统繁忙,请稍后再试");
}
}
@ApiOperation(value = "隐患列表", notes = "隐患列表")
@PostMapping(value = "/list")
@TycloudOperation(ApiLevel = UserType.AGENCY)
public CommonResponse list(@ApiParam(value = "隐患对象", required = true) @RequestBody LatentDangerListParam latentDangerListParam) {
Date startDate = new Date();
try {
AgencyUserModel user = getUserInfo();
if (ObjectUtils.isEmpty(user)) {
return CommonResponseUtil.failure("登录过期,请重新登录");
}
ReginParams reginParams = getSelectedOrgInfo();
String loginOrgCode = getOrgCode(reginParams);
return iLatentDangerService.list(getToken(), getProduct(), getAppKey(), latentDangerListParam, user,
loginOrgCode, null);
} catch (Exception e) {
logger.error("隐患列表异常", e.getMessage());
return CommonResponseUtil.failure("系统繁忙,请稍后再试");
} finally {
Date endDate = new Date();
logger.info("-------------------------隐患列表时间" + (endDate.getTime() - startDate.getTime()));
}
}
@ApiOperation(value = "隐患详情", notes = "隐患详情")
@GetMapping(value = "/detail")
@TycloudOperation(ApiLevel = UserType.AGENCY)
public CommonResponse detail(@ApiParam(value = "任务Id", required = true) @RequestParam String id,
@ApiParam(value = "是否完成", required = true) @RequestParam boolean isFinish) {
try {
AgencyUserModel user = getUserInfo();
if (ObjectUtils.isEmpty(user)) {
return CommonResponseUtil.failure("登录过期,请重新登录");
}
return iLatentDangerService.detail(id, user.getUserId(), isFinish);
} catch (Exception e) {
logger.error("隐患详情异常", e.getMessage());
return CommonResponseUtil.failure("系统繁忙,请稍后再试");
}
}
@ApiOperation(value = "隐患执行记录", notes = "隐患执行记录")
@GetMapping(value = "/listFlowRecord")
@TycloudOperation(ApiLevel = UserType.AGENCY)
public CommonResponse listFlowRecord(@ApiParam(value = "隐患编号", required = true) @RequestParam Long id) {
try {
AgencyUserModel user = getUserInfo();
if (ObjectUtils.isEmpty(user)) {
return CommonResponseUtil.failure("登录过期,请重新登录");
}
return iLatentDangerService.listFlowRecord(getToken(), getProduct(), getAppKey(), id);
} catch (Exception e) {
logger.error("隐患执行记录异常", e.getMessage());
return CommonResponseUtil.failure("系统繁忙,请稍后再试");
}
}
@ApiOperation(value = "流程执行", notes = "流程执行")
@PostMapping(value = "/excute")
@TycloudOperation(ApiLevel = UserType.AGENCY)
public CommonResponse execute(@ApiParam(value = "隐患对象", required = true) @RequestBody LatentDangerExecuteParam latentDangerExecuteParam) {
try {
AgencyUserModel user = getUserInfo();
if (ObjectUtils.isEmpty(user)) {
return CommonResponseUtil.failure("登录过期,请重新登录");
}
ReginParams reginParams = getSelectedOrgInfo();
String deptId = getDepartmentId(reginParams);
String departmentName = getDepartmentName(reginParams);
String userRealName = user.getRealName();
String userId = user.getUserId();
RoleBo role = reginParams.getRole();
DangerExecuteSubmitDto executeSubmitDto = iLatentDangerService.execute(latentDangerExecuteParam, userId,
userRealName, deptId, departmentName, role);
// iLatentDangerService.freshRiskJudgmentLangerCount(latentDangerExecuteParam);//更新统计
// 执行通过,发送执行结果消息
// if (executeSubmitDto.getIsOk()) {
// if (!StringUtils.isEmpty(executeSubmitDto.getPointOriginalId())) {
// iLatentDangerService.sendLatentDangerExecuteResult(executeSubmitDto);
// }
// return CommonResponseUtil.success();
// } else {
// return CommonResponseUtil.failure(executeSubmitDto.getMsg());
// }
return CommonResponseUtil.success();
} catch (Exception e) {
logger.error("流程执行异常", e.getMessage());
return CommonResponseUtil.failure("系统繁忙,请稍后再试");
}
}
@ApiOperation(value = "根据流程实例编号获取隐患信息", notes = "根据流程实例编号获取隐患信息")
@GetMapping(value = "/getByInstanceId")
@TycloudOperation(ApiLevel = UserType.AGENCY)
public CommonResponse getByInstanceId(@ApiParam(value = "流程实例编号", required = true) @RequestParam String instanceId) {
try {
AgencyUserModel user = getUserInfo();
if (ObjectUtils.isEmpty(user)) {
return CommonResponseUtil.failure("登录过期,请重新登录");
}
return iLatentDangerService.getByInstanceId(instanceId);
} catch (Exception e) {
logger.error("根据流程实例编号获取隐患信息异常", e.getMessage());
return CommonResponseUtil.failure("系统繁忙,请稍后再试");
}
}
@ApiOperation(value = "隐患按错计划流程执行回调", notes = "隐患按错计划流程执行回调")
@PostMapping(value = "/plan/flow/excuteCallBack")
@TycloudOperation(ApiLevel = UserType.AGENCY)
public CommonResponse executeCallBack(@ApiParam(value = "隐患按错计划流程执行回调对象") @RequestBody JSONObject json) {
try {
AgencyUserModel user = getUserInfo();
if (ObjectUtils.isEmpty(user)) {
return CommonResponseUtil.failure("登录过期,请重新登录");
}
String instanceId = json.getString("instanceId");
Integer actionType = json.getInteger("actionType");
String remark = json.getString("remark");
ReginParams reginParams = getSelectedOrgInfo();
String deptId = getDepartmentId(reginParams);
String departmentName = getDepartmentName(reginParams);
DangerExecuteSubmitDto executeSubmitDto = iLatentDangerService.executeCallBack(instanceId, actionType, remark,
getToken(), user.getUserId(), user.getRealName(), deptId, departmentName);
if (executeSubmitDto.getIsOk()) {
if (!StringUtils.isEmpty(executeSubmitDto.getPointOriginalId())) {
iLatentDangerService.sendLatentDangerExecuteResult(executeSubmitDto);
}
return CommonResponseUtil.success();
} else {
return CommonResponseUtil.failure(executeSubmitDto.getMsg());
}
} catch (Exception e) {
logger.error("隐患按错计划流程执行回调异常", e.getMessage());
return CommonResponseUtil.failure("系统繁忙,请稍后再试");
}
}
@ApiOperation(value = "获取隐患等级", notes = "获取隐患等级")
@GetMapping(value = "/dangerLevel")
@TycloudOperation(ApiLevel = UserType.AGENCY)
public CommonResponse getDangerLevel() {
return CommonResponseUtil.success(iLatentDangerService.getDangerLevel());
}
@ApiOperation(value = "获取隐患整改方式", notes = "获取隐患整改方式")
@GetMapping(value = "/danger/governance")
@TycloudOperation(ApiLevel = UserType.AGENCY)
public CommonResponse getDangerGovernance() {
return CommonResponseUtil.success(iLatentDangerService.getDangerGovernance());
}
@ApiOperation(value = "获取隐患评审信息", notes = "获取隐患评审信息")
@GetMapping(value = "/review/info")
public CommonResponse getDangerReviewInfo(@ApiParam(value = "隐患id", required = true) @RequestParam Long dangerId) {
return CommonResponseUtil.success(iLatentDangerService.getReviewInfo(dangerId));
}
/**
* 隐患清单
*/
@ApiOperation(value = "隐患清单", notes = "隐患清单")
@PostMapping(value = "/page/list")
@TycloudOperation(ApiLevel = UserType.AGENCY)
public CommonResponse listDanger(@ApiParam(value = "查询条件", required = true) @RequestBody PageParam pageParam) {
AgencyUserModel user = getUserInfo();
if (ObjectUtils.isEmpty(user)) {
return CommonResponseUtil.failure("登录过期,请重新登录");
}
Page<DangerListResponse> result = iLatentDangerService.listDanger(pageParam);
return CommonResponseUtil.success(result);
}
/**
* 导出隐患清单
*/
@ApiOperation(value = "导出隐患清单", notes = "导出隐患清单")
@PostMapping(value = "/export")
@TycloudOperation(ApiLevel = UserType.AGENCY)
public void exportDangerList(@ApiParam(value = "查询条件") @RequestBody PageParam pageParam,
HttpServletResponse response) {
AgencyUserModel user = getUserInfo();
if (ObjectUtils.isEmpty(user)) {
throw new RuntimeException("登录过期,请重新登录");
}
pageParam.setPageSize(Integer.MAX_VALUE);
List<DangerListResponse> list = iLatentDangerService.export(pageParam);
String fileName = "隐患清单" + System.currentTimeMillis();
FileHelper.exportExcel(list, "隐患清单", "隐患清单", DangerListResponse.class, fileName + ".xls", response);
}
/**
* <pre>
* @Description: 查询隐患日志
* </pre>
*
* @MethodName:
* @Param: [userId, date]
* @Return: CommonResponse
* @Throws
* @Author keyong
* @Date 2021/3/11 11:42
*/
@ApiOperation(value = "隐患日志", notes = "查询隐患节点信息")
@GetMapping(value = "/listDangerTimeAxis")
@TycloudOperation(ApiLevel = UserType.AGENCY)
public CommonResponse listTimeAxis(@ApiParam(value = "时间") @RequestParam(required = false) Integer dateTime) {
AgencyUserModel user = getUserInfo();
if (ObjectUtils.isEmpty(user)) {
throw new RuntimeException("登录过期,请重新登录");
}
try {
List<DangerTimeAxisVo> result = iLatentDangerService.queryExecuteLog(dateTime);
return CommonResponseUtil.success(result);
} catch (Exception e) {
return CommonResponseUtil.failure(e.getMessage());
}
}
}
package com.yeejoin.amos.latentdanger.business.dao.mapper;
import org.apache.ibatis.annotations.Mapper;
/**
* @author DELL
*/
@Mapper
public interface BaseMapper extends com.baomidou.mybatisplus.core.mapper.BaseMapper {
}
package com.yeejoin.amos.latentdanger.business.dao.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.yeejoin.amos.latentdanger.business.entity.mybatis.extend.LatentDangerFlowRecordBo;
import com.yeejoin.amos.latentdanger.business.vo.DangerTimeAxisVo;
import com.yeejoin.amos.latentdanger.dao.entity.LatentDangerFlowRecord;
import org.apache.ibatis.annotations.Param;
import java.util.List;
import java.util.Map;
public interface LatentDangerFlowRecordMapper extends BaseMapper<LatentDangerFlowRecord> {
Integer save(LatentDangerFlowRecordBo latentDangerFlowRecordBo);
LatentDangerFlowRecordBo getByDangerIdAndActionFlag(@Param("dangerId") Long dangerId, @Param("actionFlag") String actionFlag);
LatentDangerFlowRecordBo getByDangerIdAndCreate(@Param("dangerId") Long dangerId);
LatentDangerFlowRecordBo getById(Long id);
List<LatentDangerFlowRecordBo> listPassByDangerId(Long dangerId);
Integer update(LatentDangerFlowRecordBo latentDangerFlowRecordBo);
LatentDangerFlowRecordBo getNewestRecordByDangerId(Long dangerId);
List<LatentDangerFlowRecordBo> listNewestRecordByDangerIds(List<Long> dangerIds);
List<LatentDangerFlowRecordBo> listByDangerId(Long dangerId);
void deleteByLatentDangerIds(List<Long> dangerIds);
List<DangerTimeAxisVo> listExecuteLog(Map<String, Object> map);
LatentDangerFlowRecordBo getByIdOderByDate(Long dangerId);
}
package com.yeejoin.amos.latentdanger.business.dao.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.yeejoin.amos.latentdanger.business.entity.mybatis.extend.LatentDangerBo;
import com.yeejoin.amos.latentdanger.business.entity.mybatis.extend.LatentDangerNoticeBo;
import com.yeejoin.amos.latentdanger.business.param.LatentDangerListParam;
import com.yeejoin.amos.latentdanger.business.param.PageParam;
import com.yeejoin.amos.latentdanger.core.common.response.DangerListResponse;
import com.yeejoin.amos.latentdanger.dao.entity.LatentDanger;
import org.apache.ibatis.annotations.Param;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public interface LatentDangerMapper extends BaseMapper<LatentDanger> {
Integer save(LatentDangerBo latentDangerBo);
List<LatentDangerBo> listByMap(Map<String, Object> map);
Long countByMap(Map<String, Object> map);
LatentDangerBo getById(Long id);
Integer update(LatentDangerBo latentDangerBo);
LatentDangerBo getByInstanceId(String instanceId);
List<LatentDangerBo> listOfOvertime();
Integer countNotFinishByFlowId(String flowId);
List<LatentDangerBo> listNotFinishByPointId(HashMap<String, Object> params);
Long countByFlowUserIds(String userId);
Long countNotFinishByTypeAndDeptId(@Param("type") Integer type, @Param("departmentId") String departmentId);
String getNotFinishIdsByTypeAndDeptId(@Param("type") Integer type, @Param("departmentId") String departmentId);
void deleteByIds(List<Long> dangerIds);
/**
* 查询治理期限即将到期的隐患
*
* @return
*/
List<LatentDangerNoticeBo> listNeedNoticeDanger();
/**
* 根据隐患id获取评审信息
*
* @param dangerId
* @return
*/
List<HashMap<String, Object>> getReViewInfo(Long dangerId);
List<DangerListResponse> dangerListByMap(PageParam pageParam);
Long countDangerListByMap(PageParam pageParam);
List<LatentDangerBo> getByBathBusinessKeys(@Param("businessKeys") List<String> businessKeys, @Param("latentDangerListParam") LatentDangerListParam latentDangerListParam);
int countByBathBusinessKeys(@Param("businessKeys") List<String> businessKeys, @Param("latentDangerListParam") LatentDangerListParam latentDangerListParam);
int countByStatus(@Param("businessKeys") List<String> businessKeys);
void updateCheckInputDangerState(@Param("id") Long id, @Param("code") int code);
LatentDangerBo getbyBusinessKey(@Param("businessKey") String businessKey);
}
package com.yeejoin.amos.latentdanger.business.dao.mapper;
import com.yeejoin.amos.latentdanger.business.entity.mybatis.extend.LatentDangerPatrolBo;
import java.util.List;
import java.util.Map;
public interface LatentDangerPatrolMapper extends BaseMapper {
Integer save(LatentDangerPatrolBo latentDangerPatrolBo);
LatentDangerPatrolBo getByDangerId(Long dangerId);
List<LatentDangerPatrolBo> listByMap(Map<String, Object> map);
List<LatentDangerPatrolBo> listByPointId(Long pointId);
List<LatentDangerPatrolBo> queryByPointClassifyIds(List<String> pointClassifyIds);
void deleteByLatentDangerIds(List<Long> latentDangerIds);
}
package com.yeejoin.amos.latentdanger.business.dao.mapper;
import java.util.List;
import java.util.Map;
import com.yeejoin.amos.latentdanger.business.entity.mybatis.CheckMsgBo;
import com.yeejoin.amos.latentdanger.business.entity.mybatis.PushTargetBo;
import org.apache.ibatis.annotations.Param;
public interface MsgMapper extends BaseMapper{
public List<PushTargetBo> getAppPushTargetBo(@Param(value="userId")String userId, @Param(value="checkType")String checkType,
@Param(value="routeId")Long routeId);
public List<PushTargetBo> getEmailPushTargetBo(@Param(value="userId")String userId, @Param(value="checkEmail")String checkEmail,
@Param(value="routeId")Long routeId);
public List<PushTargetBo> getPushUserBo(@Param(value="type")String type, @Param(value="userIds")String userIds,
@Param(value="routeId")Long routeId, @Param(value="checkType")String checkType);
/**
* 根据巡检id获取巡检详情
* @param checkId
* @return
*/
public CheckMsgBo getCheckMsgBos(@Param(value="checkId")Long checkId);
/**
* 根据巡检记录ID获取对应点和路线的负责人ID
*
* @param checkId
* @return
*/
public Map<String, Object> getChargerId(@Param(value="checkId")Long checkId);
/**
* 根据巡检记录ID获取对应点和路线的负责人ID
*
* @param checkId
* @return
*/
public List getChargerIds(@Param(value="checkId")Long checkId);
}
package com.yeejoin.amos.latentdanger.business.dto;
import com.yeejoin.amos.latentdanger.common.enums.LatentDangerExecuteTypeEnum;
import lombok.Data;
/**
* @author DELL
*/
@Data
public class DangerExecuteSubmitDto extends ExecuteSubmitDto {
private String pointOriginalId;
private Long pointId;
private String dangerName;
private Long dangerId;
private LatentDangerExecuteTypeEnum executeTypeEnum;
}
package com.yeejoin.amos.latentdanger.business.dto;
import lombok.Data;
/**
* @author DELL
*/
@Data
public class ExecuteSubmitDto {
private Boolean isOk;
private String msg;
}
package com.yeejoin.amos.latentdanger.business.entity.mybatis;
public class CheckMsgBo {
/**
* 检查id
*/
private long checkId;
/**
* 执行人
*/
private String userId;
private String name;
private String orgCode;
/**
* 检查状态
*/
private String status;
/**
* 路线id
*/
private long routeId;
/**
* 点id
*/
private long pointId;
/**
* 存储消息内容
*/
private String saveMsg;
/**
* 发送消息内容
*/
private String pushMsg;
/**
* 建筑地址id
*/
private String riskSourceId;
public long getCheckId() {
return checkId;
}
public void setCheckId(long checkId) {
this.checkId = checkId;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public long getRouteId() {
return routeId;
}
public void setRouteId(long routeId) {
this.routeId = routeId;
}
public String getSaveMsg() {
return saveMsg;
}
public void setSaveMsg(String saveMsg) {
this.saveMsg = saveMsg;
}
public String getPushMsg() {
return pushMsg;
}
public void setPushMsg(String pushMsg) {
this.pushMsg = pushMsg;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getOrgCode() {
return orgCode;
}
public void setOrgCode(String orgCode) {
this.orgCode = orgCode;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public long getPointId() {
return pointId;
}
public void setPointId(long pointId) {
this.pointId = pointId;
}
public String getRiskSourceId() {
return riskSourceId;
}
public void setRiskSourceId(String riskSourceId) {
this.riskSourceId = riskSourceId;
}
}
package com.yeejoin.amos.latentdanger.business.entity.mybatis;
import lombok.Data;
/**
* @author keyong
* @title: DangerResultBo
* <pre>
* @description: TODO
* </pre>
* @date 2021/2/1 20:19
*/
@Data
public class DangerResultBo {
private int state;
private String orgCode;
private String userName;
private Long inputItemId;
}
package com.yeejoin.amos.latentdanger.business.entity.mybatis;
import lombok.Data;
@Data
public class DictBo {
private String dictDataValue;
private String dictCode;
private int orderNum;
private String dictDataKey;
private String applicationCode;
}
package com.yeejoin.amos.latentdanger.business.entity.mybatis;
import lombok.Data;
@Data
public class LatentDangerFlowRecordBoExtend {
private String executeDepartmentName = "";
private String executeUserName;
private String executeTime;
private Integer dangerOvertimeState;
private Integer dangerState;
}
package com.yeejoin.amos.latentdanger.business.entity.mybatis;
import lombok.Data;
@Data
public class LatentDangerPatrolBoExtend {
private String itemName;
private String itemBasis;
private String pointName;
private String pointLevel;
private String pointNo;
private String planName;
private String planType;
private String routeName;
private String itemRemark;
private String checkTime;
private String checkUserId;
private String classifyName;
private String pointDepartMentId;
private String classifyOriginalId;
private String pointOriginalId;
private String itemOriginalId;
private Integer executeRate;
private String checkDepartmentId;
}
package com.yeejoin.amos.latentdanger.business.entity.mybatis;
public class PushTargetBo {
private String userId;
private String orgCode;
private String name;
private String username;
private String email;
public String getOrgCode() {
return orgCode;
}
public void setOrgCode(String orgCode) {
this.orgCode = orgCode;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
}
package com.yeejoin.amos.latentdanger.business.entity.mybatis.extend;
import lombok.Data;
import java.util.Date;
/**
* 隐患表
*
* @author DELL
*/
@Data
public class LatentDangerBo {
/**
* 主键自增
*/
private Long id;
/**
* 业务唯一标识
*/
private String businessKey;
/**
* 公司组织机构
*/
private String orgCode;
/**
* 隐患名称
*/
private String dangerName;
private String instanceId;
private Long currentFlowRecordId;
/**
* 隐患等级(1:一般隐患;2:重大隐患;0:安全问题)
*/
private String dangerLevel;
/**
* 隐患地点
*/
private String dangerPosition;
/**
* 隐患类型(1:普通隐患;2:巡检隐患)
*/
private String dangerType;
/**
* 备注
*/
private String remark;
/**
* 整改类型(1:常规整改;2:安措计划;3:延期整改)
*/
private String reformType;
/**
* 限制时间
*/
private Date reformLimitDate;
private Integer overtimeState;
private String reformJson;
/**
* 隐患状态(1:待评审;2:待治理;3:安措计划中;4:逾期未治理;5:待验证;6:治理完毕;7:已撤销)
*/
private String dangerState;
/**
* 发现人
*/
private String discovererUserId;
private String discovererDepartmentId;
private String photoUrls;
/**
* 是否删除(0:否;1:是)
*/
private Integer deleted;
/**
* 记录创建时间
*/
private Date createDate;
/**
* 记录修改时间
*/
private Date updateDate;
/**
* 延期治理时间
*/
private Date delayLimitDate;
/**
* 问题描述
*/
private String problemDescription;
/**
* 原因分析
*/
private String reasonAnalysis;
/**
* 举一反三
*/
private String inferOtherThings;
/**
* 检查记录创建的隐患检查项对应id
*/
private Long bizId;
/**
* 建筑id
*/
private Long structureId;
/**
* 建筑名称
*/
private String structureName;
private String instanceKey;
/**
* 业务类型(不同业务创建的隐患以此区分:巡检隐患、防火监督隐患、其他隐患。。。)
*/
private String bizType;
/**
* 经度
*/
private String longitude;
/**
* 纬度
*/
private String latitude;
}
package com.yeejoin.amos.latentdanger.business.entity.mybatis.extend;
import com.yeejoin.amos.latentdanger.business.entity.mybatis.LatentDangerFlowRecordBoExtend;
import lombok.Data;
import java.util.Date;
@Data
public class LatentDangerFlowRecordBo extends LatentDangerFlowRecordBoExtend {
private Long id;
private Long dangerId;
private String actionFlag;
private String flowTaskName;
private String flowTaskUserIds;
private String flowTaskId;
private Integer executeState;
private String executeUserId;
private String executeResult;
private String remark;
private String flowJson;
/**
* 是否删除(0:否;1:是)
*/
private Integer deleted;
/**
* 记录创建时间
*/
private Date createDate;
/**
* 记录修改时间
*/
private Date updateDate;
private String excuteDepartmentId;
}
package com.yeejoin.amos.latentdanger.business.entity.mybatis.extend;
import java.util.Date;
public class LatentDangerNoticeBo {
/**
* 隐患id
*/
private Long dangerId;
private String orgCode;
/**
* 隐患状态
*/
private Integer dangerState;
/**
* 隐患名称
*/
private String dangerName;
/**
* 治理期限
*/
private Date reformLimitDate;
/**
* 消息接收人(隐患治理人)
*/
private String receiverIds;
private String instanceId;
public String getInstanceId() {
return instanceId;
}
public void setInstanceId(String instanceId) {
this.instanceId = instanceId;
}
public Long getDangerId() {
return dangerId;
}
public void setDangerId(Long dangerId) {
this.dangerId = dangerId;
}
public String getOrgCode() {
return orgCode;
}
public void setOrgCode(String orgCode) {
this.orgCode = orgCode;
}
public Integer getDangerState() {
return dangerState;
}
public void setDangerState(Integer dangerState) {
this.dangerState = dangerState;
}
public String getDangerName() {
return dangerName;
}
public void setDangerName(String dangerName) {
this.dangerName = dangerName;
}
public Date getReformLimitDate() {
return reformLimitDate;
}
public void setReformLimitDate(Date reformLimitDate) {
this.reformLimitDate = reformLimitDate;
}
public String getReceiverIds() {
return receiverIds;
}
public void setReceiverIds(String receiverIds) {
this.receiverIds = receiverIds;
}
}
package com.yeejoin.amos.latentdanger.business.entity.mybatis.extend;
import com.yeejoin.amos.latentdanger.business.entity.mybatis.LatentDangerPatrolBoExtend;
import lombok.Data;
import java.util.Date;
/**
* 隐患巡检关系表
*/
@Data
public class LatentDangerPatrolBo extends LatentDangerPatrolBoExtend {
private Long id;
private Long latentDangerId;
private Long pointClassifyId;
private Long checkId;
private Long itemId;
private Long pointId;
private Long routeId;
private String riskFactorFlowId;
private Long routePointItemId;
/**
* 是否删除(0:否;1:是)
*/
private Integer deleted;
/**
* 检查类型-交大字段,只是前段显示用
*/
private String checkType;
/**
* 记录创建时间
*/
private Date createDate;
/**
* 记录修改时间
*/
private Date updateDate;
}
//package com.yeejoin.amos.latentdanger.business.feign;
//
//import com.yeejoin.amos.latentdanger.business.entity.mybatis.DangerResultBo;
//import com.yeejoin.amos.latentdanger.business.util.CommonResponse;
//import org.springframework.cloud.openfeign.FeignClient;
//import org.springframework.web.bind.annotation.PostMapping;
//import org.springframework.web.bind.annotation.RequestBody;
//
//@FeignClient(name = "${Business.fegin.name}", configuration = FeignConfiguration.class)
//public interface Business {
//
// /**
// * <pre>
// * @Description: 隐患治理完成更新rpn值
// * </pre>
// *
// * @MethodName:
// * @Param:
// * @Return: null
// * @Throws
// * @Author keyong
// * @Date 2021/2/4 20:55
// */
// @PostMapping(value = "/fireAutoSys/api/risksource/data/danger/state")
// CommonResponse processProtalDataFromDanger(@RequestBody DangerResultBo data);
//}
\ No newline at end of file
//package com.yeejoin.amos.latentdanger.business.feign;
//
//import org.springframework.cloud.openfeign.FeignClient;
//import org.springframework.web.bind.annotation.RequestBody;
//import org.springframework.web.bind.annotation.RequestMapping;
//import org.springframework.web.bind.annotation.RequestMethod;
//import org.springframework.web.bind.annotation.RequestParam;
//
//import java.util.LinkedHashMap;
//
////装备
//@FeignClient(name = "${equip.fegin.name}")
//public interface EquipFeign {
// @RequestMapping(value = "${equip.fegin.prefix}" + "/equipSpecific/getSourceNameByEquipSpeId", method = RequestMethod.GET, consumes = "application/json")
// LinkedHashMap<String, Object> getEquipDetail(@RequestParam(value = "id", required = true) Long id);
//
// @RequestMapping(value = "${equip.fegin.prefix}" + "/equipSpecific/getSourceNameList", method = RequestMethod.POST, consumes = "application/json")
// LinkedHashMap<String, Object> getEquipList(@RequestBody Long id);
//
// @RequestMapping(value = "${equip.fegin.prefix}" + "/warehouse-structure/listAll", method = RequestMethod.GET, consumes = "application/json")
// String getStructureNameAll();
//
// /**
// * 消防建筑树
// *
// * @return
// */
// @RequestMapping(value = "${equip.fegin.prefix}" + "/building/tree", method = RequestMethod.GET, consumes = "application/json")
// LinkedHashMap<String, Object> getBuildingTree();
//
// @RequestMapping(value = "${equip.fegin.prefix}" + "/building/getBuildingAbsolutePosition", method = RequestMethod.GET, consumes = "application/json")
// LinkedHashMap<String, Object> getBuildingAbsolutePosition();
//
// /**
// * 所属局域树
// *
// * @return
// */
// @RequestMapping(value = "${equip.fegin.prefix}" + "/area/tree", method = RequestMethod.GET, consumes = "application/json")
// LinkedHashMap<String, Object> getRegionTress();
//}
//
package com.yeejoin.amos.latentdanger.business.feign;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
public class FeignBasicAuthRequestInterceptor implements RequestInterceptor {
public FeignBasicAuthRequestInterceptor() {
}
@Override
public void apply(RequestTemplate template) {
RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
if (requestAttributes == null) {
return;
}
ServletRequestAttributes attributes = (ServletRequestAttributes) requestAttributes;
HttpServletRequest request = attributes.getRequest();
//设置header
String token = request.getHeader("X-Access-Token");
String product = request.getHeader("product");
String appKey = request.getHeader("appKey");
template.header("token", token);
template.header("product", product);
template.header("appKey", appKey);
}
}
package com.yeejoin.amos.latentdanger.business.feign;
import feign.codec.Encoder;
import feign.form.spring.SpringFormEncoder;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.cloud.openfeign.support.SpringEncoder;
import org.springframework.context.annotation.Bean;
public class FeignConfiguration {
@Autowired
private ObjectFactory<HttpMessageConverters> messageConverters;
@Bean
public Encoder feignFormEncoder() {
return new SpringFormEncoder(new SpringEncoder(messageConverters));
}
@Bean
public FeignBasicAuthRequestInterceptor basicAuthRequestInterceptor() {
return new FeignBasicAuthRequestInterceptor();
}
}
//package com.yeejoin.amos.latentdanger.business.listeners;
//
//import org.springframework.beans.factory.annotation.Lookup;
//import org.springframework.scheduling.annotation.EnableAsync;
//import org.springframework.stereotype.Component;
//
///**
// * 隐患状态监听器
// *
// * @author DELL
// */
//@Component
//public interface LatentDangerListener {
//
// /**
// * 隐患关闭
// *
// * @param latentDangerId 隐患id
// */
// @Lookup
// void latentDangerClosed(String latentDangerId);
//}
//package com.yeejoin.amos.latentdanger.business.listeners;
//
//import com.yeejoin.amos.latentdanger.core.listeners.LatentDangerListener;
//import org.springframework.scheduling.annotation.EnableAsync;
//import org.springframework.stereotype.Component;
//
///**
// * 隐患状态监听器
// *
// * @author DELL
// */
//public class LatentDangerListenerImpl implements LatentDangerListener {
//
// /**
// * 隐患关闭
// *
// * @param latentDangerId 隐患id
// */
// @Override
// public void latentDangerClosed(String latentDangerId) {
//
// };
//}
package com.yeejoin.amos.latentdanger.business.param;
/**
* JPush 推送类型
* @author maoying
*
*/
public enum JPushTypeEnum {
ALL("广播","1"),
TAG("标签","2" ),
ALIAS("别名", "3");
/**
* 名称,描述
*/
private String name;
/**
* 编码
*/
private String code;
private JPushTypeEnum(String name, String code){
this.name = name;
this.code = code;
}
public static JPushTypeEnum getEnum(String code) {
JPushTypeEnum jPushTypeEnum = null;
for(JPushTypeEnum type: JPushTypeEnum.values()) {
if (type.getCode().equals(code)) {
jPushTypeEnum = type;
break;
}
}
return jPushTypeEnum;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
}
package com.yeejoin.amos.latentdanger.business.param;
import lombok.Data;
import javax.persistence.Column;
import java.util.List;
/**
* @author tb
* @title: LatentDangerDto
* <pre>
* @description: TODO
* </pre>
* @date 2021/1/26 14:48
*/
@Data
public class LatentDangerDto {
/**
* 隐患等级(1:一般隐患;2:重大隐患;0:安全问题)
*/
private String dangerLevel;
/**
* 隐患等级名称
*/
private String dangerLevelName;
/**
* 问题描述
*/
private String remark;
/**
* 创建隐患的业务id(p_check_input)
*/
private Long bizId;
/**
* 建筑id
*/
private Long structureId;
/**
* 建筑名称
*/
private String structureName;
private String instanceKey;
/**
* 隐患名称
*/
private String name;
/**
* 整改日期
*/
private String reformLimitDate;
/**
* 经度
*/
private String longitude;
/**
* 纬度
*/
private String latitude;
/**
* 隐患图片列表
*/
private List<String> photoUrl;
/**
* 检查项名称
*/
private String inputItemName;
/**
* 风险点id
*/
private String riskSourceId;
/**
* 隐患地址
*/
private String dangerPosition;
/**
* 治理方式
*/
private String reformType;
/**
* 治理方式名称
*/
private String reformTypeName;
/**
* 是否删除(0未删除、1已删除)
*/
private Boolean deleted = false;
/**
* 主键
*/
private Long id;
/**
* 隐患状态
*/
private String dangerState;
/**
* 隐患状态名称
*/
private String dangerStateName;
/**
* 业务类型(不同业务创建的隐患以此区分:巡检隐患、防火监督隐患、其他隐患。。。)
*/
private String bizType;
/**
* 检查类型(1无码检查、2计划检查、3无计划检查、4随手拍)
*/
private String checkMode;
}
package com.yeejoin.amos.latentdanger.business.param;
import com.alibaba.fastjson.JSONObject;
import lombok.Data;
/**
* @author DELL
*/
@Data
public class LatentDangerExecuteParam {
/**
* 隐患工作流记录id
*/
private Long flowRecordId;
/**
* 任务id
*/
private String taskId;
/**
* 执行类型
*/
private Integer executeType;
/**
* 备注
*/
private String remark;
/**
* 可执行人
*/
private String nextCanActionUser;
/**
* 整改日期
*/
private String reformLimitDate;
private JSONObject flowJson;
/**
* 整改延期日期
*/
private String delayLimitDate;
/**
* 隐患id
*/
private Long dangerId;
/**
* 延期治理是否需要公司审核
*/
private Integer needCompanyVerify;
/**
* 原因分析
*/
private String reasonAnalysis;
/**
* 举一反三
*/
private String inferOtherThings;
/**
*问题描述
*/
private String problemDescription;
/**
* 隐患等级
*/
private String dangerLevel;
}
package com.yeejoin.amos.latentdanger.business.param;
import com.yeejoin.amos.latentdanger.core.common.request.CommonPageable;
import lombok.Data;
/**
* @author keyong
* @title: LatentDangerListParam
* <pre>
* @description: TODO
* </pre>
* @date 2021/1/26 14:49
*/
@Data
public class LatentDangerListParam extends CommonPageable {
/**
* 0:全部;1:我的
*/
private Integer belongType;
/**
* 0:全部;1:待评审;2:待治理;3:安措计划中;4:待验证;5:治理完毕;6:已撤销;7:延期治理中;8:延期治理待车间部门审核;9:延期治理待公司审核
*/
private Integer dangerState;
/**
* 是否已处理(1:是;2:否)
*/
private Boolean isHandle;
/**
* -1:全部;1:一般隐患;2:重大隐患;0:安全问题
*/
private Integer dangerLevel;
private String dangerName;
private String userId;
}
package com.yeejoin.amos.latentdanger.business.param;
import lombok.Data;
import java.util.List;
/**
* @author keyong
* @title: LatentDangerNormalParam
* <pre>
* @description: 隐患
* </pre>
* @date 2021/1/26 14:46
*/
@Data
public class LatentDangerNormalParam {
/**
* 隐患名称
*/
private String dangerName;
/**
* 隐患等级(1:一般隐患;2:重大隐患;3:安全问题)
*/
private String dangerLevel;
/**
* 隐患地点
*/
private String dangerPosition;
/**
* 备注
*/
private String remark;
/**
* 拍照路径集合(多个逗号分开)
*/
private List<String> photoUrl;
/**
* 建筑id
*/
private Long structureId;
/**
* 建筑名称
*/
private String structureName;
/**
* 隐患地址经度
*/
private String longitude;
/**
* 隐患地址纬度
*/
private String latitude;
/**
* 业务类型(不同业务创建的隐患以此区分:巡检隐患、防火监督隐患、其他隐患。。。)
*/
private String bizType;
}
package com.yeejoin.amos.latentdanger.business.param;
import lombok.Data;
import java.util.List;
/**
* @author keyong
* @title: LatentDangerPatrolParam
* <pre>
* @description: TODO
* </pre>
* @date 2021/1/26 14:47
*/
@Data
public class LatentDangerPatrolParam {
private List<LatentDangerDto> dangerList;
/**
* 业务类型(不同业务创建的隐患以此区分:巡检隐患、防火监督隐患、其他隐患。。。)
*/
private String bizType;
/**
* 检查类型(1无码检查、2计划检查、3无计划检查、4随手拍)
*/
private String checkMode;
}
package com.yeejoin.amos.latentdanger.business.param;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import java.util.HashMap;
public class PageParam<K, V> extends HashMap<K, V> implements Pageable {
/**
* 页号(大于等于0)
*/
protected int pageNumber = 0;
/**
* 每页大小(大于等于0)
*/
protected int pageSize = 10;
/**
* 起始索引
*/
protected int offset = 0;
/**
* 排序
*/
protected Sort sort = null;
public PageParam() {
this.pageNumber = 0;
this.pageSize = 10;
this.offset = pageSize * pageNumber;
}
public PageParam(int pageNumber, int pageSize) {
this.pageNumber = pageNumber;
this.pageSize = pageSize;
this.offset = pageSize * pageNumber;
}
public PageParam(int pageNumber, int pageSize, Sort sort) {
this.pageNumber = pageNumber;
this.pageSize = pageSize;
this.sort = sort;
this.offset = pageSize * pageNumber;
}
public int getPageNumber() {
return this.pageNumber;
}
public int getPageSize() {
return pageSize;
}
public long getOffset() {
offset = pageSize * pageNumber;
return offset;
}
public Sort getSort() {
return sort;
}
public Pageable next() {
return null;
}
public Pageable previousOrFirst() {
return null;
}
public Pageable first() {
return null;
}
public boolean hasPrevious() {
return false;
}
public void setPageNumber(int pageNumber) {
this.pageNumber = pageNumber;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public void setSort(Sort sort) {
this.sort = sort;
}
public void setOffset(int offset) {
this.offset = offset;
}
}
package com.yeejoin.amos.latentdanger.business.param;
import java.util.List;
import java.util.Map;
public class PushMsgParam {
/**
* 标题
*/
private String subject;
/**
* 消息内容
*/
private String content;
/**
* 邮件地址
*/
private String[] emails;
/**
* jpush接收人
*/
private List<String> recivers;
//
/**
* jpush参数传递
*/
Map<String, String> extras;
/**
* jpush发送类型:1:广播;2:标签;3:别名
*/
private String type = "3";
private String relationId;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public List<String> getRecivers() {
return recivers;
}
public void setRecivers(List<String> recivers) {
this.recivers = recivers;
}
public Map<String, String> getExtras() {
return extras;
}
public void setExtras(Map<String, String> extras) {
this.extras = extras;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String[] getEmails() {
return emails;
}
public void setEmails(String[] emails) {
this.emails = emails;
}
public String getRelationId() {
return relationId;
}
public void setRelationId(String relationId) {
this.relationId = relationId;
}
}
package com.yeejoin.amos.latentdanger.business.service.impl;
import com.yeejoin.amos.latentdanger.business.dao.mapper.LatentDangerFlowRecordMapper;
import com.yeejoin.amos.latentdanger.business.entity.mybatis.extend.LatentDangerFlowRecordBo;
import com.yeejoin.amos.latentdanger.business.service.intfc.ILatentDangerFlowRecordService;
import com.yeejoin.amos.latentdanger.dao.entity.LatentDangerFlowRecord;
import org.springframework.stereotype.Service;
import org.typroject.tyboot.core.rdbms.service.BaseService;
/**
* @author DELL
*/
@Service("latentDangerFlowRecordService")
public class LatentDangerFlowRecordServiceImpl extends BaseService<LatentDangerFlowRecordBo, LatentDangerFlowRecord,
LatentDangerFlowRecordMapper> implements ILatentDangerFlowRecordService {
}
package com.yeejoin.amos.latentdanger.business.service.impl;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.yeejoin.amos.boot.biz.common.bo.DepartmentBo;
import com.yeejoin.amos.boot.biz.common.bo.RoleBo;
import com.yeejoin.amos.boot.biz.common.utils.RedisUtils;
import com.yeejoin.amos.boot.module.common.api.feign.EquipFeignClient;
import com.yeejoin.amos.boot.module.common.api.feign.SupervisionFeignClient;
import com.yeejoin.amos.component.feign.model.FeignClientResult;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;
import com.yeejoin.amos.feign.privilege.model.DepartmentModel;
import com.yeejoin.amos.feign.systemctl.Systemctl;
import com.yeejoin.amos.feign.systemctl.model.DictionarieModel;
import com.yeejoin.amos.feign.systemctl.model.DictionarieValueModel;
import com.yeejoin.amos.latentdanger.business.constants.Constants;
import com.yeejoin.amos.latentdanger.business.dao.mapper.LatentDangerFlowRecordMapper;
import com.yeejoin.amos.latentdanger.business.dao.mapper.LatentDangerMapper;
import com.yeejoin.amos.latentdanger.business.dao.mapper.LatentDangerPatrolMapper;
import com.yeejoin.amos.latentdanger.business.dto.DangerExecuteSubmitDto;
import com.yeejoin.amos.latentdanger.business.entity.mybatis.DangerResultBo;
import com.yeejoin.amos.latentdanger.business.entity.mybatis.DictBo;
import com.yeejoin.amos.latentdanger.business.entity.mybatis.extend.LatentDangerBo;
import com.yeejoin.amos.latentdanger.business.entity.mybatis.extend.LatentDangerFlowRecordBo;
import com.yeejoin.amos.latentdanger.business.entity.mybatis.extend.LatentDangerNoticeBo;
import com.yeejoin.amos.latentdanger.business.entity.mybatis.extend.LatentDangerPatrolBo;
import com.yeejoin.amos.latentdanger.business.param.LatentDangerDto;
import com.yeejoin.amos.latentdanger.business.param.LatentDangerExecuteParam;
import com.yeejoin.amos.latentdanger.business.param.LatentDangerListParam;
import com.yeejoin.amos.latentdanger.business.param.LatentDangerNormalParam;
import com.yeejoin.amos.latentdanger.business.param.PageParam;
import com.yeejoin.amos.latentdanger.business.service.intfc.ILatentDangerService;
import com.yeejoin.amos.latentdanger.business.util.CommonResponse;
import com.yeejoin.amos.latentdanger.business.util.CommonResponseUtil;
import com.yeejoin.amos.latentdanger.business.util.DateUtil;
import com.yeejoin.amos.latentdanger.business.util.RandomUtil;
import com.yeejoin.amos.latentdanger.business.vo.DangerTimeAxisVo;
import com.yeejoin.amos.latentdanger.business.vo.LatentDangerDetailRiskVo;
import com.yeejoin.amos.latentdanger.business.vo.LatentDangerDetailVo;
import com.yeejoin.amos.latentdanger.business.vo.LatentDangerListVo;
import com.yeejoin.amos.latentdanger.common.enums.DangerHandleStateEnum;
import com.yeejoin.amos.latentdanger.common.enums.DictTypeEnum;
import com.yeejoin.amos.latentdanger.common.enums.ExecuteStateEnum;
import com.yeejoin.amos.latentdanger.common.enums.InstanceKeyEnum;
import com.yeejoin.amos.latentdanger.common.enums.LatentDangerBizTypeEnum;
import com.yeejoin.amos.latentdanger.common.enums.LatentDangerExecuteTypeEnum;
import com.yeejoin.amos.latentdanger.common.enums.LatentDangerLevelEnum;
import com.yeejoin.amos.latentdanger.common.enums.LatentDangerOvertimeStateEnum;
import com.yeejoin.amos.latentdanger.common.enums.LatentDangerReformTypeEnum;
import com.yeejoin.amos.latentdanger.common.enums.LatentDangerStateEnum;
import com.yeejoin.amos.latentdanger.common.enums.LatentDangerTypeEnum;
import com.yeejoin.amos.latentdanger.common.remote.RemoteSpcService;
import com.yeejoin.amos.latentdanger.common.remote.RemoteWebSocketServer;
import com.yeejoin.amos.latentdanger.common.remote.RemoteWorkFlowService;
import com.yeejoin.amos.latentdanger.core.async.AsyncTask;
import com.yeejoin.amos.latentdanger.core.common.request.LatentDangerResultPushSpcRequest;
import com.yeejoin.amos.latentdanger.core.common.response.DangerListResponse;
import com.yeejoin.amos.latentdanger.core.util.StringUtil;
import com.yeejoin.amos.latentdanger.dao.entity.LatentDanger;
import com.yeejoin.amos.latentdanger.dao.entity.LatentDangerFlowRecord;
import com.yeejoin.amos.latentdanger.exception.YeeException;
import com.yeejoin.amos.latentdanger.feign.RemoteSecurityService;
import com.yeejoin.amos.latentdanger.mqtt.WebMqttComponent;
import org.apache.commons.lang3.ObjectUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.typroject.tyboot.core.foundation.context.RequestContext;
import org.typroject.tyboot.core.foundation.utils.Bean;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;
import org.typroject.tyboot.core.rdbms.service.BaseService;
import org.typroject.tyboot.core.restful.utils.ResponseModel;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
import static com.yeejoin.amos.latentdanger.business.util.RandomUtil.buildOrderNo;
import static org.typroject.tyboot.core.foundation.context.RequestContext.getProduct;
//import com.yeejoin.amos.latentdanger.business.feign.Business;
//import com.yeejoin.amos.latentdanger.business.feign.EquipFeign;
@Service("latentDangerService")
public class LatentDangerServiceImpl extends BaseService<LatentDangerBo, LatentDanger, LatentDangerMapper> implements ILatentDangerService {
private static final String permissionType = "SUBMENU";
private static final String acctivePermissionType = "activitiItem";
private static final String path = "AppNormalLatentDangerReview";
private final Logger logger = LoggerFactory.getLogger(LatentDangerServiceImpl.class);
@Autowired
EquipFeignClient equipFeign;
@Autowired
SupervisionFeignClient supervisionFeignClient;
@Autowired
private RemoteWorkFlowService remoteWorkFlowService;
@Autowired
private RemoteSecurityService remoteSecurityService;
@Autowired
private LatentDangerMapper latentDangerMapper;
@Autowired
private LatentDangerFlowRecordMapper latentDangerFlowRecordMapper;
@Autowired
private LatentDangerPatrolMapper latentDangerPatrolMapper;
@Autowired
private RemoteSpcService remoteSpcService;
@Autowired
private AsyncTask asyncTask;
@Autowired
private RemoteWebSocketServer remoteWebSocketServer;
@Autowired
private LatentDangerFlowRecordServiceImpl latentDangerFlowRecordService;
// @Autowired
// private Business business;
@Value("${file.url}")
private String fileServerAddress;
@Value("${params.work.flow.processDefinitionKey}")
private String processDefinitionKey;
@Value("${amosRefresh.danger.topic}")
private String dangerTopic;
@Autowired
private WebMqttComponent webMqttComponent;
@Value("${danger.biz.type}")
private String dangerBizType;
@Value("${workflow.process.definition.key}")
private String workflowProcessDefinitionKey;
@Transactional(rollbackFor = Exception.class)
@Override
public CommonResponse saveNormal(LatentDangerNormalParam latentDangerDto, String userId, String userRealName, String departmentId, String departmentName, String companyId, String orgCode, RoleBo role) {
LatentDangerLevelEnum dangerLevelEnum = LatentDangerLevelEnum.getEnumByCode(latentDangerDto.getDangerLevel());
if (ValidationUtil.isEmpty(dangerLevelEnum)) {
return CommonResponseUtil.failure("隐患等级有误");
}
String businessKey = buildOrderNo();
LatentDanger latentDanger = saveLatentDanger("", "", "", latentDangerDto.getRemark(),
userId, departmentId, businessKey, orgCode, latentDangerDto.getDangerName(), latentDangerDto.getDangerLevel()
, latentDangerDto.getDangerPosition(), LatentDangerTypeEnum.随手拍,
latentDangerDto.getPhotoUrl(), 0L, latentDangerDto.getStructureId(),
latentDangerDto.getStructureName(), InstanceKeyEnum.NORMAL.getCode(),
latentDangerDto.getLongitude(), latentDangerDto.getLatitude());
// 更新p_check_input表state字段
updateCheckInputDangerState(latentDanger.getBizId(), DangerHandleStateEnum.HANDLE.getCode());
Long dangerId = latentDanger.getId();
Date startDate = new Date();
JSONObject jsonObject = remoteWorkFlowService.startNew(dangerId, businessKey, processDefinitionKey);
Date endDate = new Date();
logger.info("-------------------------提交隐患时间" + (endDate.getTime() - startDate.getTime()));
if (jsonObject == null) {
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
return CommonResponseUtil.failure("启动流程失败");
}
JSONObject instance = jsonObject.getJSONObject("data");
if (instance == null) {
return CommonResponseUtil.failure("无提交隐患权限");
}
//提交隐患
// jsonObject = remoteWorkFlowService.excute(instance.getString("id"), null);
// JSONObject task = jsonObject.getJSONObject("data");
latentDanger.setInstanceId(instance.getString("id"));
JSONObject flowJson = new JSONObject();
flowJson.put("photoUrls", latentDangerDto.getPhotoUrl());
LatentDangerFlowRecord record = saveFlowRecord(instance.getString("id"), "提交隐患", userId, departmentId, flowJson, dangerId, role, LatentDangerExecuteTypeEnum.填写隐患完成.getName(), latentDangerDto.getRemark());
latentDanger.setCurrentFlowRecordId(record.getId());
latentDangerMapper.updateById(latentDanger);
sendMessage(latentDanger, LatentDangerExecuteTypeEnum.填写隐患完成, null,
"隐患排查与治理", this.getNextExecuteUsers(latentDanger.getInstanceId()), userRealName, departmentName);
try {
webMqttComponent.publish(dangerTopic, "");
} catch (Exception e) {
logger.error("隐患提交数字换流站页面推送失败-----------" + e.getMessage());
}
return CommonResponseUtil.success();
}
@Transactional(rollbackFor = Exception.class)
@Override
public CommonResponse savePatrol(List<LatentDangerDto> latentDangerDtoList, String userId, String userRealName,
String departmentId, String departmentName, String companyId, String orgCode, RoleBo role) throws IllegalAccessException, InstantiationException {
if (ValidationUtil.isEmpty(latentDangerDtoList)) {
return CommonResponseUtil.success();
}
// 获取业务类型枚举
LatentDangerBizTypeEnum bizTypeEnum =
LatentDangerBizTypeEnum.getByCode(latentDangerDtoList.get(0).getBizType());
if (ValidationUtil.isEmpty(bizTypeEnum)) {
return CommonResponseUtil.failure("业务类型有误");
}
// 根据业务类型填充隐患等级枚举 TODO aop
// fillLatentDangerLevelEnum(bizTypeEnum);
List<LatentDanger> dangerList = Lists.newArrayList();
for (LatentDangerDto param : latentDangerDtoList) {
String businessKey = RandomUtil.buildOrderNo();
LatentDangerLevelEnum levelEnum = LatentDangerLevelEnum.getEnumByCode(param.getDangerLevel());
if (levelEnum == null) {
return CommonResponseUtil.failure("隐患等级参数有误");
}
LatentDangerTypeEnum dangerTypeEnum =
LatentDangerTypeEnum.getByCode(latentDangerDtoList.get(0).getCheckMode());
if (ValidationUtil.isEmpty(dangerTypeEnum)) {
return CommonResponseUtil.failure("检查类型参数有误");
}
// 保存隐患
LatentDanger latentDanger = saveLatentDanger2(param, userId, departmentId, businessKey, orgCode,
dangerTypeEnum);
JSONObject instance = new JSONObject();
// 巡检业务需要在填写隐患后直接开启工作流
if (bizTypeEnum == LatentDangerBizTypeEnum.巡检) {
// 更新巡检p_check_input表state字段
updateCheckInputDangerState(latentDanger.getBizId(), DangerHandleStateEnum.HANDLE.getCode());
Long dangerId = latentDanger.getId();
Date startDate = new Date();
JSONObject jsonObject = remoteWorkFlowService.startNew(dangerId, businessKey, processDefinitionKey);
Date endDate = new Date();
logger.info("-------------------------提交隐患时间" + (endDate.getTime() - startDate.getTime()));
if (jsonObject == null) {
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
return CommonResponseUtil.failure("启动流程失败");
}
instance = jsonObject.getJSONObject("data");
if (instance == null) {
return CommonResponseUtil.failure("无提交隐患权限");
}
}
JSONObject flowJson = new JSONObject();
flowJson.put("photoUrls", Joiner.on(",").join(param.getPhotoUrl()));
// 第一次保存隐患提交记录
LatentDangerFlowRecord inputRecord = saveFlowRecord(instance.getString("id"), "提交隐患", userId, departmentId,
flowJson, latentDanger.getId(), role, LatentDangerExecuteTypeEnum.填写隐患完成.getName(),
latentDanger.getRemark());
// TODO 业务自己保存
// if (LatentDangerTypeEnum.计划检查.getCode().equals(latentDangerBo.getDangerType())
// || LatentDangerTypeEnum.无计划检查.getCode().equals(latentDangerBo.getDangerType())) {
// LatentDangerPatrolBo latentDangerPatrolBo = new LatentDangerPatrolBo();
// latentDangerPatrolBo.setCheckId((Long) inputCheckObj.get("checkId"));
// latentDangerPatrolBo.setPointClassifyId((Long) inputCheckObj.get("pointClassifyId"));
// latentDangerPatrolBo.setItemId((Long) inputCheckObj.get("itemId"));
// latentDangerPatrolBo.setRouteId((Long) inputCheckObj.get("routeId"));
// latentDangerPatrolBo.setPointId((Long) inputCheckObj.get("pointId"));
// latentDangerPatrolBo.setLatentDangerId(latentDangerBo.getId());
// latentDangerPatrolBo.setRoutePointItemId((Long) inputCheckObj.get("routePointItemId"));
// latentDangerPatrolMapper.save(latentDangerPatrolBo);
// }
latentDanger.setCurrentFlowRecordId(inputRecord.getId());
latentDanger.setInstanceId(instance.getString("id"));
latentDangerMapper.updateById(latentDanger);
// TODO 使用远程调用替换
// LatentDangerPatrolBo patrolBo = latentDangerPatrolMapper.getByDangerId(latentDanger.getId());
// LatentDangerPatrolBo patrolBo = new LatentDangerPatrolBo();
// sendMessage(latentDanger, LatentDangerExecuteTypeEnum.填写隐患完成, patrolBo,
// "巡检隐患排查与治理", this.getNextExecuteUsers(latentDanger.getInstanceId()), userRealName, departmentName);
try {
webMqttComponent.publish(dangerTopic, "");
} catch (Exception e) {
logger.error("巡检隐患提交数字换流站页面推送失败-----------" + e.getMessage());
}
dangerList.add(latentDanger);
}
return CommonResponseUtil.success(dangerList);
}
// TODO 使用远程调用替换
// private void updateMeasuresContentStatus(Long riskFactorId, Long measuresContentId, String evaluateId, RiskFactorsCmStatusEnum riskFactorsCmStatusEnum) {
// Map<String, Object> map = Maps.newHashMap();
// map.put("riskFactorId", riskFactorId);
// map.put("measuresContentId", measuresContentId);
// map.put("evaluateId", evaluateId);
// map.put("status", riskFactorsCmStatusEnum.getCode());
// riskFactorCmMapper.updateStatusByMap(map);
// RiskFactorBo riskFactorBo = new RiskFactorBo();
// riskFactorBo.setId(riskFactorId);
// Long outControlNumber = riskFactorCmMapper.countOutControl(map);
// if (outControlNumber.equals(0L)) {
// riskFactorBo.setControlStatus(RiskFactorsCmStatusEnum.Control.getName());
// } else {
// riskFactorBo.setControlStatus(RiskFactorsCmStatusEnum.outOfControl.getName());
// }
// riskFactorMapper.updateControlStatus(riskFactorBo);
// }
// TODO 改为远程调用
private void updateCheckInputDangerState(Long id, int code) {
latentDangerMapper.updateCheckInputDangerState(id, code);
}
public LatentDanger saveLatentDanger(String bizType, String instanceId, String problemDescription, String remark,
String userId, String departmentId, String businessKey, String orgCode,
String dangerName, String level, String position,
LatentDangerTypeEnum dangerTypeEnum, List<String> photoUrls,
Long checkInputId, Long structureId, String structureName,
String instanceKey, String longitude, String latitude) {
LatentDanger latentDanger = new LatentDanger();
latentDanger.setBizType(bizType);
latentDanger.setInstanceId(instanceId);
latentDanger.setProblemDescription(problemDescription);
latentDanger.setRemark(remark);
latentDanger.setDangerState(LatentDangerStateEnum.待评审.getCode().toString());
latentDanger.setDiscovererUserId(userId);
latentDanger.setDiscovererDepartmentId(departmentId);
latentDanger.setBusinessKey(businessKey);
latentDanger.setOrgCode(orgCode);
latentDanger.setDangerName(dangerName);
latentDanger.setDangerLevel(level);
latentDanger.setDangerPosition(position);
latentDanger.setDangerType(dangerTypeEnum.getCode().toString());
latentDanger.setLongitude(longitude);
latentDanger.setLatitude(latitude);
latentDanger.setPhotoUrls(Joiner.on(",").join(photoUrls));
latentDanger.setBizId(checkInputId);
latentDanger.setStructureId(structureId);
latentDanger.setStructureName(structureName);
latentDanger.setInstanceKey(instanceKey);
this.saveOrUpdate(latentDanger);
return latentDanger;
}
public LatentDanger saveLatentDanger2(LatentDangerDto param, String userId,
String departmentId, String businessKey, String orgCode,
LatentDangerTypeEnum dangerTypeEnum) {
LatentDanger latentDanger = new LatentDanger();
Bean.copyExistPropertis(param, latentDanger);
if (ValidationUtil.isEmpty(param.getId())) {
// 新增
latentDanger.setBusinessKey(businessKey);
latentDanger.setDiscovererDepartmentId(departmentId);
latentDanger.setDiscovererUserId(userId);
latentDanger.setOrgCode(orgCode);
latentDanger.setDangerType(dangerTypeEnum.getCode().toString());
if (!ValidationUtil.isEmpty(param.getName())) {
latentDanger.setDangerName(param.getName());
} else {
latentDanger.setDangerName(param.getInputItemName());
}
}
this.saveOrUpdate(latentDanger);
return latentDanger;
}
public LatentDangerFlowRecord saveFlowRecord(String taskId, String taskName, String userId, String departmentId,
JSONObject flowJson, Long dangerId, RoleBo role, String executeResult, String remark) {
LatentDangerFlowRecord record = new LatentDangerFlowRecord();
record.setFlowTaskId(taskId);
record.setExecuteUserId(userId);
record.setExecuteDepartmentId(departmentId);
record.setFlowJson(flowJson != null ? flowJson.toJSONString() : null);
record.setFlowTaskName(taskName);
record.setDangerId(dangerId);
record.setExecuteResult(executeResult);
record.setActionFlag(taskName);
record.setRemark(remark);
latentDangerFlowRecordService.saveOrUpdate(record);
return record;
}
public LatentDangerFlowRecordBo saveFlowRecord(String taskId, String userIds, String taskName,
String taskDefinitionKey, Long dangerId) {
LatentDangerFlowRecordBo record = new LatentDangerFlowRecordBo();
record.setFlowTaskId(taskId);
record.setFlowTaskUserIds(userIds);
record.setFlowTaskName(taskName);
record.setActionFlag(taskDefinitionKey);
record.setDangerId(dangerId);
latentDangerFlowRecordMapper.save(record);
return record;
}
public void updateFlowRecord(LatentDangerFlowRecordBo flowRecordBo, LatentDangerExecuteTypeEnum executeTypeEnum,
String userId, String departmentId, String remark, JSONObject flowJson) {
flowRecordBo.setExecuteState(executeTypeEnum.getExecuteState().getCode());
flowRecordBo.setExcuteDepartmentId(departmentId);
flowRecordBo.setExecuteUserId(userId);
flowRecordBo.setExecuteResult(executeTypeEnum.getName());
if (!StringUtils.isEmpty(remark)) {
flowRecordBo.setRemark(remark);
}
if (flowJson != null) {
flowRecordBo.setFlowJson(flowJson.toJSONString());
}
latentDangerFlowRecordMapper.update(flowRecordBo);
}
private Set<String> getUserIdsStrByTypeAndDefKey(String definitionKey) {
List<AgencyUserModel> users = remoteSecurityService.listUserByMenuCode(acctivePermissionType, definitionKey);
if (CollectionUtils.isEmpty(users)) {
return Sets.newHashSet();
} else {
return Sets.newHashSet(Lists.transform(users, AgencyUserModel::getUserId));
}
}
private Set<String> getUserIdsStrByPerTypeAndDefKey(JSONObject jsonObject) {
String taskDefinitionKey = jsonObject.getString("taskDefinitionKey");
// List<UserModel> users = remoteSecurityService.listUserByMenuCode(acctivePermissionType, taskDefinitionKey);
// if (CollectionUtils.isEmpty(users)) {
// return Sets.newHashSet();
// } else {
// return Sets.newHashSet(Lists.transform(users, UserModel::getUserId));
// }
return getUserIdsStrByTypeAndDefKey(taskDefinitionKey);
}
private Map<String, Object> buildQueryMapForList(LatentDangerListParam latentDangerListParam, String userId) {
Map<String, Object> map = Maps.newHashMap();
Long offset = latentDangerListParam.getOffset();
map.put("offset", offset);
map.put("limit", latentDangerListParam.getPageSize());
if (latentDangerListParam.getIsHandle() != null) {
List<String> states = Lists.newArrayList();
if (latentDangerListParam.getIsHandle()) {
states.add(LatentDangerStateEnum.治理完毕.getCode());
states.add(LatentDangerStateEnum.已撤销.getCode());
} else {
states.add(LatentDangerStateEnum.待验证.getCode());
states.add(LatentDangerStateEnum.延期治理申请.getCode());
states.add(LatentDangerStateEnum.安措计划中.getCode());
states.add(LatentDangerStateEnum.待治理.getCode());
states.add(LatentDangerStateEnum.待评审.getCode());
states.add(LatentDangerStateEnum.延期治理申请待车间部门审核.getCode());
states.add(LatentDangerStateEnum.延期治理申请待公司审核.getCode());
}
map.put("states", states);
}
if (!latentDangerListParam.getBelongType().equals(0)) {
map.put("userId", userId);
}
if (!latentDangerListParam.getDangerLevel().equals(-1)) {
map.put("dangerLevel", latentDangerListParam.getDangerLevel());
}
if (!latentDangerListParam.getDangerState().equals(0)) {
map.put("dangerState", latentDangerListParam.getDangerState());
}
if (!StringUtils.isEmpty(latentDangerListParam.getDangerName())) {
map.put("dangerName", latentDangerListParam.getDangerName());
}
return map;
}
@Override
public CommonResponse list(String toke, String product, String appKey, LatentDangerListParam latentDangerListParam, AgencyUserModel user, String loginOrgCode, String deptId) {
JSONObject respBody;
Date startDate = new Date();
if (latentDangerListParam.getIsHandle()) {
respBody = remoteWorkFlowService.completedPageTask(user.getUserName(), latentDangerListParam.getBelongType());
} else {
respBody = remoteWorkFlowService.pageTask(user.getUserId(), latentDangerListParam.getBelongType());
}
Date endDate = new Date();
logger.info("-------------------------工作流列表时间" + (endDate.getTime() - startDate.getTime()));
JSONArray taskJsonList = respBody.getJSONArray("data");
List<JSONObject> taskList = JSONObject.parseArray(taskJsonList.toJSONString(), JSONObject.class);
List<String> bussinessKeys = new ArrayList<>();
for (JSONObject json : taskList) {
bussinessKeys.add(json.getString("businessKey"));
}
if (0 == latentDangerListParam.getBelongType()) {
latentDangerListParam.setUserId(null);
}
if (-1 == latentDangerListParam.getDangerLevel()) {
latentDangerListParam.setDangerLevel(null);
}
if (0 == latentDangerListParam.getDangerState()) {
latentDangerListParam.setDangerState(null);
}
Date startDate1 = new Date();
int dangerListSize = latentDangerMapper.countByBathBusinessKeys(bussinessKeys, latentDangerListParam);
List<LatentDangerBo> dangerList = latentDangerMapper.getByBathBusinessKeys(bussinessKeys, latentDangerListParam);
Date endDate1 = new Date();
logger.info("-------------------------sql时间" + (endDate1.getTime() - startDate1.getTime()));
// Map<String, Object> map = buildQueryMapForList(latentDangerListParam, userId);
// map.put("org_code", loginOrgCode);
// map.put("discoverer_department_id", deptId);
// String permissions = hasProcessBPermission(userId, acctivePermissionType);
// map.put("permissions", permissions);
// List<LatentDangerBo> list = latentDangerMapper.listByMap(map);
// Long count = 0L;
List<LatentDangerListVo> voList = Lists.newArrayList();
Date date = new Date();
if (!CollectionUtils.isEmpty(dangerList)) {
Set<String> userIds = Sets.newHashSet();
dangerList.forEach(e -> userIds.add(e.getDiscovererUserId()));
String userIdsStr = Joiner.on(",").join(userIds);
List<AgencyUserModel> users = remoteSecurityService.listUserByUserIds(toke, product, appKey, userIdsStr);
Map<String, AgencyUserModel> userMap = Maps.uniqueIndex(users, AgencyUserModel::getUserId);
for (LatentDangerBo bo : dangerList) {
JSONObject task = taskList.stream().filter(t -> t.getString("businessKey").equals(bo.getBusinessKey())).collect(Collectors.toList()).get(0);
LatentDangerListVo vo = new LatentDangerListVo();
vo.setTaskId(task.getString("id"));
vo.setDangerId(bo.getId());
vo.setOvertimeState(bo.getOvertimeState());
vo.setDangerName(bo.getDangerName());
vo.setDiscovererUserName(userMap.get(bo.getDiscovererUserId()).getRealName());
vo.setLevel(bo.getDangerLevel());
LatentDangerLevelEnum levelEnum = LatentDangerLevelEnum.getEnumByCode(bo.getDangerLevel());
if (levelEnum != null) {
vo.setLevelDesc(levelEnum.getName());
}
vo.setState(bo.getDangerState());
LatentDangerStateEnum stateEnum = LatentDangerStateEnum.getByCode(bo.getDangerState());
if (stateEnum != null) {
vo.setStateDesc(stateEnum.getName());
}
vo.setLimitDesc(getLimitDesc(bo, date));
voList.add(vo);
}
// count = latentDangerMapper.countByMap(map);
}
// return CommonResponseUtil.success(new PageImpl<>(newList, latentDangerListParam, respBody.getLong("total")));
return CommonResponseUtil.success(new PageImpl<>(voList, latentDangerListParam, dangerListSize));
}
/**
* 获取指定用户具有隐患权限的code
*
* @param userId 指定用户id
* @param permissionType “activitiItem”
* @return permissions 具有隐患权限的code(逗号分割)
*/
private String hasProcessBPermission(String userId, String permissionType) {
String permissions = "";
// 根据用户id和许可类型获取用户所有的授权操作菜单路径("B"、"B_1"、"G_1_1"、"A"、"A_1"、"C".....)
JSONArray jsonArray = remoteSecurityService.getMenuPathByUserIdAndPermissionType(userId, permissionType);
if (CollectionUtils.isEmpty(jsonArray)) {
return "";
}
// 过滤出隐患权限菜单路径("B_1,B_2.....B_10")
Object obj = jsonArray.stream().filter(i -> i.toString().matches("^B_\\d+")).collect(Collectors.toList());
if (StringUtil.isNotEmpty(obj) && ((List<String>) obj).size() > 0) {
permissions = Joiner.on(",").join((List<String>) obj);
}
return permissions;
}
private String getLimitDesc(LatentDangerBo bo, Date start) {
String dangerState = bo.getDangerState();
if (LatentDangerStateEnum.已撤销.getCode().equals(dangerState) || LatentDangerStateEnum.治理完毕.getCode().equals(dangerState)) {
if (bo.getOvertimeState().equals(LatentDangerOvertimeStateEnum.已超时.getCode())) {
return "逾期治理";
} else {
return "按期治理";
}
} else {
Date end = bo.getReformLimitDate();
if (end == null) {
return "";
}
if (bo.getOvertimeState().equals(LatentDangerOvertimeStateEnum.已超时.getCode())) {
return "逾期未治理";
} else {
long betweenSecond = (end.getTime() - start.getTime()) / 1000;
if (betweenSecond < 0) {
return "逾期未治理";
} else {
String str = "";
if (betweenSecond > 3600) {
long hour = betweenSecond / 3600;
str += hour + "时";
betweenSecond = betweenSecond % 3600;
}
if (betweenSecond > 60) {
long minute = betweenSecond / 60;
str += minute + "分";
betweenSecond = betweenSecond % 60;
}
if (betweenSecond > 0) {
str += betweenSecond + "秒";
}
return str;
}
}
}
}
@Transactional(rollbackFor = Exception.class)
@Override
public DangerExecuteSubmitDto execute(LatentDangerExecuteParam latentDangerExecuteParam, String userId, String userRealName, String departmentId, String departmentName, RoleBo role) {
DangerExecuteSubmitDto executeSubmitDto = new DangerExecuteSubmitDto();
LatentDanger latentDanger = latentDangerMapper.selectById(latentDangerExecuteParam.getDangerId());
if (ValidationUtil.isEmpty(latentDanger)) {
executeSubmitDto.setIsOk(false);
executeSubmitDto.setMsg("隐患不存在");
return executeSubmitDto;
}
DangerExecuteSubmitDto dangerExecuteSubmitDto = executeSubmit(latentDangerExecuteParam, latentDanger, userId, userRealName, departmentId, departmentName, executeSubmitDto, role);
try {
if (dangerExecuteSubmitDto.getIsOk()) {
webMqttComponent.publish(dangerTopic, "");
}
} catch (Exception e) {
logger.error("隐患执行结果推送失败-----------" + e.getMessage());
}
return dangerExecuteSubmitDto;
}
@Override
public CommonResponse detail(String id, String userId, boolean isFinish) {
JSONObject jsonObject;
if (isFinish) {
jsonObject = remoteWorkFlowService.queryFinishTaskDetail(id);
} else {
jsonObject = remoteWorkFlowService.queryTaskDetail(id);
}
JSONObject task = jsonObject.getJSONObject("data");
LatentDangerBo latentDangerBo = latentDangerMapper.getbyBusinessKey(task.getString("businessKey"));
LatentDangerDetailVo detailVo = new LatentDangerDetailVo();
if (latentDangerBo != null) {
detailVo.setDangerId(latentDangerBo.getId());
detailVo.setDangerType(latentDangerBo.getDangerType());
if (StringUtils.isEmpty(latentDangerBo.getDangerPosition())) {
detailVo.setPosition(latentDangerBo.getStructureName());
} else {
detailVo.setPosition(latentDangerBo.getStructureName() + "·" + latentDangerBo.getDangerPosition());
}
detailVo.setDangerState(latentDangerBo.getDangerState());
detailVo.setProblemDescription(latentDangerBo.getProblemDescription());
detailVo.setReasonAnalysis(latentDangerBo.getReasonAnalysis());
detailVo.setInferOtherThings(latentDangerBo.getInferOtherThings());
detailVo.setProblemDescription(latentDangerBo.getProblemDescription());
LatentDangerStateEnum dangerStateEnum = LatentDangerStateEnum.getByCode(latentDangerBo.getDangerState());
if (dangerStateEnum != null) {
detailVo.setDangerStateDesc(dangerStateEnum.getName());
}
detailVo.setDangerName(latentDangerBo.getDangerName());
detailVo.setLevel(latentDangerBo.getDangerLevel());
LatentDangerLevelEnum levelEnum = LatentDangerLevelEnum.getEnumByCode(latentDangerBo.getDangerLevel());
if (levelEnum != null) {
detailVo.setLevelDesc(levelEnum.getName());
}
detailVo.setRemark(latentDangerBo.getRemark());
if (latentDangerBo.getReformType() != null) {
LatentDangerReformTypeEnum typeEnum = LatentDangerReformTypeEnum.getEnumByCode(latentDangerBo.getReformType());
if (typeEnum != null) {
detailVo.setReformTypeDesc(typeEnum.getName());
}
}
if (latentDangerBo.getReformLimitDate() != null) {
detailVo.setReformLimitDate(DateUtil.date2Str(latentDangerBo.getReformLimitDate(), DateUtil.DATETIME_DEFAULT_FORMAT));
}
if (latentDangerBo.getDelayLimitDate() != null) {
detailVo.setDelayLimitDate(DateUtil.date2Str(latentDangerBo.getDelayLimitDate(),
DateUtil.DATETIME_DEFAULT_FORMAT));
}
detailVo.setCurrentFlowRecordId(latentDangerBo.getCurrentFlowRecordId());
if (!StringUtils.isEmpty(latentDangerBo.getReformJson())) {
detailVo.setReformJson(JSONObject.parseObject(latentDangerBo.getReformJson()));
}
if (!StringUtils.isEmpty(latentDangerBo.getPhotoUrls())) {
List<String> photoUrls = Lists.newArrayList(latentDangerBo.getPhotoUrls().split(","));
detailVo.setPhotoUrls(photoUrls);
}
buildOfDifferentDangerType(latentDangerBo, detailVo);
detailVo.setTaskId(task.getString("id"));
}
return CommonResponseUtil.success(detailVo);
}
/**
* 根据隐患类型填充隐患对象属性(计划检查和无计划检查填充图片及风险点信息)
*
* @param latentDangerBo
* @param detailVo
*/
private void buildOfDifferentDangerType(LatentDangerBo latentDangerBo, LatentDangerDetailVo detailVo) {
if (latentDangerBo.getDangerType().equals(LatentDangerTypeEnum.计划检查.getCode())
|| latentDangerBo.getDangerType().equals(LatentDangerTypeEnum.无计划检查.getCode())) {
LatentDangerPatrolBo patrolBo = latentDangerPatrolMapper.getByDangerId(latentDangerBo.getId());
if (patrolBo != null) {
LatentDangerDetailRiskVo riskVo = new LatentDangerDetailRiskVo();
List<String> basis = new ArrayList<>();
if (!StringUtils.isEmpty(patrolBo.getItemBasis())) {
basis.add(patrolBo.getItemBasis());
}
riskVo.setBasis(basis);
riskVo.setPointName(patrolBo.getPointName());
riskVo.setPointNo(patrolBo.getPointNo());
riskVo.setPointLevel(StringUtil.isNotEmpty(patrolBo.getPointLevel()) ? patrolBo.getPointLevel() : "");
riskVo.setPlanName(patrolBo.getPlanName());
riskVo.setCheckTime(patrolBo.getCheckTime());
AgencyUserModel checkUser = remoteSecurityService.getUserById(RequestContext.getToken(), getProduct(), RequestContext.getAppKey(), patrolBo.getCheckUserId());
if (StringUtil.isNotEmpty(checkUser)) {
riskVo.setCheckUser(checkUser.getRealName());
}
// TODO 使用远程调用替换
// RiskFactorBo riskFactorBo = StringUtil.isNotEmpty(patrolBo.getClassifyOriginalId()) ? riskFactorMapper.getById(Long.valueOf(patrolBo.getClassifyOriginalId())) : null;
// if (riskFactorBo != null && riskFactorBo.getEquipmentDepartmentId() != null) {
// DepartmentModel department = remoteSecurityService.getDepartmentByDeptId(RequestContext.getToken(), getProduct(), RequestContext.getAppKey(), riskFactorBo.getEquipmentDepartmentId().toString());
// if (department != null) {
// riskVo.setBelongDepartmentName(department.getDepartmentName());
// }
// }
// List<CheckShot> checkShots = iCheckShotDao.findAllByCheckIdAndCheckInputId(patrolBo.getCheckId(),
// latentDangerBo.getCheckInputId());
// if (!CollectionUtils.isEmpty(checkShots)) {
// List<String> photos = Lists.transform(checkShots, e -> {
// if (e != null) {
// return fileServerAddress + e.getPhotoData().replaceAll("\\\\", "/");
// } else {
// return "";
// }
// });
// detailVo.setPhotoUrls(photos);
// }
detailVo.setRiskInfo(riskVo);
}
}
}
@Override
public CommonResponse getByInstanceId(String instanceId) {
LatentDangerBo latentDangerBo = latentDangerMapper.getByInstanceId(instanceId);
if (latentDangerBo == null) {
return CommonResponseUtil.failure("隐患不存在");
}
JSONObject result = new JSONObject();
JSONObject baseInfo = new JSONObject();
JSONObject reviewInfo = new JSONObject();
JSONObject dangerInfo = new JSONObject();
Set<String> userIds = Sets.newHashSet();
userIds.add(latentDangerBo.getDiscovererUserId());
LatentDangerPatrolBo patrolBo = null;
if (latentDangerBo.getDangerType().equals(LatentDangerTypeEnum.计划检查.getCode())) {
patrolBo = latentDangerPatrolMapper.getByDangerId(latentDangerBo.getId());
JSONArray checkTypeArray = remoteSecurityService.listDictionaryByDictCode(RequestContext.getToken(), getProduct(),
RequestContext.getAppKey(), Constants.CHECK_TYPE);
Map<String, String> checkTypeMap = Maps.newHashMap();
for (int i = 0; i < checkTypeArray.size(); i++) {
JSONObject categoryJson = checkTypeArray.getJSONObject(i);
checkTypeMap.put(categoryJson.getString("dictDataKey"), categoryJson.getString("dictDataValue"));
}
if (patrolBo != null) {
// TODO 使用远程调用替换
// PointClassify classify = iPointClassifyDao.getOne(patrolBo.getPointClassifyId());
// RiskFactorBo riskFactorBo = riskFactorMapper.getById(Long.valueOf(classify.getOriginalId()));
String jsonStr = patrolBo.getItemBasis();
String itemBasis = "";
if (!StringUtils.isEmpty(jsonStr)) {
StringBuilder itemBasisBuilder = new StringBuilder();
JSONArray arr = JSONArray.parseArray(jsonStr);
for (int i = 0; i < arr.size(); i++) {
JSONObject object = arr.getJSONObject(i);
itemBasisBuilder.append(object.getString("name")).append(",");
}
itemBasis = itemBasisBuilder.length() > 0 ? itemBasisBuilder.substring(0, itemBasisBuilder.length() - 1) : itemBasis;
}
// if (riskFactorBo != null) {
if (true) {
userIds.add(patrolBo.getCheckUserId());
dangerInfo.put("type", "设备设施类");
// TODO 使用远程调用替换
// dangerInfo.put("equipmentCode", riskFactorBo.getEquipmentCode());
dangerInfo.put("isCheckWithPlan", "是");
dangerInfo.put("planName", patrolBo.getPlanName());
dangerInfo.put("planType", checkTypeMap.get(patrolBo.getCheckType()));
dangerInfo.put("routeName", patrolBo.getRouteName());
dangerInfo.put("classifyName", patrolBo.getClassifyName());
dangerInfo.put("itemName", patrolBo.getItemName());
dangerInfo.put("itemBasis", itemBasis);
dangerInfo.put("itemRemark", patrolBo.getItemRemark());
dangerInfo.put("checkTime", DateUtil.str2Date(patrolBo.getCheckTime(), DateUtil.DATETIME_DEFAULT_FORMAT));
}
}
}
LatentDangerFlowRecordBo reviewRecordBo = latentDangerFlowRecordMapper.getByDangerIdAndActionFlag(latentDangerBo.getId(), "B_2");
LatentDangerFlowRecordBo reformRecordBo = latentDangerFlowRecordMapper.getByDangerIdAndActionFlag(latentDangerBo.getId(), "B_3");
if (reviewRecordBo != null) {
userIds.add(reviewRecordBo.getExecuteUserId());
}
if (reformRecordBo != null) {
userIds.add(reformRecordBo.getExecuteUserId());
}
userIds.removeAll(Collections.singleton(null));
List<AgencyUserModel> userModels = remoteSecurityService.listUserByUserIds(Joiner.on(",").join(userIds));
Map<String, AgencyUserModel> userMap = Maps.uniqueIndex(userModels, AgencyUserModel::getUserId);
AgencyUserModel user = userMap.get(latentDangerBo.getDiscovererUserId());
baseInfo.put("orderNo", latentDangerBo.getBusinessKey());
baseInfo.put("startTime", latentDangerBo.getCreateDate());
if (user != null) {
baseInfo.put("userName", user.getRealName());
}
DepartmentBo departmentBo = remoteSecurityService.getDepartmentByDeptId(latentDangerBo.getDiscovererDepartmentId());
if (departmentBo != null) {
baseInfo.put("department", departmentBo.getDepartmentName());
}
LatentDangerLevelEnum levelEnum = LatentDangerLevelEnum.getEnumByCode(latentDangerBo.getDangerLevel());
if (levelEnum != null) {
dangerInfo.put("latentDangerLevel", levelEnum.getName());
}
dangerInfo.put("latentDangerName", latentDangerBo.getDangerName());
if (!StringUtils.isEmpty(latentDangerBo.getReformJson())) {
String str = JSONObject.parseObject(latentDangerBo.getReformJson()).getString("rectMeasures");
dangerInfo.put("reformJson", str.replace("\\n", "\\\\n"));
}
dangerInfo.put("reformLimitDate", latentDangerBo.getReformLimitDate());
if (reformRecordBo != null) {
AgencyUserModel reformUser = userMap.get(reformRecordBo.getExecuteUserId());
if (reformUser != null) {
dangerInfo.put("reformUserName", reformUser.getRealName());
}
}
if (patrolBo != null) {
if (patrolBo.getCheckUserId() != null) {
AgencyUserModel checkUser = userMap.get(patrolBo.getCheckUserId());
if (checkUser != null) {
dangerInfo.put("checkUserName", checkUser.getRealName());
}
}
if (patrolBo.getCheckDepartmentId() != null) {
DepartmentBo checkDepartment = remoteSecurityService.getDepartmentByDeptId(patrolBo.getCheckDepartmentId());
if (checkDepartment != null) {
dangerInfo.put("checkUserDeptName", checkDepartment.getDepartmentName());
}
}
}
if (reviewRecordBo != null) {
AgencyUserModel reviewUser = userMap.get(reviewRecordBo.getExecuteUserId());
reviewInfo.put("reviewUserName", StringUtil.isNotEmpty(reviewUser) ? reviewUser.getRealName() : "");
reviewInfo.put("reviewDate", StringUtil.isNotEmpty(reviewUser) ? reviewRecordBo.getUpdateDate() : "");
reviewInfo.put("reviewResult", StringUtil.isNotEmpty(reviewUser) ? reviewRecordBo.getExecuteResult() : "");
}
result.put("baseInfo", baseInfo);
result.put("dangerInfo", dangerInfo);
result.put("reviewInfo", reviewInfo);
result.put("latentDangerType", latentDangerBo.getDangerType());
LatentDangerTypeEnum typeEnum = LatentDangerTypeEnum.getByCode(latentDangerBo.getDangerType());
if (typeEnum != null) {
result.put("latentDangerTypeDesc", typeEnum.getName());
}
return CommonResponseUtil.success(result);
}
@Transactional
@Override
public DangerExecuteSubmitDto executeCallBack(String instanceId, Integer actionType, String remark, String token,
String userId, String userRealName, String departmentId, String departmentName) {
DangerExecuteSubmitDto executeSubmitDto = new DangerExecuteSubmitDto();
executeSubmitDto.setIsOk(true);
LatentDanger latentDanger =
latentDangerMapper.selectOne(new LambdaQueryWrapper<LatentDanger>().eq(LatentDanger::getInstanceId,
instanceId));
if (latentDanger != null) {
LatentDangerFlowRecordBo currentRecord = latentDangerFlowRecordMapper.getById(latentDanger.getCurrentFlowRecordId());
if (actionType.equals(1)) {
//通过
LatentDangerExecuteTypeEnum executeTypeEnum = LatentDangerExecuteTypeEnum.公司负责人审核通过;
updateFlowRecord(currentRecord, executeTypeEnum, userId, departmentId, remark, null);
JSONObject flowJson = remoteWorkFlowService.allTasksInProcessInstanceId(latentDanger.getInstanceId());
if (flowJson == null) {
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
return executeSubmitDto;
}
LatentDangerPatrolBo patrolBo = null;
String userIds;
if (latentDanger.getDangerType().equals(LatentDangerTypeEnum.计划检查.getCode())) {
patrolBo = latentDangerPatrolMapper.getByDangerId(latentDanger.getId());
userIds = Joiner.on(",").join(getUserIdsStrByPerTypeAndDefKey(flowJson));
} else {
LatentDangerFlowRecordBo recordBo = latentDangerFlowRecordMapper.getByDangerIdAndActionFlag(latentDanger.getId(), "B_8");
userIds = recordBo.getFlowTaskUserIds();
}
LatentDangerFlowRecordBo record = saveFlowRecord(flowJson.getString("id"), userIds,
flowJson.getString("name"), flowJson.getString("taskDefinitionKey"), latentDanger.getId());
latentDanger.setCurrentFlowRecordId(record.getId());
latentDanger.setDangerState(executeTypeEnum.getNextState().getCode().toString());
latentDangerMapper.updateById(latentDanger);
///web推送刷新消息
// dangerStateChangeWebSockte(latentDangerBo);
// Set<String> nextExecuteUserIds = Sets.newHashSet(Arrays.asList(userIds.split(",")));
sendMessage(latentDanger, executeTypeEnum, patrolBo, currentRecord.getFlowTaskName(), this.getNextExecuteUsers(latentDanger.getInstanceId()), userRealName, departmentName);
} else if (actionType.equals(2)) {
//终止
latentDanger.setDangerState(LatentDangerStateEnum.已撤销.getCode().toString());
latentDangerMapper.updateById(latentDanger);
if (latentDanger.getDangerType().equals(LatentDangerTypeEnum.计划检查.getCode())) {
LatentDangerPatrolBo patrolBo = latentDangerPatrolMapper.getByDangerId(latentDanger.getId());
if (patrolBo.getClassifyOriginalId() != null && patrolBo.getItemOriginalId() != null) {
// updateMeasuresContentStatus(Long.valueOf(patrolBo.getClassifyOriginalId()), Long.valueOf(patrolBo.getItemOriginalId()),
// patrolBo.getRiskFactorFlowId(), RiskFactorsCmStatusEnum.Control);
}
LatentDangerLevelEnum levelEnum = LatentDangerLevelEnum.getEnumByCode(latentDanger.getDangerLevel());
if (levelEnum != null) {
updateRiskSourceDangerState(false, Long.valueOf(patrolBo.getPointOriginalId()), levelEnum, patrolBo.getPointId(), latentDanger.getId());
}
executeSubmitDto.setDangerId(latentDanger.getId());
executeSubmitDto.setDangerName(latentDanger.getDangerName());
executeSubmitDto.setPointOriginalId(patrolBo.getPointOriginalId());
executeSubmitDto.setPointId(patrolBo.getPointId());
executeSubmitDto.setExecuteTypeEnum(LatentDangerExecuteTypeEnum.隐患评审拒绝);
}
} else if (actionType.equals(3)) {
//拒绝
LatentDangerExecuteTypeEnum executeTypeEnum = LatentDangerExecuteTypeEnum.公司负责人审核拒绝;
updateFlowRecord(currentRecord, executeTypeEnum, userId, departmentId, remark, null);
JSONObject flowJson = remoteWorkFlowService.allTasksInProcessInstanceId(latentDanger.getInstanceId());
if (flowJson == null) {
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
return executeSubmitDto;
}
LatentDangerPatrolBo patrolBo = null;
String userIds;
if (latentDanger.getDangerType().equals(LatentDangerTypeEnum.计划检查.getCode())) {
patrolBo = latentDangerPatrolMapper.getByDangerId(latentDanger.getId());
userIds = Joiner.on(",").join(getUserIdsStrByPerTypeAndDefKey(flowJson));
} else {
LatentDangerFlowRecordBo recordBo = latentDangerFlowRecordMapper.getByDangerIdAndActionFlag(latentDanger.getId(), "B_3");
userIds = recordBo.getFlowTaskUserIds();
}
LatentDangerFlowRecordBo record = saveFlowRecord(flowJson.getString("id"), userIds,
flowJson.getString("name"), flowJson.getString("taskDefinitionKey"), latentDanger.getId());
latentDanger.setCurrentFlowRecordId(record.getId());
latentDanger.setDangerState(executeTypeEnum.getNextState().getCode().toString());
latentDangerMapper.updateById(latentDanger);
///web推送刷新消息
// dangerStateChangeWebSocket(latentDangerBo);
// Set<String> nextExecuteUserIds = Sets.newHashSet(Arrays.asList(userIds.split(",")));
sendMessage(latentDanger, executeTypeEnum, patrolBo, currentRecord.getFlowTaskName(), this.getNextExecuteUsers(latentDanger.getInstanceId()), userRealName, departmentName);
}
}
return executeSubmitDto;
}
@Override
public void updateDangerStateOfOvertime() {
logger.info("修改治理过期隐患的逾期状态");
List<LatentDangerBo> overtimeList = latentDangerMapper.listOfOvertime();
for (LatentDangerBo latentDangerBo : overtimeList) {
latentDangerBo.setOvertimeState(LatentDangerOvertimeStateEnum.已超时.getCode());
latentDangerMapper.update(latentDangerBo);
if (latentDangerBo.getDangerType().equals(LatentDangerTypeEnum.计划检查.getCode())) {
// TODO 远程调用修改
LatentDangerPatrolBo patrolBo = latentDangerPatrolMapper.getByDangerId(latentDangerBo.getId());
LatentDangerResultPushSpcRequest spcRequest = new LatentDangerResultPushSpcRequest();
spcRequest.setProcessingTime(DateUtil.date2Str(new Date(), DateUtil.DATETIME_DEFAULT_FORMAT));
spcRequest.setHiddenTroubleName(latentDangerBo.getDangerName());
spcRequest.setRiskSourceId(patrolBo.getPointOriginalId());
spcRequest.setHiddenTroubleStatus("治理逾期");
spcRequest.setTroubleList(getTroubleList(patrolBo.getPointId()));
remoteSpcService.pushLatentDangerExecuteResult(spcRequest);
}
}
//推送页面刷新
// remoteWebSocketServer.wsDataRefresh("dangerOverdue");
// 即将逾期的隐患发送消息提醒用户
List<LatentDangerNoticeBo> needNoticeDangerList = latentDangerMapper.listNeedNoticeDanger();
if (!CollectionUtils.isEmpty(needNoticeDangerList)) {
logger.info("隐患治理即将逾期通知》》》》");
needNoticeDangerList.forEach(danger -> {
asyncTask.pushLatentDangerReformLimitDateExpireMessage(this.getNextExecuteUsers(danger.getInstanceId()),
danger.getOrgCode(),
danger.getDangerName(), DateUtil.date2Str(danger.getReformLimitDate(), DateUtil.DATETIME_DEFAULT_FORMAT),
danger.getDangerId(),
danger.getDangerState(), "");
});
}
}
/**
* web安全态势预控 ( 隐患按车间/部门统计) 模块推送刷新消息
*/
private void dangerStateChangeWebSocket(LatentDangerBo latentDangerBo) {
String state = latentDangerBo.getDangerState();
String type = latentDangerBo.getDangerType();
if (LatentDangerTypeEnum.计划检查.getCode().equals(type)
|| LatentDangerTypeEnum.无计划检查.getCode().equals(type)) {
if (LatentDangerStateEnum.待治理.getCode().equals(state)
// || LatentDangerStateEnum.安措计划中.getCode().equals(state)
|| LatentDangerStateEnum.待验证.getCode().equals(state)) {
remoteWebSocketServer.wsDataRefresh("dangerExecute");
}
}
}
@Override
public CommonResponse listFlowRecord(String token, String product, String appKey, Long id) {
LatentDangerBo latentDangerBo = latentDangerMapper.getById(id);
if (latentDangerBo == null) {
return CommonResponseUtil.failure("隐患不存在");
}
LatentDangerDetailVo detailVo = new LatentDangerDetailVo();
detailVo.setDangerName(latentDangerBo.getDangerName());
detailVo.setLevel(latentDangerBo.getDangerLevel());
detailVo.setPosition(latentDangerBo.getStructureName());
LatentDangerLevelEnum levelEnum = LatentDangerLevelEnum.getEnumByCode(latentDangerBo.getDangerLevel());
if (levelEnum != null) {
detailVo.setLevelDesc(levelEnum.getName());
}
List<LatentDangerFlowRecordBo> records = latentDangerFlowRecordMapper.listByDangerId(latentDangerBo.getId());
if (!CollectionUtils.isEmpty(records)) {
Set<String> userIds = Sets.newHashSet();
Set<String> deptIds = Sets.newHashSet();
records.forEach(e -> {
if (!StringUtils.isEmpty(e.getExecuteUserId())) {
userIds.add(e.getExecuteUserId());
}
if (!StringUtils.isEmpty(e.getExcuteDepartmentId())) {
deptIds.add(e.getExcuteDepartmentId());
}
});
List<DepartmentModel> departmentBos = remoteSecurityService.getlistDepartmentByDeptIds(token, product, appKey, Joiner.on(",").join(deptIds));
List<AgencyUserModel> userModels = remoteSecurityService.listUserByUserIds(token, product, appKey, Joiner.on(",").join(userIds));
Map<String, AgencyUserModel> userMap = Maps.uniqueIndex(userModels, AgencyUserModel::getUserId);
Map<Long, DepartmentModel> departmentBoMap = Maps.uniqueIndex(departmentBos, DepartmentModel::getSequenceNbr);
for (LatentDangerFlowRecordBo recordBo : records) {
AgencyUserModel user = userMap.get(recordBo.getExecuteUserId());
if (user != null) {
recordBo.setExecuteUserName(user.getRealName());
}
DepartmentModel departmentBo = departmentBoMap.get(recordBo.getExcuteDepartmentId());
if (departmentBo != null) {
recordBo.setExecuteDepartmentName(departmentBo.getDepartmentName());
}
recordBo.setExecuteTime(DateUtil.date2Str(recordBo.getCreateDate(), DateUtil.DATETIME_DEFAULT_FORMAT));
}
detailVo.setRecords(records);
}
return CommonResponseUtil.success(detailVo);
}
/**
* 工作流执行节点操作
*
* @param param
* @param latentDanger
* @param userId
* @param userRealName
* @param departmentId
* @param departmentName
* @param executeSubmitDto
* @param role
* @return
*/
public DangerExecuteSubmitDto executeSubmit(LatentDangerExecuteParam param,
LatentDanger latentDanger,
String userId,
String userRealName,
String departmentId,
String departmentName,
DangerExecuteSubmitDto executeSubmitDto,
RoleBo role) {
// 根据业务类型不同执行不同逻辑
if (StringUtil.isNotEmpty(param.getReformLimitDate())) {
param.setReformLimitDate(param.getReformLimitDate() + " 23:59:59");
}
LatentDangerExecuteTypeEnum executeTypeEnum = LatentDangerExecuteTypeEnum.getByCode(param.getExecuteType());
if (executeTypeEnum == null) {
executeSubmitDto.setIsOk(false);
executeSubmitDto.setMsg("执行类型有误");
return executeSubmitDto;
}
// 延期治理时,根据用户选择是否需要公司来构造参数调用工作流
if (StringUtil.isNotEmpty(param.getNeedCompanyVerify())
&& executeTypeEnum.equals(LatentDangerExecuteTypeEnum.隐患延期治理车间部门审核通过)) {
String requestBody = "";
if (param.getNeedCompanyVerify() == 0) {// 延期治理申请 不需要公司审核
requestBody = "{\"needCompanyApproval\": \"否\",\"approveResult\": \"通过\"}";
} else {// 延期治理申请 需要公司审核
requestBody = "{\"needCompanyApproval\": \"是\",\"approveResult\": \"通过\"}";
}
executeTypeEnum.setRequestBody(requestBody);
}
// 延期治理选择的延期日期不能早于整改日期校验
if (executeTypeEnum.equals(LatentDangerExecuteTypeEnum.隐患延期治理)) {
if (latentDanger.getReformLimitDate().compareTo(DateUtil.longStr2Date(param.getDelayLimitDate())) >= 0) {
executeSubmitDto.setIsOk(false);
executeSubmitDto.setMsg("延期日期不能早于整改期限");
return executeSubmitDto;
}
}
JSONObject executeJson = remoteWorkFlowService.execute(param.getTaskId(), executeTypeEnum.getRequestBody());
if (executeJson == null) {
executeSubmitDto.setIsOk(false);
executeSubmitDto.setMsg("执行失败");
return executeSubmitDto;
}
LatentDangerPatrolBo patrolBo = null;
if (latentDanger.getDangerType().equals(LatentDangerTypeEnum.计划检查.getCode())) {
patrolBo = latentDangerPatrolMapper.getByDangerId(latentDanger.getId());
}
JSONObject data = executeJson.getJSONObject("data");
if (executeTypeEnum.getNextState().equals(LatentDangerStateEnum.已撤销)) {
latentDanger.setDangerState(executeTypeEnum.getNextState().getCode().toString());
saveFlowRecord(executeJson.getString("id"), data.getString("name"), userId, departmentId,
param.getFlowJson(), param.getDangerId(), role, executeTypeEnum.getName(), param.getRemark());
} else if (executeTypeEnum.getNextState().equals(LatentDangerStateEnum.治理完毕)) {
latentDanger.setDangerState(executeTypeEnum.getNextState().getCode().toString());
saveFlowRecord(executeJson.getString("id"), data.getString("name"), userId, departmentId,
param.getFlowJson(), param.getDangerId(), role, executeTypeEnum.getName(), param.getRemark());
} else {
LatentDangerFlowRecord flowRecord = saveFlowRecord(executeJson.getString("id"), data.getString("name"), userId, departmentId,
param.getFlowJson(), param.getDangerId(), role, executeTypeEnum.getName(), param.getRemark());
latentDanger.setCurrentFlowRecordId(flowRecord.getId());
latentDanger.setDangerState(executeTypeEnum.getNextState().getCode().toString());
if (executeTypeEnum.equals(LatentDangerExecuteTypeEnum.隐患常规治理)) {
latentDanger.setReformType(LatentDangerReformTypeEnum.常规整改.getCode().toString());
latentDanger.setReformJson(param.getFlowJson().toJSONString());
latentDanger.setInferOtherThings(param.getInferOtherThings());
latentDanger.setProblemDescription(param.getReasonAnalysis());
latentDanger.setReasonAnalysis(param.getRemark());
} else if (executeTypeEnum.equals(LatentDangerExecuteTypeEnum.隐患延期治理)) {
latentDanger.setReformType(LatentDangerReformTypeEnum.延期治理.getCode().toString());
latentDanger.setReformJson(param.getFlowJson().toJSONString());
latentDanger.setInferOtherThings(param.getInferOtherThings());
latentDanger.setProblemDescription(param.getReasonAnalysis());
latentDanger.setReasonAnalysis(param.getRemark());
latentDanger.setDelayLimitDate(DateUtil.str2Date(param.getDelayLimitDate(), DateUtil.DATETIME_DEFAULT_FORMAT));
}
if (executeTypeEnum.equals(LatentDangerExecuteTypeEnum.隐患评审通过)) {
latentDanger.setReformLimitDate(DateUtil.str2Date(param.getReformLimitDate(), DateUtil.DATETIME_DEFAULT_FORMAT));
latentDanger.setDangerLevel(param.getDangerLevel());
}
}
if (executeTypeEnum.equals(LatentDangerExecuteTypeEnum.隐患延期治理车间部门审核通过)) {
// 延期治理评审通过且 不需要 公司审核
if (param.getNeedCompanyVerify() == 0) {
latentDanger.setDangerState(LatentDangerStateEnum.延期治理申请.getCode().toString());
latentDanger.setReformLimitDate(latentDanger.getDelayLimitDate());
} else {// 延期治理评审通过且 需要 公司审核
latentDanger.setDangerState(LatentDangerStateEnum.延期治理申请待公司审核.getCode().toString());
LatentDangerFlowRecordBo recordBo =
latentDangerFlowRecordMapper.getByDangerIdAndCreate(latentDanger.getId());
String flowJsonStr = recordBo.getFlowJson();
JSONObject flowJson = JSONObject.parseObject(flowJsonStr);
flowJson.put("needCompanyVerify", param.getNeedCompanyVerify());
recordBo.setFlowJson(flowJson.toJSONString());
latentDangerFlowRecordMapper.update(recordBo);
}
} else if (executeTypeEnum.equals(LatentDangerExecuteTypeEnum.隐患延期治理车间部门审核拒绝)) {
latentDanger.setDangerState(LatentDangerStateEnum.待治理.getCode().toString());
} else if (executeTypeEnum.equals(LatentDangerExecuteTypeEnum.隐患延期治理公司审核通过)) {
latentDanger.setDangerState(LatentDangerStateEnum.延期治理申请.getCode().toString());
latentDanger.setReformLimitDate(latentDanger.getDelayLimitDate());
} else if (executeTypeEnum.equals(LatentDangerExecuteTypeEnum.隐患延期治理公司审核拒绝)) {
latentDanger.setDangerState(LatentDangerStateEnum.延期治理申请待车间部门审核.getCode().toString());
}
latentDangerMapper.updateById(latentDanger);
if (patrolBo != null) {
executeSubmitDto.setPointOriginalId(patrolBo.getPointOriginalId());
executeSubmitDto.setPointId(patrolBo.getPointId());
}
executeSubmitDto.setIsOk(true);
executeSubmitDto.setExecuteTypeEnum(executeTypeEnum);
executeSubmitDto.setDangerName(latentDanger.getDangerName());
executeSubmitDto.setDangerId(latentDanger.getId());
sendMessage(latentDanger, executeTypeEnum, patrolBo, executeTypeEnum.getName(), this.getNextExecuteUsers(latentDanger.getInstanceId()), userRealName, departmentName);
return executeSubmitDto;
}
private void sendMessage(LatentDanger latentDanger, LatentDangerExecuteTypeEnum executeTypeEnum,
LatentDangerPatrolBo patrolBo, String flowTaskName, String informerList,
String userRealName, String departmentName) {
if (LatentDangerBizTypeEnum.巡检.getCode().equals(latentDanger.getBizType())) {
// 巡检流程消息处理
sendPatrolDangerMessage(latentDanger, executeTypeEnum, patrolBo, flowTaskName, informerList, userRealName, departmentName);
} else if (LatentDangerBizTypeEnum.防火监督.getCode().equals(latentDanger.getBizType())) {
// TODO 防火监督消息处理
sendSupervisionDangerMessage(latentDanger, executeTypeEnum, patrolBo, flowTaskName, informerList, userRealName, departmentName);
}
}
// 巡检流程消息处理
private void sendPatrolDangerMessage(LatentDanger latentDanger, LatentDangerExecuteTypeEnum executeTypeEnum, LatentDangerPatrolBo patrolBo, String flowTaskName, String informerList, String userRealName, String departmentName) {
try {
if (executeTypeEnum.equals(LatentDangerExecuteTypeEnum.隐患评审拒绝)) {
String pointName = null;
if (patrolBo != null) {
pointName = patrolBo.getPointName();
}
Set<String> sendUserIds = Sets.newHashSet(latentDanger.getDiscovererUserId());
asyncTask.pushLatentDangerExecuteMessage(informerList, latentDanger.getOrgCode(),
latentDanger.getDangerName(), pointName,
departmentName, latentDanger.getId(), userRealName,
flowTaskName, ExecuteStateEnum.驳回.getName(),
DateUtil.date2Str(new Date(), DateUtil.DATETIME_DEFAULT_FORMAT),
Integer.valueOf(latentDanger.getDangerState()));
} else if (executeTypeEnum.equals(LatentDangerExecuteTypeEnum.隐患验证通过)) {
if (patrolBo != null) {
// TODO 使用远程调用替换 更新p_check_input表state字段
updateCheckInputDangerState(latentDanger.getBizId(), DangerHandleStateEnum.COMPLETED.getCode());
DangerResultBo dangerResultBo = new DangerResultBo();
try {
// business.processProtalDataFromDanger(dangerResultBo);
} catch (Exception e) {
throw new RuntimeException("隐患治理完成调用站端接口出错!");
}
}
} else {
String pointName = null;
if (patrolBo != null) {
pointName = patrolBo.getPointName();
}
asyncTask.pushLatentDangerExecuteMessage(informerList, latentDanger.getOrgCode(),
latentDanger.getDangerName(), pointName,
departmentName, latentDanger.getId(), userRealName,
flowTaskName, executeTypeEnum.getExecuteState().getName(),
DateUtil.date2Str(new Date(), DateUtil.DATETIME_DEFAULT_FORMAT),
Integer.valueOf(latentDanger.getDangerState()));
if (executeTypeEnum.equals(LatentDangerExecuteTypeEnum.隐患评审通过)) {
// 隐患治理到期时间为当天,则立即提示消息
Date reformLimitDate = latentDanger.getReformLimitDate();
if (DateUtil.getDateFormat(new Date()).equals(DateUtil.getDateFormat(reformLimitDate))) {
asyncTask.pushLatentDangerReformLimitDateExpireMessage(informerList,
latentDanger.getOrgCode(), latentDanger.getDangerName(),
DateUtil.date2Str(latentDanger.getReformLimitDate(), DateUtil.DATETIME_DEFAULT_FORMAT),
latentDanger.getId(),
Integer.valueOf(latentDanger.getDangerState()), userRealName);
}
}
}
} catch (Exception e) {
logger.error("隐患执行发送消息失败", e);
}
}
// 防火监督流程消息处理
private void sendSupervisionDangerMessage(LatentDanger latentDanger, LatentDangerExecuteTypeEnum executeTypeEnum,
LatentDangerPatrolBo patrolBo, String flowTaskName, String informerList, String userRealName, String departmentName) {
}
@Async
@Override
public void sendLatentDangerExecuteResult(DangerExecuteSubmitDto executeSubmitDto) {
LatentDangerExecuteTypeEnum executeTypeEnum = executeSubmitDto.getExecuteTypeEnum();
String dangerName = executeSubmitDto.getDangerName();
String pointOriginalId = executeSubmitDto.getPointOriginalId();
Long pointId = executeSubmitDto.getPointId();
String status = null;
if (executeTypeEnum.equals(LatentDangerExecuteTypeEnum.隐患评审通过)) {
status = "隐患评审通过";
} else if (executeTypeEnum.equals(LatentDangerExecuteTypeEnum.隐患评审拒绝)) {
status = "隐患评审不通过";
} else if (executeTypeEnum.equals(LatentDangerExecuteTypeEnum.隐患验证拒绝)) {
status = "治理验证不通过";
} else if (executeTypeEnum.equals(LatentDangerExecuteTypeEnum.隐患验证通过)) {
status = "治理验证完成";
}
if (status != null) {
LatentDangerResultPushSpcRequest spcRequest = new LatentDangerResultPushSpcRequest();
spcRequest.setProcessingTime(DateUtil.date2Str(new Date(), DateUtil.DATETIME_DEFAULT_FORMAT));
spcRequest.setHiddenTroubleName(dangerName);
spcRequest.setRiskSourceId(pointOriginalId);
spcRequest.setHiddenTroubleStatus(status);
spcRequest.setTroubleList(getTroubleList(pointId));
remoteSpcService.pushLatentDangerExecuteResult(spcRequest);
}
}
// TODO 远程调用修改;巡检业务需要
private List<String> getTroubleList(Long pointId) {
List<String> troubleList = Lists.newArrayList();
List<LatentDangerPatrolBo> patrolList = latentDangerPatrolMapper.listByPointId(pointId);
if (!CollectionUtils.isEmpty(patrolList)) {
List<Long> dangerIds = Lists.transform(patrolList, LatentDangerPatrolBo::getLatentDangerId);
List<LatentDangerFlowRecordBo> flowRecordBos = latentDangerFlowRecordMapper.listNewestRecordByDangerIds(dangerIds);
flowRecordBos.forEach(l -> {
String status = null;
if (l.getDangerState().equals(LatentDangerStateEnum.待治理.getCode())
&& l.getDangerOvertimeState().equals(LatentDangerOvertimeStateEnum.已超时.getCode())) {
status = "治理逾期";
} else {
if (l.getExecuteResult().equals(LatentDangerExecuteTypeEnum.隐患评审通过.getName())) {
status = "隐患评审通过";
} else if (l.getExecuteResult().equals(LatentDangerExecuteTypeEnum.隐患评审拒绝.getName())) {
status = "隐患评审不通过";
} else if (l.getExecuteResult().equals(LatentDangerExecuteTypeEnum.隐患验证拒绝.getName())) {
status = "治理验证不通过";
} else if (l.getExecuteResult().equals(LatentDangerExecuteTypeEnum.隐患验证通过.getName())) {
status = "治理验证完成";
}
}
if (status != null) {
troubleList.add(status);
}
});
}
return troubleList;
}
private void updateRiskSourceDangerState(Boolean isSave, Long riskSourceId, LatentDangerLevelEnum
levelEnum, Long pointId, Long dangerId) {
// RiskSourceBo riskSourceBo = riskSourceMapper.getById(riskSourceId);
// if (riskSourceBo != null) {
// if (isSave) {
// //添加隐患
// riskSourceBo.setIsDanger(true);
// if (riskSourceBo.getDangerLevel() == null) {
// riskSourceBo.setDangerLevel(levelEnum.getRiskSourceDangerLevelCode());
// } else {
//// if (riskSourceBo.getDangerLevel().equals(LatentDangerLevelEnum.一般隐患.getRiskSourceDangerLevelCode())
//// && levelEnum.equals(LatentDangerLevelEnum.重大隐患)) {
//// riskSourceBo.setDangerLevel(levelEnum.getRiskSourceDangerLevelCode());
//// }
// if (Integer.parseInt(riskSourceBo.getDangerLevel()) < Integer.parseInt(levelEnum.getRiskSourceDangerLevelCode())) {
// riskSourceBo.setDangerLevel(levelEnum.getRiskSourceDangerLevelCode());
// }
// }
// } else {
// //撤销、完成隐患
// HashMap<String, Object> params = new HashMap<>();
// params.put("pointId", pointId);
// params.put("dangerId", dangerId);
// List<LatentDangerBo> latentDangerBos = latentDangerMapper.listNotFinishByPointId(params);
// if (CollectionUtils.isEmpty(latentDangerBos)) {
// riskSourceBo.setIsDanger(false);
// } else {
// riskSourceBo.setIsDanger(true);
// String dangerLevel = checkHasSeriousDanger(latentDangerBos);
// riskSourceBo.setDangerLevel(dangerLevel);
// }
// }
// riskSourceMapper.updateDangerState(riskSourceBo);
// }
}
private String checkHasSeriousDanger(List<LatentDangerBo> latentDangerBos) {
String dangerLevel;
List<LatentDangerLevelEnum> levelEnums = Lists.newArrayList();
Map<String, List<LatentDangerBo>> map =
latentDangerBos.stream().collect(Collectors.groupingBy(LatentDangerBo::getDangerLevel));
map.keySet().forEach(l -> levelEnums.add(LatentDangerLevelEnum.getEnumByCode(l)));
int order = levelEnums.stream().mapToInt(LatentDangerLevelEnum::getOrder).max().getAsInt();
dangerLevel = Objects.requireNonNull(LatentDangerLevelEnum.getEnumByOrder(order)).getRiskSourceDangerLevelCode();
return dangerLevel;
}
@Override
public void freshRiskJudgmentLangerCount(LatentDangerExecuteParam latentDangerExecuteParam) {
// TODO 使用远程调用替换
// Long currentFlowRecordId = latentDangerExecuteParam.getFlowRecordId();
// LatentDangerFlowRecordBo currentRecord = latentDangerFlowRecordMapper.getById(currentFlowRecordId);
// if (currentRecord == null) {
// return;
// }
// LatentDangerBo latentDangerBo = latentDangerMapper.getById(currentRecord.getDangerId());
// if (latentDangerBo == null) {
// return;
// }
// LatentDangerPatrolBo patrolBo = latentDangerPatrolMapper.getByDangerId(latentDangerBo.getId());
// if (patrolBo != null && StringUtil.isNotEmpty(patrolBo.getPointOriginalId())) {
// iRiskJudgmentTaskService.freshRiskJudgmentLangerCount(Long.parseLong(patrolBo.getPointOriginalId()));
// }
}
@Override
public List<DictionarieValueModel> getDangerLevel() {
String dictCode = LatentDangerLevelEnum.dictCode;
if (!ValidationUtil.isEmpty(dangerBizType)) {
dictCode = dangerBizType + dictCode;
}
FeignClientResult<List<DictionarieValueModel>> result = Systemctl.dictionarieClient.dictValues(dictCode);
return result.getResult();
}
@Override
public List<DictionarieValueModel> getDangerGovernance() {
String dictCode = LatentDangerReformTypeEnum.dictCode;
if (!ValidationUtil.isEmpty(dangerBizType)) {
dictCode = dangerBizType + dictCode;
}
FeignClientResult<List<DictionarieValueModel>> result = Systemctl.dictionarieClient.dictValues(dictCode);
return result.getResult();
}
// @Override
// public JSONObject getDangerLevelJsonObject(String dangerLevelStr, String token, String product, String appKey, String dictCode) {
// JSONArray dangerLevelList = (JSONArray) this.getDangerLevel(token, product, appKey, dictCode);
// JSONObject dangerLevel = new JSONObject();
// List<Object> objs =
// dangerLevelList.stream().filter(level -> ((JSONObject) level).get("dictDataKey").equals(dangerLevelStr)).collect(Collectors.toList());
// if (!CollectionUtils.isEmpty(objs)) {
// dangerLevel = (JSONObject) objs.get(0);
// }
// return dangerLevel;
// }
@Override
public JSONObject getReviewInfo(Long dangerId) {
List<HashMap<String, Object>> result = latentDangerMapper.getReViewInfo(dangerId);
Set<String> userIdSet = Sets.newHashSet();
result.forEach(r -> {
userIdSet.add((String) r.get("executeUserId"));
if (StringUtil.isNotEmpty(r.get("handleUserIds"))) {
List<String> handleUserIds = Arrays.asList(r.get("handleUserIds").toString().split(","));
userIdSet.addAll(handleUserIds);
}
});
userIdSet.removeAll(Collections.singleton(null));
List<AgencyUserModel> userModels = remoteSecurityService.listUserByUserIds(Joiner.on(",").join(userIdSet));
if (StringUtil.isNotEmpty(userModels)) {
Map<String, AgencyUserModel> userMap = Maps.uniqueIndex(userModels, AgencyUserModel::getUserId);
result.forEach(r -> {
r.put("executeUserName", StringUtil.isNotEmpty(r.get("executeUserId")) ? userMap.get(r.get(
"executeUserId")).getRealName() : "");
List<String> handleUserNames = Lists.newArrayList();
if (StringUtil.isNotEmpty(r.get("handleUserIds"))) {
List<String> handleUserIds = Arrays.asList(r.get("handleUserIds").toString().split(","));
handleUserIds.forEach(id -> handleUserNames.add(userMap.get(id).getRealName()));
}
r.put("handleUserName", Joiner.on(",").join(handleUserNames));
});
}
JSONObject resultObjJson = new JSONObject();
result.forEach(r -> {
r.put("flowJson", JSON.parseObject((String) r.get("flowJson")));
resultObjJson.put((String) r.get("actionFlag"), JSONObject.toJSON(r));
});
return resultObjJson;
}
public List<Object> getBuildTree() {
ResponseModel<Object> response = equipFeign.getBuildingTree();
if (200 == response.getStatus() && ObjectUtils.isNotEmpty(response.getResult())) {
return JSONArray.parseArray(JSON.toJSONString(response.getResult()));
}
return null;
}
@Override
public Page<DangerListResponse> listDanger(PageParam pageParam) {
String idsStr = (String) pageParam.get("dangerIds");
if (StringUtil.isNotEmpty(idsStr)) {
List<String> dangerIdList = Lists.newArrayList(idsStr.split(","));
pageParam.put("dangerIds", dangerIdList);
}
if (StringUtil.isNotEmpty(pageParam.get("pageNumber")) && StringUtil.isNotEmpty(pageParam.get("pageSize"))) {
int offSet = (int) pageParam.get("pageNumber") * (int) pageParam.get("pageSize");
pageParam.put("offset", offSet);
}
// 获取隐患地点的子节点
Object structureId = pageParam.get("structureId");
List<Long> structureIdList = null;
if (structureId != null && structureId.toString().trim().length() > 0) {
// LinkedHashMap<String, Object> o = equipFeign.getBuildingTree();
ResponseModel<Object> response = equipFeign.getBuildingTree();
// if (o == null || !"200".equals(o.get("status").toString())) {
// throw new YeeException("获取建筑树出错");
// }
List<Map<String, Object>> buildingTree = (List<Map<String, Object>>) response.getResult();
Map<String, Object> node = getAllNodes(buildingTree).stream().filter(map -> structureId.equals(map.get("id"))).findFirst().orElse(null);
if (node != null) {
structureIdList = findBuildChildrenIds(node);
}
}
pageParam.put("structureId", structureIdList);
List<DangerListResponse> dangerListResponseList = latentDangerMapper.dangerListByMap(pageParam);
Map<Long, String> buildingAbsolutePositionMap = new HashMap<>();
try {
LinkedHashMap<String, Object> buildingAbsolutePosition = (LinkedHashMap<String, Object>) equipFeign.getBuildingAbsolutePosition().getResult();
if (buildingAbsolutePosition == null || !"200".equals(buildingAbsolutePosition.get("status").toString())) {
throw new YeeException("获取建筑树出错");
}
buildingAbsolutePositionMap = (Map<Long, String>) buildingAbsolutePosition.get("result");
} catch (Exception e) {
}
if (!dangerListResponseList.isEmpty()) {
Map<Long, String> finalBuildingAbsolutePositionMap = buildingAbsolutePositionMap;
dangerListResponseList.forEach(danger -> danger.setStructureName(finalBuildingAbsolutePositionMap.get(danger.getStructureId())));
}
Long count = latentDangerMapper.countDangerListByMap(pageParam);
if (CollectionUtils.isEmpty(dangerListResponseList)) {
return new PageImpl<>(dangerListResponseList, pageParam, 0L);
}
return new PageImpl<>(dangerList(dangerListResponseList), pageParam, count);
}
private List<Map<String, Object>> getAllNodes(List<Map<String, Object>> buildingTree) {
List<Map<String, Object>> res = new LinkedList<>();
if (buildingTree != null && !buildingTree.isEmpty()) {
res.addAll(buildingTree);
buildingTree.forEach(building -> {
List<Map<String, Object>> childrenTree = (List<Map<String, Object>>) building.get("children");
res.addAll(getAllNodes(childrenTree));
});
}
return res;
}
private List<Long> findBuildChildrenIds(Map<String, Object> building) {
List<Map<String, Object>> buildingTree = getAllNodes(Collections.singletonList(building));
return buildingTree.stream().map(building123 -> Long.valueOf(building123.get("id").toString())).collect(Collectors.toList());
}
@Override
public List<DangerListResponse> export(PageParam pageParam) {
String idsStr = (String) pageParam.get("dangerIds");
if (StringUtil.isNotEmpty(idsStr)) {
List<String> dangerIdList = Lists.newArrayList(idsStr.split(","));
pageParam.put("dangerIds", dangerIdList);
}
List<DangerListResponse> dangerListResponseList = latentDangerMapper.dangerListByMap(pageParam);
return dangerList(dangerListResponseList);
}
@Override
public List<DangerTimeAxisVo> queryExecuteLog(Integer dateTime) {
Map<String, Object> param = new HashMap<>();
String beginTime = "";
if (dateTime != null && dateTime == 7) {
beginTime = com.yeejoin.amos.latentdanger.core.util.DateUtil.getIntervalDateStr(new Date(), -7, "yyyy-MM-dd");
} else if (dateTime != null && dateTime == 30) {
beginTime = com.yeejoin.amos.latentdanger.core.util.DateUtil.getIntervalDateStr(new Date(), -30, "yyyy-MM-dd");
} else {
beginTime = com.yeejoin.amos.latentdanger.core.util.DateUtil.getShortCurrentDate();
}
param.put("beginTime", beginTime + " 00:00:00");
List<DangerTimeAxisVo> list = latentDangerFlowRecordMapper.listExecuteLog(param);
String d;
if (0 < list.size()) {
for (DangerTimeAxisVo vo : list) {
AgencyUserModel userModel = remoteSecurityService.getUserById(RequestContext.getToken(), getProduct(), RequestContext.getAppKey(), vo.getExecuteUserId().toString());
vo.setUserName(userModel.getRealName());
vo.setDangerState(LatentDangerStateEnum.getEnumName(vo.getDangerState()));
vo.setXAxis(null == vo.getUpdateDate() ? DateUtil.getDateFormat(new Date(), DateUtil.DATETIME_DEFAULT_FORMAT) : DateUtil.getDateFormat(vo.getUpdateDate(), DateUtil.DATETIME_DEFAULT_FORMAT));
vo.setRow1(vo.getUserName() + "-" + vo.getDangerState() + "-" + vo.getDangerName());
if ("3".equals(vo.getReformType())) {
d = null == vo.getDelayLimitDate() ? "无" : DateUtil.getDateFormat(vo.getDelayLimitDate(), DateUtil.DATETIME_DEFAULT_FORMAT);
} else {
d = null == vo.getReformLimitDate() ? "无" : DateUtil.getDateFormat(vo.getReformLimitDate(), DateUtil.DATETIME_DEFAULT_FORMAT);
}
vo.setRow2(vo.getStructureName() + "-" + d);
}
}
return list;
}
private List<DangerListResponse> dangerList(List<DangerListResponse> dangerListResponseList) {
JSONArray array = remoteSecurityService.listDictionaryByDictCode(RequestContext.getToken(), getProduct(), RequestContext.getAppKey(),
DictTypeEnum.DANGERLEVEL.getCode());
List<DictBo> dangerLevelList = JSONArray.parseArray(array.toJSONString(), DictBo.class);
for (DangerListResponse e : dangerListResponseList) {
e.setDangerState(LatentDangerStateEnum.getEnumName(e.getDangerState()));
DictBo dangerLevel =
dangerLevelList.stream().filter(item -> item.getDictDataKey().equals(e.getDangerLevel())).collect(Collectors.toList()).get(0);
e.setDangerLevel(dangerLevel.getDictDataValue());
e.setReformType(!StringUtil.isNotEmpty(e.getReformType()) ? "" :
LatentDangerReformTypeEnum.getEnumByCode(e.getReformType()).getName());
e.setOvertimeState("0".equals(e.getOvertimeState()) ? "否" : "是");
e.setDangerTypeName(LatentDangerTypeEnum.getEnumName(e.getDangerType()));
e.setDeadline(null == e.getDeadlineDate() ? "" : DateUtil.getLongDate(e.getDeadlineDate()));
}
return dangerListResponseList;
}
//获取下一节点需要发消息的用户信息
private String getNextExecuteUsers(String instanceId) {
String informerList = "";
JSONObject object = remoteWorkFlowService.getChildNodeDetail(instanceId);
if (object != null) {
JSONArray array = object.getJSONArray("data");
if (array.size() > 0) {
JSONObject workFlowDetail = array.getJSONObject(0);
informerList = workFlowDetail.getString("informerList");
}
}
return informerList;
}
}
package com.yeejoin.amos.latentdanger.business.service.intfc;
import com.alibaba.fastjson.JSONObject;
import com.yeejoin.amos.boot.biz.common.bo.RoleBo;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;
import com.yeejoin.amos.latentdanger.business.dto.DangerExecuteSubmitDto;
import com.yeejoin.amos.latentdanger.business.param.LatentDangerExecuteParam;
import com.yeejoin.amos.latentdanger.business.param.LatentDangerListParam;
import com.yeejoin.amos.latentdanger.business.param.LatentDangerNormalParam;
import com.yeejoin.amos.latentdanger.business.param.LatentDangerPatrolParam;
import com.yeejoin.amos.latentdanger.business.param.PageParam;
import com.yeejoin.amos.latentdanger.business.util.CommonResponse;
import com.yeejoin.amos.latentdanger.business.vo.DangerTimeAxisVo;
import com.yeejoin.amos.latentdanger.core.common.response.DangerListResponse;
import org.springframework.data.domain.Page;
import java.util.List;
/**
* @author tb
* @title: ILatentDangerFlowRecordService
* <pre>
* @description: TODO
* </pre>
* @date 2021/1/26 14:44
*/
public interface ILatentDangerFlowRecordService {
}
package com.yeejoin.amos.latentdanger.business.service.intfc;
import java.util.List;
import java.util.Map;
import com.yeejoin.amos.feign.systemctl.model.DictionarieValueModel;
import com.yeejoin.amos.latentdanger.business.param.LatentDangerDto;
import com.yeejoin.amos.latentdanger.business.param.LatentDangerExecuteParam;
import com.yeejoin.amos.latentdanger.business.param.PageParam;
import com.yeejoin.amos.latentdanger.common.enums.LatentDangerLevelEnum;
import org.springframework.data.domain.Page;
import com.alibaba.fastjson.JSONObject;
import com.yeejoin.amos.boot.biz.common.bo.RoleBo;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;
import com.yeejoin.amos.latentdanger.business.dto.DangerExecuteSubmitDto;
import com.yeejoin.amos.latentdanger.business.param.LatentDangerListParam;
import com.yeejoin.amos.latentdanger.business.param.LatentDangerNormalParam;
import com.yeejoin.amos.latentdanger.business.param.LatentDangerPatrolParam;
import com.yeejoin.amos.latentdanger.business.util.CommonResponse;
import com.yeejoin.amos.latentdanger.business.vo.DangerTimeAxisVo;
import com.yeejoin.amos.latentdanger.core.common.response.DangerListResponse;
/**
* @author keyong
* @title: ILatentDangerService
* <pre>
* @description: TODO
* </pre>
* @date 2021/1/26 14:44
*/
public interface ILatentDangerService {
CommonResponse saveNormal(LatentDangerNormalParam latentDangerParam, String userId, String userRealName,
String departmentId, String departmentName, String companyId, String orgCode, RoleBo role);
CommonResponse savePatrol(List<LatentDangerDto> latentDangerDtoList, String userId, String userRealName,
String departmentId, String departmentName, String companyId, String orgCode, RoleBo role) throws IllegalAccessException, InstantiationException;
CommonResponse list(String toke, String product, String appKey, LatentDangerListParam latentDangerListParam, AgencyUserModel user, String loginOrgCode, String deptId);
/**
* 隐患流程执行
*
* @param latentDangerExecuteParam
* @param userId
* @param userRealName
* @param departmentId
* @param departmentName
* @param role
* @return
*/
DangerExecuteSubmitDto execute(LatentDangerExecuteParam latentDangerExecuteParam, String userId,
String userRealName, String departmentId, String departmentName, RoleBo role);
CommonResponse detail(String id, String userId,boolean isFinish);
CommonResponse getByInstanceId(String instanceId);
DangerExecuteSubmitDto executeCallBack(String instanceId, Integer actionType, String remark, String token, String userId,
String userRealName, String departmentId, String departmentName);
void updateDangerStateOfOvertime();
CommonResponse listFlowRecord(String token, String product, String appKey, Long id);
void sendLatentDangerExecuteResult(DangerExecuteSubmitDto executeSubmitDto);
void freshRiskJudgmentLangerCount(LatentDangerExecuteParam latentDangerExecuteParam);
/**
* 获取隐患等级字典值
*
* @return
*/
List<DictionarieValueModel> getDangerLevel();
/**
* 获取隐患治理方式字典值
*
* @return
*/
List<DictionarieValueModel> getDangerGovernance();
// /**
// * 根据等级字符串获取等级字典对象
// *
// * @param dangerLevelStr 等级("1","2","0")
// * @return
// */
// JSONObject getDangerLevelJsonObject(String dangerLevelStr, String token, String product, String appKey, String dictCode);
/**
* 根据隐患id获取评审信息
*
* @param dangerId
* @return
*/
JSONObject getReviewInfo(Long dangerId);
Page<DangerListResponse> listDanger(PageParam pageParam);
List<DangerListResponse> export(PageParam pageParam);
List<DangerTimeAxisVo> queryExecuteLog(Integer dateTime);
}
package com.yeejoin.amos.latentdanger.business.service.intfc;
import com.yeejoin.amos.latentdanger.dao.entity.Msg;
public interface IMessageService {
/**
* 消息公告推送
*
* @param msg
*/
Msg pushMsgAndSave(String toke, String product, String appKey, Msg msg);
void pushMsg(String toke, String product, String appKey, com.yeejoin.amos.latentdanger.business.param.PushMsgParam pmsg);
}
package com.yeejoin.amos.latentdanger.business.service.intfc;
import java.util.List;
import org.springframework.data.domain.Page;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;
import com.yeejoin.amos.latentdanger.business.util.DaoCriteria;
import com.yeejoin.amos.latentdanger.core.common.request.CommonPageable;
import com.yeejoin.amos.latentdanger.dao.entity.Msg;
import com.yeejoin.amos.latentdanger.dao.entity.MsgSubscribe;
public interface IMsgSubscribeService {
public List<MsgSubscribe> queryMsgSubscribes(String orgCode, String userId);
public List<MsgSubscribe> queryMsgSubscribes(String userId);
public void saveSubscribe(List<MsgSubscribe> subscribe);
/**
* 根据登陆用户获取未读消息数
* @param user
* @return
*/
public int getUnreadCount(AgencyUserModel user);
/**
* 根据条件获取用户消息列表
* @param criterias
* @param commonPageable
* @return
*/
public Page<Msg> queryMsgList(List<DaoCriteria> criterias,CommonPageable commonPageable);
/**
* 修改消息为已读
* @param msgId
* @return
*/
public Msg isRead(long msgId);
}
package com.yeejoin.amos.latentdanger.business.trigger;
import java.util.HashMap;
public interface ITriggerDataService {
/**
* 判断表类型,进行不同的查询,调用安全进行数据维护
* @param keyMap
* @return
*/
boolean process(HashMap<String,Object> keyMap);
}
package com.yeejoin.amos.latentdanger.business.trigger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import java.util.HashMap;
@Service("triggerDataService")
public class TriggerDataServiceImpl implements ITriggerDataService {
/**
* 日志记录器
*/
private static final Logger logger = LoggerFactory.getLogger(TriggerDataServiceImpl.class);
@Override
public boolean process(HashMap<String, Object> keyMap) {
return false;
}
}
package com.yeejoin.amos.latentdanger.business.trigger;
import com.yeejoin.amos.latentdanger.context.IotContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashMap;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
public class TriggerKeyQueue {
/**
* 日志记录器
*/
private static final Logger log = LoggerFactory.getLogger(TriggerKeyQueue.class);
/**
* 单例
*/
private static TriggerKeyQueue instance;
/**
* 队列
*/
private static final BlockingQueue<HashMap<String,Object>> blockingQueue = new LinkedBlockingQueue<HashMap<String,Object>>();
/**
* 控制消费者线程运行状态
*/
private static boolean isRunning = true;
/**
* 构造方法
*/
private TriggerKeyQueue() {
}
/**
* 获取单例
*
* @return
*/
public static TriggerKeyQueue getInstance() {
if (instance == null) {
synchronized (TriggerKeyQueue.class) {
if (instance == null) {
instance = new TriggerKeyQueue();
}
}
}
return instance;
}
/**
* 添加数据
*
* @param frame
*/
public void add(HashMap<String,Object> keyMap) {
while (blockingQueue.add(keyMap)) {
log.debug("add a keyMap into blockingQueue successful!");
break;
}
}
public void start() {
Thread thread = new Thread(new TriggerKeyConsumer(), "trigger consumer thread");
thread.start();
}
/**
* 消费者线程
*
* @author as-suhg
*
*/
class TriggerKeyConsumer implements Runnable {
/**
* 1.从队列中取出数据;2.调用业务接口;
*/
@Override
public void run() {
while (isRunning) {
// 1.从队列中取出数据
HashMap<String,Object> keyMap = new HashMap<String,Object>();
try {
keyMap = blockingQueue.take();
} catch (InterruptedException e) {
log.error(e.getMessage(),e);
}
// 2.调用业务接口;
if (keyMap == null||keyMap.isEmpty()) {
log.warn("keyMap is empty!");
} else {
try {
ITriggerDataService triggerDataService = (ITriggerDataService) IotContext.getInstance().getBean(("triggerDataService"));
triggerDataService.process(keyMap);
} catch (Exception e) {
log.error(e.getMessage(),e);
// 失败处理
}
}
}
}
}
}
package com.yeejoin.amos.latentdanger.business.util;
public interface AbstractHtml {
public void createHtml(String inputFile, String outputFile) throws Exception;
}
package com.yeejoin.amos.latentdanger.business.util;
import org.springframework.cglib.beans.BeanCopier;
import java.util.concurrent.ConcurrentHashMap;
/**
* @Author: xinglei
* @Description:
* @Date: 2020/5/31 21:45
*/
public class BeanCopierUtil {
/**
* BeanCopier的缓存
*/
static final ConcurrentHashMap<String, BeanCopier> BEAN_COPIER_CACHE = new ConcurrentHashMap<>();
/**
* BeanCopier的copy
* @param source 源文件的
* @param target 目标文件
*/
public static void copyProperties(Object source, Object target) {
String key = genKey(source.getClass(), target.getClass());
BeanCopier beanCopier;
if (BEAN_COPIER_CACHE.containsKey(key)) {
beanCopier = BEAN_COPIER_CACHE.get(key);
} else {
beanCopier = BeanCopier.create(source.getClass(), target.getClass(), false);
BEAN_COPIER_CACHE.put(key, beanCopier);
}
beanCopier.copy(source, target, null);
}
/**
* 生成key
* @param srcClazz 源文件的class
* @param tgtClazz 目标文件的class
* @return string
*/
private static String genKey(Class<?> srcClazz, Class<?> tgtClazz) {
return srcClazz.getName() + tgtClazz.getName();
}
}
package com.yeejoin.amos.latentdanger.business.util;
//获取对象
public class CacheFactory {
private static CacheMap cacheMap;
private CacheFactory(){
}
public synchronized static CacheMap newChacheMap(){
if(cacheMap==null){
cacheMap=new CacheMap();
}
return cacheMap;
}
}
package com.yeejoin.amos.latentdanger.business.util;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
public class CacheMap{
//缓存Map
ConcurrentHashMap<String, CacheValue> cacheMap=new ConcurrentHashMap<String, CacheValue> ();
//保证不能被外界 构造
CacheMap(){
}
public void setex(String key,Toke value,long times){
CacheValue cValue=new CacheValue();
cValue.setTimes(System.currentTimeMillis()+times*1000);
cValue.setValue(value);
cacheMap.put(key, cValue);
}
public Toke getValue(String key){
CacheValue cValue=cacheMap.get(key);
if(cValue!=null && cValue.getTimes()>System.currentTimeMillis()){
return cValue.getValue();
}else if(cValue!=null && cacheMap.containsKey(key)){
//清理一次
cacheMap.remove(key);
}
return null;
}
/**
获取key集合
@return
*/
public Set getKeys(){
return cacheMap.keySet();
}
}
\ No newline at end of file
package com.yeejoin.amos.latentdanger.business.util;
public class CacheValue {
private Toke value; //真实数据对象
private long times; //缓存到期时间
public Toke getValue() {
return value;
}
public void setValue(Toke value) {
this.value = value;
}
public long getTimes() {
return times;
}
public void setTimes(long times) {
this.times = times;
}
}
package com.yeejoin.amos.latentdanger.business.util;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* <pre>
* 处理反射映射问题
* </pre>
*
* @author wanwei
* @time 2020-6-17 15:43:32
*/
public class ClazzFieldUtil {
public static Field[] getAllFields(Object object){
Class clazz = object.getClass();
List<Field> fieldList = new ArrayList<>();
while (clazz != null){
fieldList.addAll(new ArrayList<>(Arrays.asList(clazz.getDeclaredFields())));
clazz = clazz.getSuperclass();
}
Field[] fields = new Field[fieldList.size()];
fieldList.toArray(fields);
return fields;
}
}
package com.yeejoin.amos.latentdanger.business.util;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import io.swagger.annotations.ApiModelProperty;
import java.io.Serializable;
/**
* <pre>
* 返回封装对象
* </pre>
*
* @author mincx
* @version CommonReponse.java v0.1
* @time 2017-9-19 15:43:32
*/
public class CommonResponse implements Serializable {
private static final long serialVersionUID = -8737351878134480646L;
/**
* 操作状态
*/
@ApiModelProperty(required=true,value="操作状态")
private String result;
/**
* 操作状态
*/
@ApiModelProperty(required=true,value="状态码")
private int status;
/**
* 数据
*/
@ApiModelProperty(required=false,value="数据")
private Object dataList;
/**
* 操作详细信息
*/
@ApiModelProperty(required=false,value="操作详细信息")
private String message;
public CommonResponse(){
}
public CommonResponse(String result) {
this.result = result;
}
public CommonResponse(Object dataList) {
this.dataList = dataList;
this.result = "";
}
public CommonResponse(String result, Object dataList) {
this.dataList = dataList;
this.result = result;
}
public CommonResponse(String result, String message) {
this.result = result;
this.message = message;
}
public CommonResponse(String result, Object dataList, String message) {
this.dataList = dataList;
this.result = result;
this.message = message;
}
public CommonResponse(String result, Object dataList, int status) {
this.dataList = dataList;
this.result = result;
this.status = status;
}
public CommonResponse(String result, String message, int status) {
this.result = result;
this.message = message;
this.status = status;
}
public CommonResponse(String result, Object dataList, String message, int status) {
this.dataList = dataList;
this.result = result;
this.message = message;
this.status = status;
}
public Boolean isSuccess(){
return "SUCCESS".equals(getResult());
}
public String getResult() {
return result;
}
public void setResult(String result) {
this.result = result;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Object getDataList() {
return dataList;
}
public void setDataList(Object dataList) {
this.dataList = dataList;
}
public void setStatus(int status) {
this.status = status;
}
public int getStatus() {
return status;
}
public String toJsonStr() throws Exception {
return JSON.toJSONString(this,SerializerFeature.WriteMapNullValue,SerializerFeature.DisableCircularReferenceDetect,SerializerFeature.SkipTransientField);
}
}
package com.yeejoin.amos.latentdanger.business.util;
import org.springframework.http.HttpStatus;
public class CommonResponseUtil
{
public static CommonResponse success()
{
CommonResponse response = new CommonResponse();
response.setResult(Constants.RESULT_SUCCESS);
response.setStatus(HttpStatus.OK.value());
return response;
}
public static CommonResponse success(Object obj)
{
CommonResponse response = new CommonResponse();
response.setResult(Constants.RESULT_SUCCESS);
response.setStatus(HttpStatus.OK.value());
response.setDataList(obj);
return response;
}
public static CommonResponse success(Object obj, String message)
{
CommonResponse response = new CommonResponse();
response.setResult(Constants.RESULT_SUCCESS);
response.setStatus(HttpStatus.OK.value());
response.setDataList(obj);
response.setMessage(message);
return response;
}
public static CommonResponse failure()
{
CommonResponse response = new CommonResponse();
response.setResult(Constants.RESULT_FAILURE);
response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
return response;
}
public static CommonResponse failure(String message)
{
CommonResponse response = new CommonResponse();
response.setResult(Constants.RESULT_FAILURE);
response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
response.setMessage(message);
return response;
}
public static CommonResponse failure(Object obj, String message)
{
CommonResponse response = new CommonResponse();
response.setResult(Constants.RESULT_FAILURE);
response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
response.setDataList(obj);
response.setMessage(message);
return response;
}
}
package com.yeejoin.amos.latentdanger.business.util;
/**
* <pre>
* 系统常量
* </pre>
*
* @author mincx
* @version Constants.java v0.1
* @time 2017-9-19 15:43:32
*/
public class Constants {
public static final String ERROR_MESSAGE = "系统异常";
public static final String RESULT_SUCCESS = "SUCCESS";
public static final String RESULT_FAILURE = "FAILURE";
public static final String RULE_FACT_PREFIX = "rule_";
public static final String RULE_COMPILATION_ERROR = "规则编译异常";
public static final String NEW_LINE= "\r\n";
public static final String POSITION_LATITUDE = "latitude";
public static final String POSITION_LONGITUDE = "longitude";
public static final double PI = 3.1415;
public static final double EARTH_RADIUS = 6370.996;
public static final String RULE_CONDITION_AND = "&&";
public static final String RULE_CONDITION_OR = "||";
/**
* DES加密解密默认key
*/
public static final String XSS_KEY = "qaz";
/**
* 灾情状态
*/
public static final String FireHappenStateID = "90db70b7-49a4-4a72-b54b-0fabbed9bec7";//发生
public static final String FireDevelopStateID = "1f7fe7d7-b30c-4518-8c95-6e3bc506ca86";//猛烈
/**
* 车辆状态
*/
public static final String CarArrivedStateID = "ad55748a-1206-4507-8831-95b7f2ad804f";//到达
public static final String CarDispatchingStateID = "43a23576-3d0f-4c3d-a46b-555391a4d870";//待出动
public static final String CarOnDutyStateID = "21cc717f-60b4-46ae-942e-9efd63d13415";//执勤
public static final String CarOnSiteStateID = "d7eddc16-4c55-4de0-b726-3547c7b0b980";//在位
public static final String CarOnTheWayStateID = "5e1b6e98-d1dc-4c49-a7ad-b959d2278dba";//在途
public static final String CarRepairStateID = "e86d455b-e9fd-4938-9826-38ca46623287";//维修
/**
* 战斗力量编队状态
*/
public static final String RescuePowerArrivedStateID = "0951f770-7f75-43d8-bcec-47d7559be727";//到达
public static final String RescuePowerDispatchedStateID = "ec4afc56-6cec-41a3-95f5-20c735f052d4";//已调派
public static final String RescuePowerEnhanceStateID = "3d6cf113-b69d-47c3-a3a8-ded448cc4636";//增援
public static final String RescuePowerFightingStateID = "4bacd4b4-b07d-454e-b737-431e7c997cde";//战斗
public static final String RescuePowerStandByStateID = "4fc6e4d6-c6a8-453c-b554-ce7de0b828b2";//待命
/**
* sql注入关键字
*/
public static String badStr = "'|and|exec|execute|insert|select|delete|update|count|drop|%|chr|mid|master|truncate|" +
"char|declare|sitename|net user|xp_cmdshell|;|or|-|+|,|like'|and|exec|execute|insert|create|drop|" +
"table|from|grant|use|group_concat|column_name|" +
"information_schema.columns|table_schema|union|where|select|delete|update|order|by|count|" +
"chr|mid|master|truncate|char|declare|or|;|-|--|,|like|//|/|%|#";
}
package com.yeejoin.amos.latentdanger.business.util;
import java.io.Serializable;
import org.apache.commons.lang3.builder.ToStringBuilder;
/**
*
* <pre>
* 查询条件封装类
* </pre>
*
* @author as-hanshipeng
* @version $Id: DaoCriteria.java, v 0.1 2016-12-9 下午12:22:03 as-hanshipeng Exp $
*/
public class DaoCriteria implements Serializable
{
private static final long serialVersionUID = 812759366580443779L;
//属性名称
private String propertyName;
//操作符
private String operator;
//属性值
private Object value;
public String getOperator()
{
return operator;
}
public void setOperator(String operator)
{
this.operator = operator;
}
public String getPropertyName()
{
return propertyName;
}
public void setPropertyName(String propertyName)
{
this.propertyName = propertyName;
}
public Object getValue()
{
return value;
}
public void setValue(Object value)
{
this.value = value;
}
public DaoCriteria()
{
}
public DaoCriteria(String property, String operator, Object value)
{
propertyName = property;
this.operator = operator;
this.value = value;
}
public String toString()
{
return (new ToStringBuilder(this)).append("Property", propertyName).append(operator).append("Value", value).toString();
}
}
package com.yeejoin.amos.latentdanger.business.util;
import org.apache.commons.lang.StringUtils;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import static com.yeejoin.amos.latentdanger.core.util.DateUtil.LONG_PATTERN;
import static com.yeejoin.amos.latentdanger.core.util.DateUtil.getCurrentCalendar;
/**
* 日期工具类
*
*/
public class DateUtil {
// 默认日期格式
public static final String DATE_DEFAULT_FORMAT = "yyyy-MM-dd";
// 默认日期格式
public static final String DATE_YEARANDMONTH_FORMAT = "yyyy-MM";
// 默认时间格式
public static final String DATETIME_DEFAULT_FORMAT = "yyyy-MM-dd HH:mm:ss";
public static final String TIME_DEFAULT_FORMAT = "HH:mm:ss";
// 日期格式化
private static DateFormat dateFormat = null;
// 时间格式化
private static DateFormat dateTimeFormat = null;
// 年月格式化
private static DateFormat dateYearAndMonthFormat = null;
private static DateFormat timeFormat = null;
private static Calendar gregorianCalendar = null;
static {
dateFormat = new SimpleDateFormat(DATE_DEFAULT_FORMAT);
dateYearAndMonthFormat = new SimpleDateFormat(DATE_YEARANDMONTH_FORMAT);
dateTimeFormat = new SimpleDateFormat(DATETIME_DEFAULT_FORMAT);
timeFormat = new SimpleDateFormat(TIME_DEFAULT_FORMAT);
gregorianCalendar = new GregorianCalendar();
}
/**
* 日期格式化yyyy-MM-dd
*
* @param date
* @return
*/
public static Date formatDate(String date, String format) {
try {
return new SimpleDateFormat(format).parse(date);
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
/**
* 日期格式化yyyy-MM-dd
*
* @param date
* @return
*/
public static String getDateFormat(Date date) {
return dateFormat.format(date);
}
/**
* 日期格式化yyyy-MM
*
* @param date
* @return
*/
public static String getDateYearAndMonthFormat(Date date) {
return dateYearAndMonthFormat.format(date);
}
/**
* 日期格式化yyyy-MM-dd HH:mm:ss
*
* @param date
* @return
*/
public static String getDateTimeFormat(Date date) {
return dateTimeFormat.format(date);
}
/**
* 时间格式化
*
* @param date
* @return HH:mm:ss
*/
public static String getTimeFormat(Date date) {
return timeFormat.format(date);
}
/**
* 日期格式化
*
* @param date
* @param 格式类型
* @return
*/
public static String getDateFormat(Date date, String formatStr) {
if (StringUtils.isNotBlank(formatStr)) {
return new SimpleDateFormat(formatStr).format(date);
}
return null;
}
/**
* 日期格式化
*
* @param date
* @return
*/
public static Date getDateFormat(String date) {
try {
return dateFormat.parse(date);
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
/**
* 时间格式化
*
* @param date
* @return
*/
public static Date getDateTimeFormat(String date) {
try {
return dateTimeFormat.parse(date);
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
/**
* 获取当前日期(yyyy-MM-dd)
*
* @param date
* @return
*/
public static Date getNowDate() {
return DateUtil.getDateFormat(dateFormat.format(new Date()));
}
/**
* 获取当前日期星期一日期
*
* @return date
*/
public static Date getFirstDayOfWeek() {
gregorianCalendar.setFirstDayOfWeek(Calendar.MONDAY);
gregorianCalendar.setTime(new Date());
gregorianCalendar.set(Calendar.DAY_OF_WEEK, gregorianCalendar.getFirstDayOfWeek()); // Monday
return gregorianCalendar.getTime();
}
/**
* 获取当前日期星期日日期
*
* @return date
*/
public static Date getLastDayOfWeek() {
gregorianCalendar.setFirstDayOfWeek(Calendar.MONDAY);
gregorianCalendar.setTime(new Date());
gregorianCalendar.set(Calendar.DAY_OF_WEEK, gregorianCalendar.getFirstDayOfWeek() + 6); // Monday
return gregorianCalendar.getTime();
}
/**
* <pre>
* 获取当前北京时间
* </pre>
*
* @return
*/
public static String getLongCurrentDate() {
return new SimpleDateFormat(LONG_PATTERN)
.format(getCurrentCalendar().getTime());
}
public static String getLongDate(Date date) {
if (null == date)
return getLongCurrentDate();
else
return new SimpleDateFormat(LONG_PATTERN).format(date);
}
/**
* 获取日期星期一日期
*
* @param 指定日期
* @return date
*/
public static Date getFirstDayOfWeek(Date date) {
if (date == null) {
return null;
}
gregorianCalendar.setFirstDayOfWeek(Calendar.MONDAY);
gregorianCalendar.setTime(date);
gregorianCalendar.set(Calendar.DAY_OF_WEEK, gregorianCalendar.getFirstDayOfWeek()); // Monday
return gregorianCalendar.getTime();
}
/**
* 获取日期星期一日期
*
* @param 指定日期
* @return date
*/
public static Date getLastDayOfWeek(Date date) {
if (date == null) {
return null;
}
gregorianCalendar.setFirstDayOfWeek(Calendar.MONDAY);
gregorianCalendar.setTime(date);
gregorianCalendar.set(Calendar.DAY_OF_WEEK, gregorianCalendar.getFirstDayOfWeek() + 6); // Monday
return gregorianCalendar.getTime();
}
/**
* 获取当前月的第一天
*
* @return date
*/
public static Date getFirstDayOfMonth() {
gregorianCalendar.setTime(new Date());
gregorianCalendar.set(Calendar.DAY_OF_MONTH, 1);
return gregorianCalendar.getTime();
}
/**
* 获取当前月的最后一天
*
* @return
*/
public static Date getLastDayOfMonth() {
gregorianCalendar.setTime(new Date());
gregorianCalendar.set(Calendar.DAY_OF_MONTH, 1);
gregorianCalendar.add(Calendar.MONTH, 1);
gregorianCalendar.add(Calendar.DAY_OF_MONTH, -1);
return gregorianCalendar.getTime();
}
/**
* 获取指定月的第一天
*
* @param date
* @return
*/
public static Date getFirstDayOfMonth(Date date) {
gregorianCalendar.setTime(date);
gregorianCalendar.set(Calendar.DAY_OF_MONTH, 1);
return gregorianCalendar.getTime();
}
/**
* 获取指定月的最后一天
*
* @param date
* @return
*/
public static Date getLastDayOfMonth(Date date) {
gregorianCalendar.setTime(date);
gregorianCalendar.set(Calendar.DAY_OF_MONTH, 1);
gregorianCalendar.add(Calendar.MONTH, 1);
gregorianCalendar.add(Calendar.DAY_OF_MONTH, -1);
return gregorianCalendar.getTime();
}
/**
* 获取日期前一天
*
* @param date
* @return
*/
public static Date getDayBefore(Date date) {
gregorianCalendar.setTime(date);
int day = gregorianCalendar.get(Calendar.DATE);
gregorianCalendar.set(Calendar.DATE, day - 1);
return gregorianCalendar.getTime();
}
/**
* 获取日期后一天
*
* @param date
* @return
*/
public static Date getDayAfter(Date date) {
gregorianCalendar.setTime(date);
int day = gregorianCalendar.get(Calendar.DATE);
gregorianCalendar.set(Calendar.DATE, day + 1);
return gregorianCalendar.getTime();
}
/**
* 获取当前年
*
* @return
*/
public static int getNowYear() {
Calendar d = Calendar.getInstance();
return d.get(Calendar.YEAR);
}
/**
* 获取当前月份
*
* @return
*/
public static int getNowMonth() {
Calendar d = Calendar.getInstance();
return d.get(Calendar.MONTH) + 1;
}
/**
* 获取date的年
*
* @return
*/
public static int getDateYear(Date date) {
Calendar d = Calendar.getInstance();
d.setTime(date);
return d.get(Calendar.YEAR);
}
/**
* 获取date的月份
*
* @return
*/
public static int getDateMonth(Date date) {
Calendar d = Calendar.getInstance();
d.setTime(date);
return d.get(Calendar.MONTH) + 1;
}
/**
* 获取当月天数
*
* @return
*/
public static int getNowMonthDay() {
Calendar d = Calendar.getInstance();
return d.getActualMaximum(Calendar.DATE);
}
/**
* 获取时间段的每一天
*
* @param 开始日期
* @param 结算日期
* @return 日期列表
*/
public static List<Date> getEveryDay(Date startDate, Date endDate) {
if (startDate == null || endDate == null) {
return null;
}
// 格式化日期(yy-MM-dd)
startDate = DateUtil.getDateFormat(DateUtil.getDateFormat(startDate));
endDate = DateUtil.getDateFormat(DateUtil.getDateFormat(endDate));
List<Date> dates = new ArrayList<Date>();
gregorianCalendar.setTime(startDate);
dates.add(gregorianCalendar.getTime());
while (gregorianCalendar.getTime().compareTo(endDate) < 0) {
// 加1天
gregorianCalendar.add(Calendar.DAY_OF_MONTH, 1);
dates.add(gregorianCalendar.getTime());
}
return dates;
}
/**
* 获取提前多少个月
*
* @param monty
* @return
*/
public static Date getFirstMonth(int monty) {
Calendar c = Calendar.getInstance();
c.add(Calendar.MONTH, -monty);
return c.getTime();
}
/**
* 得到现在时间
*
* @return
*/
public static Date getNow()
{
Date currentTime = new Date();
return currentTime;
}
/**
* 获取现在时间
*
* @return 返回时间类型 yyyy-MM-dd HH:mm:ss
*/
public static String getNowDateLongForHandset()
{
Date currentTime = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy:MM:dd-HH:mm:ss");
String dateString = formatter.format(currentTime);
return dateString;
}
public static String getDateLongForHandset(java.util.Date dateDate){
SimpleDateFormat formatter = new SimpleDateFormat("yyyy:MM:dd HH:mm:ss");
String dateString = formatter.format(dateDate);
return dateString;
}
public static String getDateStr(String formatterstr) {
Date currentTime = new Date();
SimpleDateFormat formatter = new SimpleDateFormat(formatterstr);
String dateString = formatter.format(currentTime);
return dateString;
}
/**
* 获取现在时间
*
* @return 返回时间类型 yyyy-MM-dd HH:mm:ss
*/
public static Date getNowDateLong()
{
Date currentTime = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateString = formatter.format(currentTime);
ParsePosition pos = new ParsePosition(0);
Date currentTime_2 = formatter.parse(dateString, pos);
return currentTime_2;
}
/**
* 获取现在时间
*
* @return返回短时间格式 yyyy-MM-dd
*/
public static Date getNowDateShort()
{
Date currentTime = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
String dateString = formatter.format(currentTime);
ParsePosition pos = new ParsePosition(8);
Date currentTime_2 = formatter.parse(dateString, pos);
return currentTime_2;
}
/**
* 获取现在时间字符串
*
* @return返回字符串格式 yyyy-MM-dd HH:mm:ss
*/
public static String getNowStrLong()
{
Date currentTime = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateString = formatter.format(currentTime);
return dateString;
}
/**
* 获取现在时间字符串
*
* @return 返回短时间字符串格式yyyy-MM-dd
*/
public static String getNowStrShort()
{
Date currentTime = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
String dateString = formatter.format(currentTime);
return dateString;
}
/**
* 获取时间 小时:分;秒 HH:mm:ss
*
* @return
*/
public static String getNowHHMMSS()
{
SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
Date currentTime = new Date();
String dateString = formatter.format(currentTime);
return dateString;
}
/**
*
* <pre>
*
* </pre>
*
* @param strDate
* @param dateFormat
* @return
*/
public static Date str2Date(String strDate, String dateFormat)
{
SimpleDateFormat formatter = new SimpleDateFormat(dateFormat);
ParsePosition pos = new ParsePosition(0);
Date strtodate = formatter.parse(strDate, pos);
return strtodate;
}
/**
*
* <pre>
* e.g localDateStr ="2017-03-30T06:28:12.803Z";
* </pre>
*
* @param strDate
* @param dateFormat
* @return
*/
public static Date localDateStr2Date(String localDateStr)
{
LocalDateTime localDate = LocalDateTime.parse(localDateStr,DateTimeFormatter.ISO_ZONED_DATE_TIME);
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String formatLocalDate2Str = localDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
ParsePosition pos = new ParsePosition(0);
Date strtodate = formatter.parse(formatLocalDate2Str, pos);
return strtodate;
}
/**
* 将长时间格式字符串转换为时间 yyyy-MM-dd HH:mm:ss
*
* @param strDate
* @return
*/
public static Date longStr2Date(String strDate)
{
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
ParsePosition pos = new ParsePosition(0);
Date strtodate = formatter.parse(strDate, pos);
return strtodate;
}
/**
* 将长时间格式字符串转换为时间 yyyy-MM-dd HH:mm
*
* @param strDate
* @return
*/
public static Date longStr3Date(String strDate)
{
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
ParsePosition pos = new ParsePosition(0);
Date strtodate = formatter.parse(strDate, pos);
return strtodate;
}
/**
* 将长时间格式字符串转换为long型数据
*
* @param strDate
* @return
*/
public static Long longStr2Long(String strDate)
{
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
ParsePosition pos = new ParsePosition(0);
Date strtodate = formatter.parse(strDate, pos);
return strtodate.getTime();
}
/**
* 将长时间格式时间转换为字符串 yyyy-MM-dd HH:mm:ss
*
* @param dateDate
* @return
*/
public static String date2LongStr(Date dateDate)
{
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateString = formatter.format(dateDate);
return dateString;
}
/**
* 将短时间格式时间转换为字符串 yyyy-MM-dd
*
* @param dateDate
* @param k
* @return
*/
public static String date2ShortStr(java.util.Date dateDate)
{
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
String dateString = formatter.format(dateDate);
return dateString;
}
/**
*
* <pre>
*
* </pre>
*
* @param l
* @param dateFormat
* @return
*/
public static String long2Str(long l, String dateFormat)
{
if (l == 0)
{
return "";
}
try
{
Date dateDate = new Date(l);
SimpleDateFormat formatter = new SimpleDateFormat(dateFormat);
String dateString = formatter.format(dateDate);
return dateString;
}
catch (Exception e)
{
return "";
}
}
/**
* 把LONG数据类型转换为字符串
*
* @param l
* @return
*/
public static String long2LongStr(long l)
{
if (l == 0)
{
return "";
}
try
{
Date dateDate = new Date(l);
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateString = formatter.format(dateDate);
return dateString;
}
catch (Exception e)
{
return "";
}
}
/**
* 把LONG数据类型转换为字符串
*
* <pre>
*
* </pre>
*
* @param l
* @return
*/
public static String long2ShortStr(long l)
{
if (l == 0)
{
return "";
}
try
{
Date dateDate = new Date(l);
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
String dateString = formatter.format(dateDate);
return dateString;
}
catch (Exception e)
{
return "";
}
}
/**
* 将短时间格式字符串转换为时间 yyyy-MM-dd
*
* @param strDate
* @return
*/
public static Date shortStr2ShortDate(String strDate)
{
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
ParsePosition pos = new ParsePosition(0);
Date strtodate = formatter.parse(strDate, pos);
return strtodate;
}
/**
* 提取一个月中的最后一天
*
* @param day
* @return
*/
public static Date getLastDateOfThisMonth(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;
}
/**
* 获取日期中的年
*
* @param date
* @return
*/
public static String getYear(Date date) {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateString = formatter.format(date);
String year;
year = dateString.substring(0, 4);
return year;
}
/**
* 得到现在小时
*/
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 getMinute()
{
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 parseDate(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
{
java.util.Date date = myFormatter.parse(sj1);
java.util.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)
{
mydate1 = "";
}
return mydate1;
}
/**
* 得到一个时间延后或前移几天的时间,nowdate为时间,delay为前移或后延的天数
*/
public static String getNextDay(String nowdate, String delay)
{
try
{
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
String mdate = "";
Date d = shortStr2ShortDate(nowdate);
long myTime = (d.getTime() / 1000) + Integer.parseInt(delay) * 24 * 60 * 60;
d.setTime(myTime * 1000);
mdate = format.format(d);
return mdate;
}
catch (Exception e)
{
return "";
}
}
/**
* 判断是否润年
*
* @param ddate
* @return
*/
public static boolean isLeapYear(String ddate)
{
/**
* 详细设计: 1.被400整除是闰年,否则: 2.不能被4整除则不是闰年 3.能被4整除同时不能被100整除则是闰年
* 3.能被4整除同时能被100整除则不是闰年
*/
Date d = shortStr2ShortDate(ddate);
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 = shortStr2ShortDate(sdate);
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());
}
/**
* 根据一个日期,返回是星期几的字符串
*
* @param sdate
* @return
*/
public static String getWeek(String sdate)
{
// 再转换为时间
Date date = shortStr2ShortDate(sdate);
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 = 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");
java.util.Date date = null;
java.util.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 sdate
* @return
*/
public static String getNowMonth(String sdate)
{
// 取该时间所在月的一号
sdate = sdate.substring(0, 8) + "01";
// 得到这个月的1号是星期几
Date date = shortStr2ShortDate(sdate);
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 parseDate("yyyyMMddhhmmss") + getRandom(k);
}
/**
* 返回一个随机数
*
* @param i
* @return
*/
private static String getRandom(int i)
{
Random jjj = new Random();
// int suiJiShu = jjj.nextInt(9);
if (i == 0) return "";
String jj = "";
for (int k = 0; k < i; k++)
{
jj = jj + jjj.nextInt(9);
}
return jj;
}
/**
*
* @param args
*/
public static boolean rightDate(String date)
{
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
if (date == null) return false;
if (date.length() > 10)
{
sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
}
else
{
sdf = new SimpleDateFormat("yyyy-MM-dd");
}
try
{
sdf.parse(date);
}
catch (ParseException e)
{
return false;
}
return true;
}
public static void main(String[] args)
{
//
}
/**
* 将date 按照指定 的 格式 formatStr 转换成 字符串
*
* @param date
* @param formatStr
* @return
*/
public static String date2Str(Date date, String formatStr)
{
SimpleDateFormat formatter = new SimpleDateFormat(formatStr);
String dateString = formatter.format(date);
return dateString;
}
/**
* 增加hours小時
*
* @param date
* @param hours
* @return
*/
public static Date addHours(Date date, int hours)
{
if (date == null) return null;
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.HOUR_OF_DAY, hours);// 24小时制
// cal.add(Calendar.HOUR, x);12小时制
date = cal.getTime();
return date;
}
/**
* 增加minutes分鐘
*
* @param date
* @param minutes
* @return
*/
public static Date addMinutes(Date date, int minutes)
{
if (date == null) return null;
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.MINUTE, minutes);//
date = cal.getTime();
return date;
}
/**
* 功能描述:格式化日期
*
* @param dateStr
* String 字符型日期
* @param format
* String 格式
* @return Date 日期
*/
public static Date parseDate(String dateStr, String format) {
Date date=null;
try {
DateFormat dateFormat = new SimpleDateFormat(format);
date = (Date) dateFormat.parse(dateStr);
} catch (Exception e) {
}
return date;
}
// 指定模式的时间格式
private static SimpleDateFormat getSDFormat(String pattern) {
return new SimpleDateFormat(pattern);
}
/**
* 当前日历,这里用中国时间表示
*
* @return 以当地时区表示的系统当前日历
*/
public static Calendar getCalendar() {
return Calendar.getInstance();
}
/**
* 默认日期按指定格式显示
*
* @param pattern
* 指定的格式
* @return 默认日期按指定格式显示
*/
public static String formatDate(String pattern) {
return getSDFormat(pattern).format(getCalendar().getTime());
}
/**
* 获取当前时间任意
* @return
*/
public static String get(int field) {
return String.valueOf(getCalendar().get(field));
}
/**
* 获取今日的开始时间
* @return
*/
public static Date getTodayBeginTime(){
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
Date today = calendar.getTime();
return today;
}
/**
* 获取今日的结束时间
* @return
*/
public static Date getTodayEndTime(){
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
calendar.set(Calendar.HOUR_OF_DAY, 23);
calendar.set(Calendar.MINUTE, 59);
calendar.set(Calendar.SECOND, 59);
Date today = calendar.getTime();
return today;
}
/**
* 获取两个时间相差的 *小时*分钟
* @param endDate
* @param nowDate
* @return
*/
public static String getDatePoorToMin(Date endDate, Date nowDate) {
// long nd = 1000 * 24 * 60 * 60;
long nh = 1000 * 60 * 60;
long nm = 1000 * 60;
// long ns = 1000;
// 获得两个时间的毫秒时间差异
long diff = endDate.getTime() - nowDate.getTime();
// 计算差多少天
// long day = diff / nd;
// 计算差多少小时
long hour = diff / nh;
// 计算差多少分钟
long min = diff % nh / nm;
// 计算差多少秒//输出结果
// long sec = diff % nd % nh % nm / ns;
return hour + "小时" + min + "分钟";
}
public static String getDatePoorToSec(Date endDate, Date nowDate) {
long nd = 1000 * 24 * 60 * 60;
long nh = 1000 * 60 * 60;
long nm = 1000 * 60;
long ss = 1000;
// long ns = 1000;
// 获得两个时间的毫秒时间差异
long diff = endDate.getTime() - nowDate.getTime();
// 计算差多少天
long day = diff / nd;
// 计算差多少小时
long hour = diff % nd / nh;
// 计算差多少分钟
long min = diff % nd % nh / nm;
long sen = diff % nd % nh % nm / ss;
// 计算差多少秒//输出结果
// long sec = diff % nd % nh % nm / ns;
return day + "天" + hour + "小时" + min + "分钟"+ sen + "秒";
}
}
\ No newline at end of file
package com.yeejoin.amos.latentdanger.business.util;
import lombok.Data;
import java.io.Serializable;
import java.util.List;
@Data
public class DepartmentTreeBo implements Serializable {
private static final long serialVersionUID = 1L;
private String departmentName;
private List<DepartmentTreeBo> children;
private Long deptOrgCode;
private String orgCode;
private String departmentDesc;
private String companySeq;
private String sequenceNbr;
private String parentId;
}
package com.yeejoin.amos.latentdanger.business.util;
import com.google.common.collect.Lists;
import java.util.List;
import java.util.Map;
public class DepartmentUserTreeAppVo {
private String name;
private String id;
private String type;
private Map<String, String> object;
private List<DepartmentUserTreeAppVo> children = Lists.newArrayList();
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Map<String, String> getObject() {
return object;
}
public void setObject(Map<String, String> object) {
this.object = object;
}
public List<DepartmentUserTreeAppVo> getChildren() {
return children;
}
public void setChildren(List<DepartmentUserTreeAppVo> children) {
this.children = children;
}
}
package com.yeejoin.amos.latentdanger.business.util;
import com.google.common.collect.Lists;
import java.util.List;
public class DepartmentUserTreeWebVo {
private String key;
private String label;
private String title;
private String type;
private String value;
private List<DepartmentUserTreeWebVo> children = Lists.newArrayList();
private List<DepartmentUserTreeWebVo> userModelList = Lists.newArrayList();
public List<DepartmentUserTreeWebVo> getUserModelList() {
return userModelList;
}
public void setUserModelList(List<DepartmentUserTreeWebVo> userModelList) {
this.userModelList = userModelList;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public List<DepartmentUserTreeWebVo> getChildren() {
return children;
}
public void setChildren(List<DepartmentUserTreeWebVo> children) {
this.children = children;
}
}
\ No newline at end of file
package com.yeejoin.amos.latentdanger.business.util;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang.StringUtils;
/**
*
* <pre>
* DES加密解密工具
* 加密:DesUtils.encode("admin","1,2,3");
* 解密:DesUtils.decode("012C2C9BA925FAF8045B2FD9B02A2664","1,2,3");
* </pre>
*
* @author amos
* @version $Id: DesUtil.java, v 0.1 2018年10月13日 下午3:56:27 amos Exp $
*/
public class DesUtil {
private static DesCore desCore = new DesCore();
/**
* DES加密(secretKey代表3个key,用逗号分隔)
*/
public static String encode(String data, String secretKey) {
if (StringUtils.isBlank(data)){
return "";
}
String[] ks = StringUtils.split(secretKey, ",");
if (ks.length >= 3){
return desCore.strEnc(data, ks[0], ks[1], ks[2]);
}
return desCore.strEnc(data, secretKey, "", "");
}
/**
* DES解密(secretKey代表3个key,用逗号分隔)
*/
public static String decode(String data, String secretKey) {
if (StringUtils.isBlank(data)){
return "";
}
String[] ks = StringUtils.split(secretKey, ",");
if (ks.length >= 3){
return desCore.strDec(data, ks[0], ks[1], ks[2]);
}
return desCore.strDec(data, secretKey, "", "");
}
/**
*
* <pre>
* DES加密/解密
* @Copyright Copyright (c) 2006
* </pre>
*
* @author amos
* @version $Id: DesUtil.java, v 0.1 2018年10月13日 下午3:56:59 amos Exp $
*/
@SuppressWarnings({"rawtypes","unused","unchecked"})
static class DesCore {
/*
* encrypt the string to string made up of hex return the encrypted string
*/
public String strEnc(String data, String firstKey, String secondKey, String thirdKey) {
int leng = data.length();
String encData = "";
List firstKeyBt = null, secondKeyBt = null, thirdKeyBt = null;
int firstLength = 0, secondLength = 0, thirdLength = 0;
if (firstKey != null && firstKey != "") {
firstKeyBt = getKeyBytes(firstKey);
firstLength = firstKeyBt.size();
}
if (secondKey != null && secondKey != "") {
secondKeyBt = getKeyBytes(secondKey);
secondLength = secondKeyBt.size();
}
if (thirdKey != null && thirdKey != "") {
thirdKeyBt = getKeyBytes(thirdKey);
thirdLength = thirdKeyBt.size();
}
if (leng > 0) {
if (leng < 4) {
int[] bt = strToBt(data);
int[] encByte = null;
if (firstKey != null && firstKey != "" && secondKey != null && secondKey != "" && thirdKey != null && thirdKey != "") {
int[] tempBt;
int x, y, z;
tempBt = bt;
for (x = 0; x < firstLength; x++) {
tempBt = enc(tempBt, (int[]) firstKeyBt.get(x));
}
for (y = 0; y < secondLength; y++) {
tempBt = enc(tempBt, (int[]) secondKeyBt.get(y));
}
for (z = 0; z < thirdLength; z++) {
tempBt = enc(tempBt, (int[]) thirdKeyBt.get(z));
}
encByte = tempBt;
} else {
if (firstKey != null && firstKey != "" && secondKey != null && secondKey != "") {
int[] tempBt;
int x, y;
tempBt = bt;
for (x = 0; x < firstLength; x++) {
tempBt = enc(tempBt, (int[]) firstKeyBt.get(x));
}
for (y = 0; y < secondLength; y++) {
tempBt = enc(tempBt, (int[]) secondKeyBt.get(y));
}
encByte = tempBt;
} else {
if (firstKey != null && firstKey != "") {
int[] tempBt;
int x = 0;
tempBt = bt;
for (x = 0; x < firstLength; x++) {
tempBt = enc(tempBt, (int[]) firstKeyBt.get(x));
}
encByte = tempBt;
}
}
}
encData = bt64ToHex(encByte);
} else {
int iterator = (leng / 4);
int remainder = leng % 4;
int i = 0;
for (i = 0; i < iterator; i++) {
String tempData = data.substring(i * 4 + 0, i * 4 + 4);
int[] tempByte = strToBt(tempData);
int[] encByte = null;
if (firstKey != null && firstKey != "" && secondKey != null && secondKey != "" && thirdKey != null && thirdKey != "") {
int[] tempBt;
int x, y, z;
tempBt = tempByte;
for (x = 0; x < firstLength; x++) {
tempBt = enc(tempBt, (int[]) firstKeyBt.get(x));
}
for (y = 0; y < secondLength; y++) {
tempBt = enc(tempBt, (int[]) secondKeyBt.get(y));
}
for (z = 0; z < thirdLength; z++) {
tempBt = enc(tempBt, (int[]) thirdKeyBt.get(z));
}
encByte = tempBt;
} else {
if (firstKey != null && firstKey != "" && secondKey != null && secondKey != "") {
int[] tempBt;
int x, y;
tempBt = tempByte;
for (x = 0; x < firstLength; x++) {
tempBt = enc(tempBt, (int[]) firstKeyBt.get(x));
}
for (y = 0; y < secondLength; y++) {
tempBt = enc(tempBt, (int[]) secondKeyBt.get(y));
}
encByte = tempBt;
} else {
if (firstKey != null && firstKey != "") {
int[] tempBt;
int x;
tempBt = tempByte;
for (x = 0; x < firstLength; x++) {
tempBt = enc(tempBt, (int[]) firstKeyBt.get(x));
}
encByte = tempBt;
}
}
}
encData += bt64ToHex(encByte);
}
if (remainder > 0) {
String remainderData = data.substring(iterator * 4 + 0, leng);
int[] tempByte = strToBt(remainderData);
int[] encByte = null;
if (firstKey != null && firstKey != "" && secondKey != null && secondKey != "" && thirdKey != null && thirdKey != "") {
int[] tempBt;
int x, y, z;
tempBt = tempByte;
for (x = 0; x < firstLength; x++) {
tempBt = enc(tempBt, (int[]) firstKeyBt.get(x));
}
for (y = 0; y < secondLength; y++) {
tempBt = enc(tempBt, (int[]) secondKeyBt.get(y));
}
for (z = 0; z < thirdLength; z++) {
tempBt = enc(tempBt, (int[]) thirdKeyBt.get(z));
}
encByte = tempBt;
} else {
if (firstKey != null && firstKey != "" && secondKey != null && secondKey != "") {
int[] tempBt;
int x, y;
tempBt = tempByte;
for (x = 0; x < firstLength; x++) {
tempBt = enc(tempBt, (int[]) firstKeyBt.get(x));
}
for (y = 0; y < secondLength; y++) {
tempBt = enc(tempBt, (int[]) secondKeyBt.get(y));
}
encByte = tempBt;
} else {
if (firstKey != null && firstKey != "") {
int[] tempBt;
int x;
tempBt = tempByte;
for (x = 0; x < firstLength; x++) {
tempBt = enc(tempBt, (int[]) firstKeyBt.get(x));
}
encByte = tempBt;
}
}
}
encData += bt64ToHex(encByte);
}
}
}
return encData;
}
/*
* decrypt the encrypted string to the original string
*
* return the original string
*/
public String strDec(String data, String firstKey, String secondKey, String thirdKey) {
int leng = data.length();
String decStr = "";
List firstKeyBt = null, secondKeyBt = null, thirdKeyBt = null;
int firstLength = 0, secondLength = 0, thirdLength = 0;
if (firstKey != null && firstKey != "") {
firstKeyBt = getKeyBytes(firstKey);
firstLength = firstKeyBt.size();
}
if (secondKey != null && secondKey != "") {
secondKeyBt = getKeyBytes(secondKey);
secondLength = secondKeyBt.size();
}
if (thirdKey != null && thirdKey != "") {
thirdKeyBt = getKeyBytes(thirdKey);
thirdLength = thirdKeyBt.size();
}
int iterator = leng / 16;
int i = 0;
for (i = 0; i < iterator; i++) {
String tempData = data.substring(i * 16 + 0, i * 16 + 16);
String strByte = hexToBt64(tempData);
int[] intByte = new int[64];
int j = 0;
for (j = 0; j < 64; j++) {
intByte[j] = Integer.parseInt(strByte.substring(j, j + 1));
}
int[] decByte = null;
if (firstKey != null && firstKey != "" && secondKey != null && secondKey != "" && thirdKey != null && thirdKey != "") {
int[] tempBt;
int x, y, z;
tempBt = intByte;
for (x = thirdLength - 1; x >= 0; x--) {
tempBt = dec(tempBt, (int[]) thirdKeyBt.get(x));
}
for (y = secondLength - 1; y >= 0; y--) {
tempBt = dec(tempBt, (int[]) secondKeyBt.get(y));
}
for (z = firstLength - 1; z >= 0; z--) {
tempBt = dec(tempBt, (int[]) firstKeyBt.get(z));
}
decByte = tempBt;
} else {
if (firstKey != null && firstKey != "" && secondKey != null && secondKey != "") {
int[] tempBt;
int x, y, z;
tempBt = intByte;
for (x = secondLength - 1; x >= 0; x--) {
tempBt = dec(tempBt, (int[]) secondKeyBt.get(x));
}
for (y = firstLength - 1; y >= 0; y--) {
tempBt = dec(tempBt, (int[]) firstKeyBt.get(y));
}
decByte = tempBt;
} else {
if (firstKey != null && firstKey != "") {
int[] tempBt;
int x, y, z;
tempBt = intByte;
for (x = firstLength - 1; x >= 0; x--) {
tempBt = dec(tempBt, (int[]) firstKeyBt.get(x));
}
decByte = tempBt;
}
}
}
decStr += byteToString(decByte);
}
return decStr;
}
/*
* chang the string into the bit array
*
* return bit array(it's length % 64 = 0)
*/
public List getKeyBytes(String key) {
List keyBytes = new ArrayList();
int leng = key.length();
int iterator = (leng / 4);
int remainder = leng % 4;
int i = 0;
for (i = 0; i < iterator; i++) {
keyBytes.add(i, strToBt(key.substring(i * 4 + 0, i * 4 + 4)));
}
if (remainder > 0) {
// keyBytes[i] = strToBt(key.substring(i*4+0,leng));
keyBytes.add(i, strToBt(key.substring(i * 4 + 0, leng)));
}
return keyBytes;
}
/*
* chang the string(it's length <= 4) into the bit array
*
* return bit array(it's length = 64)
*/
public int[] strToBt(String str) {
int leng = str.length();
int[] bt = new int[64];
if (leng < 4) {
int i = 0, j = 0, p = 0, q = 0;
for (i = 0; i < leng; i++) {
int k = str.charAt(i);
for (j = 0; j < 16; j++) {
int pow = 1, m = 0;
for (m = 15; m > j; m--) {
pow *= 2;
}
// bt.set(16*i+j,""+(k/pow)%2));
bt[16 * i + j] = (k / pow) % 2;
}
}
for (p = leng; p < 4; p++) {
int k = 0;
for (q = 0; q < 16; q++) {
int pow = 1, m = 0;
for (m = 15; m > q; m--) {
pow *= 2;
}
// bt[16*p+q]=parseInt(k/pow)%2;
// bt.add(16*p+q,""+((k/pow)%2));
bt[16 * p + q] = (k / pow) % 2;
}
}
} else {
for (int i = 0; i < 4; i++) {
int k = str.charAt(i);
for (int j = 0; j < 16; j++) {
int pow = 1;
for (int m = 15; m > j; m--) {
pow *= 2;
}
// bt[16*i+j]=parseInt(k/pow)%2;
// bt.add(16*i+j,""+((k/pow)%2));
bt[16 * i + j] = (k / pow) % 2;
}
}
}
return bt;
}
/*
* chang the bit(it's length = 4) into the hex
*
* return hex
*/
public String bt4ToHex(String binary) {
String hex = "";
if (binary.equalsIgnoreCase("0000")) {
hex = "0";
} else if (binary.equalsIgnoreCase("0001")) {
hex = "1";
} else if (binary.equalsIgnoreCase("0010")) {
hex = "2";
} else if (binary.equalsIgnoreCase("0011")) {
hex = "3";
} else if (binary.equalsIgnoreCase("0100")) {
hex = "4";
} else if (binary.equalsIgnoreCase("0101")) {
hex = "5";
} else if (binary.equalsIgnoreCase("0110")) {
hex = "6";
} else if (binary.equalsIgnoreCase("0111")) {
hex = "7";
} else if (binary.equalsIgnoreCase("1000")) {
hex = "8";
} else if (binary.equalsIgnoreCase("1001")) {
hex = "9";
} else if (binary.equalsIgnoreCase("1010")) {
hex = "A";
} else if (binary.equalsIgnoreCase("1011")) {
hex = "B";
} else if (binary.equalsIgnoreCase("1100")) {
hex = "C";
} else if (binary.equalsIgnoreCase("1101")) {
hex = "D";
} else if (binary.equalsIgnoreCase("1110")) {
hex = "E";
} else if (binary.equalsIgnoreCase("1111")) {
hex = "F";
}
return hex;
}
/*
* chang the hex into the bit(it's length = 4)
*
* return the bit(it's length = 4)
*/
public String hexToBt4(String hex) {
String binary = "";
if (hex.equalsIgnoreCase("0")) {
binary = "0000";
} else if (hex.equalsIgnoreCase("1")) {
binary = "0001";
}
if (hex.equalsIgnoreCase("2")) {
binary = "0010";
}
if (hex.equalsIgnoreCase("3")) {
binary = "0011";
}
if (hex.equalsIgnoreCase("4")) {
binary = "0100";
}
if (hex.equalsIgnoreCase("5")) {
binary = "0101";
}
if (hex.equalsIgnoreCase("6")) {
binary = "0110";
}
if (hex.equalsIgnoreCase("7")) {
binary = "0111";
}
if (hex.equalsIgnoreCase("8")) {
binary = "1000";
}
if (hex.equalsIgnoreCase("9")) {
binary = "1001";
}
if (hex.equalsIgnoreCase("A")) {
binary = "1010";
}
if (hex.equalsIgnoreCase("B")) {
binary = "1011";
}
if (hex.equalsIgnoreCase("C")) {
binary = "1100";
}
if (hex.equalsIgnoreCase("D")) {
binary = "1101";
}
if (hex.equalsIgnoreCase("E")) {
binary = "1110";
}
if (hex.equalsIgnoreCase("F")) {
binary = "1111";
}
return binary;
}
/*
* chang the bit(it's length = 64) into the string
*
* return string
*/
public String byteToString(int[] byteData) {
String str = "";
for (int i = 0; i < 4; i++) {
int count = 0;
for (int j = 0; j < 16; j++) {
int pow = 1;
for (int m = 15; m > j; m--) {
pow *= 2;
}
count += byteData[16 * i + j] * pow;
}
if (count != 0) {
str += "" + (char) (count);
}
}
return str;
}
public String bt64ToHex(int[] byteData) {
String hex = "";
for (int i = 0; i < 16; i++) {
String bt = "";
for (int j = 0; j < 4; j++) {
bt += byteData[i * 4 + j];
}
hex += bt4ToHex(bt);
}
return hex;
}
public String hexToBt64(String hex) {
String binary = "";
for (int i = 0; i < 16; i++) {
binary += hexToBt4(hex.substring(i, i + 1));
}
return binary;
}
/*
* the 64 bit des core arithmetic
*/
public int[] enc(int[] dataByte, int[] keyByte) {
int[][] keys = generateKeys(keyByte);
int[] ipByte = initPermute(dataByte);
int[] ipLeft = new int[32];
int[] ipRight = new int[32];
int[] tempLeft = new int[32];
int i = 0, j = 0, k = 0, m = 0, n = 0;
for (k = 0; k < 32; k++) {
ipLeft[k] = ipByte[k];
ipRight[k] = ipByte[32 + k];
}
for (i = 0; i < 16; i++) {
for (j = 0; j < 32; j++) {
tempLeft[j] = ipLeft[j];
ipLeft[j] = ipRight[j];
}
int[] key = new int[48];
for (m = 0; m < 48; m++) {
key[m] = keys[i][m];
}
int[] tempRight = xor(pPermute(sBoxPermute(xor(expandPermute(ipRight), key))), tempLeft);
for (n = 0; n < 32; n++) {
ipRight[n] = tempRight[n];
}
}
int[] finalData = new int[64];
for (i = 0; i < 32; i++) {
finalData[i] = ipRight[i];
finalData[32 + i] = ipLeft[i];
}
return finallyPermute(finalData);
}
public int[] dec(int[] dataByte, int[] keyByte) {
int[][] keys = generateKeys(keyByte);
int[] ipByte = initPermute(dataByte);
int[] ipLeft = new int[32];
int[] ipRight = new int[32];
int[] tempLeft = new int[32];
int i = 0, j = 0, k = 0, m = 0, n = 0;
for (k = 0; k < 32; k++) {
ipLeft[k] = ipByte[k];
ipRight[k] = ipByte[32 + k];
}
for (i = 15; i >= 0; i--) {
for (j = 0; j < 32; j++) {
tempLeft[j] = ipLeft[j];
ipLeft[j] = ipRight[j];
}
int[] key = new int[48];
for (m = 0; m < 48; m++) {
key[m] = keys[i][m];
}
int[] tempRight = xor(pPermute(sBoxPermute(xor(expandPermute(ipRight), key))), tempLeft);
for (n = 0; n < 32; n++) {
ipRight[n] = tempRight[n];
}
}
int[] finalData = new int[64];
for (i = 0; i < 32; i++) {
finalData[i] = ipRight[i];
finalData[32 + i] = ipLeft[i];
}
return finallyPermute(finalData);
}
public int[] initPermute(int[] originalData) {
int[] ipByte = new int[64];
int i = 0, m = 1, n = 0, j, k;
for (i = 0, m = 1, n = 0; i < 4; i++, m += 2, n += 2) {
for (j = 7, k = 0; j >= 0; j--, k++) {
ipByte[i * 8 + k] = originalData[j * 8 + m];
ipByte[i * 8 + k + 32] = originalData[j * 8 + n];
}
}
return ipByte;
}
public int[] expandPermute(int[] rightData) {
int[] epByte = new int[48];
int i, j;
for (i = 0; i < 8; i++) {
if (i == 0) {
epByte[i * 6 + 0] = rightData[31];
} else {
epByte[i * 6 + 0] = rightData[i * 4 - 1];
}
epByte[i * 6 + 1] = rightData[i * 4 + 0];
epByte[i * 6 + 2] = rightData[i * 4 + 1];
epByte[i * 6 + 3] = rightData[i * 4 + 2];
epByte[i * 6 + 4] = rightData[i * 4 + 3];
if (i == 7) {
epByte[i * 6 + 5] = rightData[0];
} else {
epByte[i * 6 + 5] = rightData[i * 4 + 4];
}
}
return epByte;
}
public int[] xor(int[] byteOne, int[] byteTwo) {
// var xorByte = new Array(byteOne.length);
// for(int i = 0;i < byteOne.length; i ++){
// xorByte[i] = byteOne[i] ^ byteTwo[i];
// }
// return xorByte;
int[] xorByte = new int[byteOne.length];
for (int i = 0; i < byteOne.length; i++) {
xorByte[i] = byteOne[i] ^ byteTwo[i];
}
return xorByte;
}
public int[] sBoxPermute(int[] expandByte) {
// var sBoxByte = new Array(32);
int[] sBoxByte = new int[32];
String binary = "";
int[][] s1 = { { 14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7 }, { 0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8 },
{ 4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0 }, { 15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13 } };
/* Table - s2 */
int[][] s2 = { { 15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10 }, { 3, 13, 4, 7, 15, 2, 8, 14, 12, 0, 1, 10, 6, 9, 11, 5 },
{ 0, 14, 7, 11, 10, 4, 13, 1, 5, 8, 12, 6, 9, 3, 2, 15 }, { 13, 8, 10, 1, 3, 15, 4, 2, 11, 6, 7, 12, 0, 5, 14, 9 } };
/* Table - s3 */
int[][] s3 = { { 10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8 }, { 13, 7, 0, 9, 3, 4, 6, 10, 2, 8, 5, 14, 12, 11, 15, 1 },
{ 13, 6, 4, 9, 8, 15, 3, 0, 11, 1, 2, 12, 5, 10, 14, 7 }, { 1, 10, 13, 0, 6, 9, 8, 7, 4, 15, 14, 3, 11, 5, 2, 12 } };
/* Table - s4 */
int[][] s4 = { { 7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15 }, { 13, 8, 11, 5, 6, 15, 0, 3, 4, 7, 2, 12, 1, 10, 14, 9 },
{ 10, 6, 9, 0, 12, 11, 7, 13, 15, 1, 3, 14, 5, 2, 8, 4 }, { 3, 15, 0, 6, 10, 1, 13, 8, 9, 4, 5, 11, 12, 7, 2, 14 } };
/* Table - s5 */
int[][] s5 = { { 2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9 }, { 14, 11, 2, 12, 4, 7, 13, 1, 5, 0, 15, 10, 3, 9, 8, 6 },
{ 4, 2, 1, 11, 10, 13, 7, 8, 15, 9, 12, 5, 6, 3, 0, 14 }, { 11, 8, 12, 7, 1, 14, 2, 13, 6, 15, 0, 9, 10, 4, 5, 3 } };
/* Table - s6 */
int[][] s6 = { { 12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11 }, { 10, 15, 4, 2, 7, 12, 9, 5, 6, 1, 13, 14, 0, 11, 3, 8 },
{ 9, 14, 15, 5, 2, 8, 12, 3, 7, 0, 4, 10, 1, 13, 11, 6 }, { 4, 3, 2, 12, 9, 5, 15, 10, 11, 14, 1, 7, 6, 0, 8, 13 } };
/* Table - s7 */
int[][] s7 = { { 4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1 }, { 13, 0, 11, 7, 4, 9, 1, 10, 14, 3, 5, 12, 2, 15, 8, 6 },
{ 1, 4, 11, 13, 12, 3, 7, 14, 10, 15, 6, 8, 0, 5, 9, 2 }, { 6, 11, 13, 8, 1, 4, 10, 7, 9, 5, 0, 15, 14, 2, 3, 12 } };
/* Table - s8 */
int[][] s8 = { { 13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7 }, { 1, 15, 13, 8, 10, 3, 7, 4, 12, 5, 6, 11, 0, 14, 9, 2 },
{ 7, 11, 4, 1, 9, 12, 14, 2, 0, 6, 10, 13, 15, 3, 5, 8 }, { 2, 1, 14, 7, 4, 10, 8, 13, 15, 12, 9, 0, 3, 5, 6, 11 } };
for (int m = 0; m < 8; m++) {
int i = 0, j = 0;
i = expandByte[m * 6 + 0] * 2 + expandByte[m * 6 + 5];
j = expandByte[m * 6 + 1] * 2 * 2 * 2 + expandByte[m * 6 + 2] * 2 * 2 + expandByte[m * 6 + 3] * 2 + expandByte[m * 6 + 4];
switch (m) {
case 0:
binary = getBoxBinary(s1[i][j]);
break;
case 1:
binary = getBoxBinary(s2[i][j]);
break;
case 2:
binary = getBoxBinary(s3[i][j]);
break;
case 3:
binary = getBoxBinary(s4[i][j]);
break;
case 4:
binary = getBoxBinary(s5[i][j]);
break;
case 5:
binary = getBoxBinary(s6[i][j]);
break;
case 6:
binary = getBoxBinary(s7[i][j]);
break;
case 7:
binary = getBoxBinary(s8[i][j]);
break;
}
sBoxByte[m * 4 + 0] = Integer.parseInt(binary.substring(0, 1));
sBoxByte[m * 4 + 1] = Integer.parseInt(binary.substring(1, 2));
sBoxByte[m * 4 + 2] = Integer.parseInt(binary.substring(2, 3));
sBoxByte[m * 4 + 3] = Integer.parseInt(binary.substring(3, 4));
}
return sBoxByte;
}
public int[] pPermute(int[] sBoxByte) {
int[] pBoxPermute = new int[32];
pBoxPermute[0] = sBoxByte[15];
pBoxPermute[1] = sBoxByte[6];
pBoxPermute[2] = sBoxByte[19];
pBoxPermute[3] = sBoxByte[20];
pBoxPermute[4] = sBoxByte[28];
pBoxPermute[5] = sBoxByte[11];
pBoxPermute[6] = sBoxByte[27];
pBoxPermute[7] = sBoxByte[16];
pBoxPermute[8] = sBoxByte[0];
pBoxPermute[9] = sBoxByte[14];
pBoxPermute[10] = sBoxByte[22];
pBoxPermute[11] = sBoxByte[25];
pBoxPermute[12] = sBoxByte[4];
pBoxPermute[13] = sBoxByte[17];
pBoxPermute[14] = sBoxByte[30];
pBoxPermute[15] = sBoxByte[9];
pBoxPermute[16] = sBoxByte[1];
pBoxPermute[17] = sBoxByte[7];
pBoxPermute[18] = sBoxByte[23];
pBoxPermute[19] = sBoxByte[13];
pBoxPermute[20] = sBoxByte[31];
pBoxPermute[21] = sBoxByte[26];
pBoxPermute[22] = sBoxByte[2];
pBoxPermute[23] = sBoxByte[8];
pBoxPermute[24] = sBoxByte[18];
pBoxPermute[25] = sBoxByte[12];
pBoxPermute[26] = sBoxByte[29];
pBoxPermute[27] = sBoxByte[5];
pBoxPermute[28] = sBoxByte[21];
pBoxPermute[29] = sBoxByte[10];
pBoxPermute[30] = sBoxByte[3];
pBoxPermute[31] = sBoxByte[24];
return pBoxPermute;
}
public int[] finallyPermute(int[] endByte) {
int[] fpByte = new int[64];
fpByte[0] = endByte[39];
fpByte[1] = endByte[7];
fpByte[2] = endByte[47];
fpByte[3] = endByte[15];
fpByte[4] = endByte[55];
fpByte[5] = endByte[23];
fpByte[6] = endByte[63];
fpByte[7] = endByte[31];
fpByte[8] = endByte[38];
fpByte[9] = endByte[6];
fpByte[10] = endByte[46];
fpByte[11] = endByte[14];
fpByte[12] = endByte[54];
fpByte[13] = endByte[22];
fpByte[14] = endByte[62];
fpByte[15] = endByte[30];
fpByte[16] = endByte[37];
fpByte[17] = endByte[5];
fpByte[18] = endByte[45];
fpByte[19] = endByte[13];
fpByte[20] = endByte[53];
fpByte[21] = endByte[21];
fpByte[22] = endByte[61];
fpByte[23] = endByte[29];
fpByte[24] = endByte[36];
fpByte[25] = endByte[4];
fpByte[26] = endByte[44];
fpByte[27] = endByte[12];
fpByte[28] = endByte[52];
fpByte[29] = endByte[20];
fpByte[30] = endByte[60];
fpByte[31] = endByte[28];
fpByte[32] = endByte[35];
fpByte[33] = endByte[3];
fpByte[34] = endByte[43];
fpByte[35] = endByte[11];
fpByte[36] = endByte[51];
fpByte[37] = endByte[19];
fpByte[38] = endByte[59];
fpByte[39] = endByte[27];
fpByte[40] = endByte[34];
fpByte[41] = endByte[2];
fpByte[42] = endByte[42];
fpByte[43] = endByte[10];
fpByte[44] = endByte[50];
fpByte[45] = endByte[18];
fpByte[46] = endByte[58];
fpByte[47] = endByte[26];
fpByte[48] = endByte[33];
fpByte[49] = endByte[1];
fpByte[50] = endByte[41];
fpByte[51] = endByte[9];
fpByte[52] = endByte[49];
fpByte[53] = endByte[17];
fpByte[54] = endByte[57];
fpByte[55] = endByte[25];
fpByte[56] = endByte[32];
fpByte[57] = endByte[0];
fpByte[58] = endByte[40];
fpByte[59] = endByte[8];
fpByte[60] = endByte[48];
fpByte[61] = endByte[16];
fpByte[62] = endByte[56];
fpByte[63] = endByte[24];
return fpByte;
}
public String getBoxBinary(int i) {
String binary = "";
switch (i) {
case 0:
binary = "0000";
break;
case 1:
binary = "0001";
break;
case 2:
binary = "0010";
break;
case 3:
binary = "0011";
break;
case 4:
binary = "0100";
break;
case 5:
binary = "0101";
break;
case 6:
binary = "0110";
break;
case 7:
binary = "0111";
break;
case 8:
binary = "1000";
break;
case 9:
binary = "1001";
break;
case 10:
binary = "1010";
break;
case 11:
binary = "1011";
break;
case 12:
binary = "1100";
break;
case 13:
binary = "1101";
break;
case 14:
binary = "1110";
break;
case 15:
binary = "1111";
break;
}
return binary;
}
/*
* generate 16 keys for xor
*/
public int[][] generateKeys(int[] keyByte) {
int[] key = new int[56];
int[][] keys = new int[16][48];
// keys[ 0] = new Array();
// keys[ 1] = new Array();
// keys[ 2] = new Array();
// keys[ 3] = new Array();
// keys[ 4] = new Array();
// keys[ 5] = new Array();
// keys[ 6] = new Array();
// keys[ 7] = new Array();
// keys[ 8] = new Array();
// keys[ 9] = new Array();
// keys[10] = new Array();
// keys[11] = new Array();
// keys[12] = new Array();
// keys[13] = new Array();
// keys[14] = new Array();
// keys[15] = new Array();
int[] loop = new int[] { 1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1 };
for (int i = 0; i < 7; i++) {
for (int j = 0, k = 7; j < 8; j++, k--) {
key[i * 8 + j] = keyByte[8 * k + i];
}
}
int i = 0;
for (i = 0; i < 16; i++) {
int tempLeft = 0;
int tempRight = 0;
for (int j = 0; j < loop[i]; j++) {
tempLeft = key[0];
tempRight = key[28];
for (int k = 0; k < 27; k++) {
key[k] = key[k + 1];
key[28 + k] = key[29 + k];
}
key[27] = tempLeft;
key[55] = tempRight;
}
// var tempKey = new Array(48);
int[] tempKey = new int[48];
tempKey[0] = key[13];
tempKey[1] = key[16];
tempKey[2] = key[10];
tempKey[3] = key[23];
tempKey[4] = key[0];
tempKey[5] = key[4];
tempKey[6] = key[2];
tempKey[7] = key[27];
tempKey[8] = key[14];
tempKey[9] = key[5];
tempKey[10] = key[20];
tempKey[11] = key[9];
tempKey[12] = key[22];
tempKey[13] = key[18];
tempKey[14] = key[11];
tempKey[15] = key[3];
tempKey[16] = key[25];
tempKey[17] = key[7];
tempKey[18] = key[15];
tempKey[19] = key[6];
tempKey[20] = key[26];
tempKey[21] = key[19];
tempKey[22] = key[12];
tempKey[23] = key[1];
tempKey[24] = key[40];
tempKey[25] = key[51];
tempKey[26] = key[30];
tempKey[27] = key[36];
tempKey[28] = key[46];
tempKey[29] = key[54];
tempKey[30] = key[29];
tempKey[31] = key[39];
tempKey[32] = key[50];
tempKey[33] = key[44];
tempKey[34] = key[32];
tempKey[35] = key[47];
tempKey[36] = key[43];
tempKey[37] = key[48];
tempKey[38] = key[38];
tempKey[39] = key[55];
tempKey[40] = key[33];
tempKey[41] = key[52];
tempKey[42] = key[45];
tempKey[43] = key[41];
tempKey[44] = key[49];
tempKey[45] = key[35];
tempKey[46] = key[28];
tempKey[47] = key[31];
int m;
switch (i) {
case 0:
for (m = 0; m < 48; m++) {
keys[0][m] = tempKey[m];
}
break;
case 1:
for (m = 0; m < 48; m++) {
keys[1][m] = tempKey[m];
}
break;
case 2:
for (m = 0; m < 48; m++) {
keys[2][m] = tempKey[m];
}
break;
case 3:
for (m = 0; m < 48; m++) {
keys[3][m] = tempKey[m];
}
break;
case 4:
for (m = 0; m < 48; m++) {
keys[4][m] = tempKey[m];
}
break;
case 5:
for (m = 0; m < 48; m++) {
keys[5][m] = tempKey[m];
}
break;
case 6:
for (m = 0; m < 48; m++) {
keys[6][m] = tempKey[m];
}
break;
case 7:
for (m = 0; m < 48; m++) {
keys[7][m] = tempKey[m];
}
break;
case 8:
for (m = 0; m < 48; m++) {
keys[8][m] = tempKey[m];
}
break;
case 9:
for (m = 0; m < 48; m++) {
keys[9][m] = tempKey[m];
}
break;
case 10:
for (m = 0; m < 48; m++) {
keys[10][m] = tempKey[m];
}
break;
case 11:
for (m = 0; m < 48; m++) {
keys[11][m] = tempKey[m];
}
break;
case 12:
for (m = 0; m < 48; m++) {
keys[12][m] = tempKey[m];
}
break;
case 13:
for (m = 0; m < 48; m++) {
keys[13][m] = tempKey[m];
}
break;
case 14:
for (m = 0; m < 48; m++) {
keys[14][m] = tempKey[m];
}
break;
case 15:
for (m = 0; m < 48; m++) {
keys[15][m] = tempKey[m];
}
break;
}
}
return keys;
}
}
}
package com.yeejoin.amos.latentdanger.business.util;
import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.yeejoin.amos.latentdanger.exception.YeeException;
import org.apache.commons.io.FileUtils;
import org.apache.poi.hslf.usermodel.HSLFSlideShow;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddressList;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.ByteBuffer;
import java.nio.channels.Channel;
import java.nio.channels.FileChannel;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
*
* 类描述: 包括功能、用途、现存BUG,以及其它别人可能感兴趣的介绍。
*
* @see 需要参见的其它类(可选)
* @version 1.0
* @date 2016年7月27日
* @author <a href="mailto:Ydm@nationsky.com">Ydm</a>
* @since JDK 1.7
*/
public class FileHelper {
private static final Logger log = LoggerFactory.getLogger(FileHelper.class);
/**
*
* @param file
* @return
*/
public static boolean isExcel2003(File file) {
InputStream is = null;
Workbook wb = null;
try {
is = new FileInputStream(file);
wb = WorkbookFactory.create(is);
if (wb instanceof XSSFWorkbook) {
return false;
} else if (wb instanceof HSSFWorkbook) {
return true;
}
} catch (Exception e) {
return false;
} finally {
try {
if (null != is) {
is.close();
}
if (null != wb) {
wb.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return true;
}
/**
*
* @param file
* @return
*/
public static boolean isWord2003(File file) {
InputStream is = null;
try {
is = new FileInputStream(file);
new HWPFDocument(is);
} catch (Exception e) {
return false;
} finally {
try {
if (null != is) {
is.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return true;
}
public static boolean isWord2007(File file) {
InputStream is = null;
try {
is = new FileInputStream(file);
new XWPFDocument(is).close();
} catch (Exception e) {
return false;
} finally {
try {
if (null != is) {
is.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return true;
}
/**
*
* @param file
* @return
*/
public static boolean isPPT2003(File file) {
InputStream is = null;
HSLFSlideShow ppt = null;
try {
is = new FileInputStream(file);
ppt = new HSLFSlideShow(is);
} catch (Exception e) {
return false;
} finally {
try {
if (null != is) {
is.close();
}
if (null != ppt) {
ppt.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return true;
}
/**
*
* @param path
* @return
*/
public static StringBuffer readFile(String path) {
StringBuffer buffer = new StringBuffer();
InputStream is = null;
BufferedReader br = null;
try {
File file = new File(path);
if (file.exists()) {
is = new FileInputStream(file);
br = new BufferedReader(new InputStreamReader(is));
String content = br.readLine();
while (null != content) {
buffer.append(content);
content = br.readLine();
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (null != is) {
is.close();
}
if (null != br) {
br.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
return buffer;
}
/**
* 读取文件,并按照指定的分割符保存文件
* @param path 文件的路径
* @param split 分割内容的标识
* @return 按照传入的分割符,标识的字符串
*/
public static StringBuffer readFile(String path, String split) {
StringBuffer buffer = new StringBuffer();
InputStream is = null;
BufferedReader br = null;
try {
File file = new File(path);
if (file.exists()) {
is = new FileInputStream(file);
br = new BufferedReader(new InputStreamReader(is));
String content = br.readLine();
while (null != content) {
buffer.append(content).append(split);
content = br.readLine();
}
}
} catch (Exception exception) {
exception.printStackTrace();
} finally {
try {
if (null != is) {
is.close();
}
if (null != br) {
br.close();
}
} catch (Exception exception2) {
exception2.printStackTrace();
}
}
return buffer;
}
/**
* 将传入的字符串写入到指定的路径的文件下
* @param content 将要写入文件的内容
* @param path 写入内容的文件路径
*/
public static void writeFile(String content, String path) {
OutputStream fos = null;
BufferedWriter bw = null;
try {
File file = new File(path);
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
fos = new FileOutputStream(file);
bw = new BufferedWriter(new OutputStreamWriter(fos, "UTF-8"));
bw.write(content);
} catch (FileNotFoundException fnfe) {
fnfe.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
try {
if (bw != null) {
bw.close();
}
} catch (IOException ioException) {
System.err.println(ioException.getMessage());
}
}
}
/**
* 将图片写成html文件
* @param size 图片数量
* @param path 保存html文件全路径
* @param fileName 图片路径
*/
public static void writeHtmlFile(int size, String path, String fileName) {
StringBuffer buffer = new StringBuffer();
buffer.append("<!DOCTYPE html><html><head>");
buffer.append("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/>");
buffer.append("<meta name=\"viewport\" ");
buffer.append("content=\"width=device-width,minimum-scale=1,maximum-scale=1,user-scalable=no,minimal-ui\"/>");
buffer.append("<meta name=\"format-detection\" content=\"telephone=no\"/>");
buffer.append("<meta http-equiv=\"Access-Control-Allow-Origin\" content=\"*\"/>");
buffer.append("<title>touch</title>");
buffer.append("<meta name=\"keywords\" content=\"\"/>");
buffer.append("<meta name=\"description\" content=\"\"/>");
buffer.append(
"<style type=\"text/css\">body{width:100%;height:auto;position:relative;}img{max-width:100%;height:auto;margin:0 auto;}</style>");
buffer.append("</head>");
buffer.append("<body>");
for (int offset = 0; offset < size; offset++) {
buffer.append("<img src=\"" + fileName + "/" + (offset + 1) + ".png\" />");
buffer.append("<br />");
}
buffer.append("</body></html>");
// System.out.println(buffer.toString());
writeFile(buffer.toString(), path + ".html");
}
public static void writeHtmlFile(String path, String fileName) {
StringBuffer buffer = new StringBuffer();
buffer.append("<!DOCTYPE html><html><head>");
buffer.append("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/>");
buffer.append(
"<meta name=\"viewport\" content=\"width=device-width,minimum-scale=1,maximum-scale=1,user-scalable=no,minimal-ui\"/>");
buffer.append("<meta name=\"format-detection\" content=\"telephone=no\"/>");
buffer.append("<meta http-equiv=\"Access-Control-Allow-Origin\" content=\"*\"/>");
buffer.append("<title>touch</title>");
buffer.append("<meta name=\"keywords\" content=\"\"/>");
buffer.append("<meta name=\"description\" content=\"\"/>");
buffer.append(
"<style type=\"text/css\">body{width:100%;height:auto;position:relative;}img{max-width:100%;height:auto;margin:0 auto;}</style>");
buffer.append("</head>");
buffer.append("<body>");
buffer.append("<img src=\"" + fileName + "/" + fileName + ".png\" />");
buffer.append("<br />");
buffer.append("</body></html>");
// System.out.println(buffer.toString());
writeFile(buffer.toString(), path + ".html");
}
public static void write2Html(StringBuffer content, String path) {
StringBuffer buffer = new StringBuffer();
buffer.append(
"<html><head><meta http-equiv=\"Access-Control-Allow-Origin\" content=\"*\"></head><body><div align=\"left\">");
buffer.append("<p>" + content + "</p>");
buffer.append("</div></body></html>");
// System.out.println(buffer.toString());
writeFile(buffer.toString(), path + ".html");
}
public static void mkdirFiles(String filePath, String fileType) {
File file = new File(filePath + "/" + fileType);
if (!file.exists()) {
file.mkdirs();
}
}
/**
* 删除文件空行
*
* @param content
* @param outPutFile
* @throws IOException
*/
public static void rmrBlankLines(String inputFile, String outPutFile) throws IOException {
File htmFile = new File(inputFile);
// 以GB2312读取文件
BufferedReader br = null;
BufferedWriter bw = null;
try {
br = new BufferedReader(new FileReader(htmFile));
bw = new BufferedWriter(new FileWriter(new File(outPutFile)));
String result = null;
while (null != (result = br.readLine())) {
if (!"".equals(result.trim())) {
bw.write(result + "\r\n");
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (null != br) {
br.close();
}
if (null != bw) {
bw.close();
}
} catch (Exception e) {
}
}
}
/**
* @param htmFilePath
* @throws IOException
*/
public static void parseH2(String htmFilePath) throws IOException {
File htmFile = new File(htmFilePath);
Document doc = Jsoup.parse(htmFile, "UTF-8");
doc.getElementsByAttribute("h2");
Elements content = doc.getElementsByTag("h2");
for (Element meta : content) {
meta.attr("style", "text-align:center");
}
FileUtils.writeStringToFile(htmFile, doc.html(), "UTF-8");
}
/**
* @param htmFilePath
* @throws IOException
*/
public static void parseCharset(String htmFilePath) throws IOException {
File htmFile = new File(htmFilePath);
// 以GB2312读取文件
Document doc = Jsoup.parse(htmFile, "utf-8");
// 获取html节点
Elements content = doc.getElementsByAttributeValueStarting("content", "text/html;");
Elements brs = doc.getElementsByTag("<br>");
for (Element br : brs) {
br.before("<br />");
br.remove();
}
for (Element meta : content) {
// 获取content节点,修改charset属性
meta.attr("content", "text/html; charset=utf-8");
break;
}
// 转换成utf-8编码的文件写入
System.out.println(doc.html());
FileUtils.writeStringToFile(htmFile, doc.html(), "utf-8");
}
/**
* @param htmFilePath
* @throws IOException
*/
public static void parse(String htmFilePath) throws IOException {
File htmFile = new File(htmFilePath);
// 以GB2312读取文件
Document doc = Jsoup.parse(htmFile, "utf-8");
String xmlns = doc.getElementsByTag("html").attr("xmlns");
if (null == xmlns || "".equals(xmlns)) {
return;
}
doc.getElementsByTag("html").removeAttr("xmlns");
Element head = doc.head();
/*
* Elements headChildren = head.children(); for(Element children : headChildren) { Elements
* metas = children.getElementsByTag("meta"); for(Element meta : metas) { meta.remove(); } }
*/
head.appendElement("meta").attr("name", "viewport").attr("content",
"width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no");
// 获取html节点
Element element = doc.body();
Elements content = head.getElementsByAttributeValueStarting("name", "meta:page-count");
for (Element meta : content) {
String value = meta.attr("content");
try {
Integer count = Integer.valueOf(value);
Elements ps = element.getElementsByTag("p");
Iterator<Element> iterator = ps.iterator();
while (iterator.hasNext()) {
Element p = iterator.next();
String text = p.text();
if (text.equals("- " + count + " -")) {
for (int offset = count; offset > 0; offset--) {
p.remove();
p = iterator.next();
text = p.text();
}
}
if (text.equals("")) {
p.remove();
p = iterator.next();
}
p.attr("align", "center");
p.attr("style", "font-size:1.5rem;");
break;
}
} catch (Exception e) {
}
// 获取content节点,修改charset属性
// meta.attr("content", "text/html; charset=utf-8");
break;
}
// 转换成utf-8编码的文件写入
FileUtils.writeStringToFile(htmFile, "<!DOCTYPE html>" + doc.html(), "utf-8");
}
public static void checkHtmlEndTag(String htmFilePath) throws IOException {
File htmFile = new File(htmFilePath);
// 以GB2312读取文件
Document doc = Jsoup.parse(htmFile, "utf-8");
Elements all = doc.getElementsByTag("html");
for (Element element : all) {
parseElements(all, element);
}
FileUtils.writeStringToFile(htmFile, doc.html(), "utf-8");
}
public static void parseElements(Elements elements, Element element) {
int childNodeSize = elements.size();
if (0 < childNodeSize) {
for (int offset = 0; offset < childNodeSize; offset++) {
parseElements(elements.get(offset).children(), elements.get(offset));
}
} else {
String tagName = element.tagName();
String content = element.toString();
if (tagName.length() + 3 > content.length()) {
element.text("");
} else {
try {
String endTag =
content.substring(content.length() - tagName.length() - 3, content.length());
if (!("</" + tagName + ">").equals(endTag)) {
element.text("");
}
} catch (Exception w) {}
}
}
}
public static void changeImageType(String htmFilePath) throws IOException {
File htmFile = new File(htmFilePath);
// 以GB2312读取文件
Document doc = Jsoup.parse(htmFile, "utf-8");
Elements elements = doc.getElementsByTag("img");
String imgPath = "";
for (Element element : elements) {
String src = element.attr("src");
String[] sp = src.split("\\.");
String newSrc = htmFile.getParent() + File.separator + sp[0] + ".jpg";
imgPath = src;
element.attr("src", newSrc);
}
FileUtils.writeStringToFile(htmFile, doc.html(), "utf-8");
String name = htmFile.getName();
htmFilePath = htmFilePath.substring(0, htmFilePath.length() - name.length()) + imgPath;
File file = new File(htmFilePath);
File[] files = file.getParentFile().listFiles();
for (File file2 : files) {
String filePath = file2.getPath();
String[] sp = filePath.split("\\.");
String newSrc = sp[0] + ".jpg";
FileHelper.copyFile(filePath, newSrc, true);
}
}
public static void nioTransferCopy(File source, File target) {
FileChannel in = null;
FileChannel out = null;
FileInputStream inStream = null;
FileOutputStream outStream = null;
try {
inStream = new FileInputStream(source);
outStream = new FileOutputStream(target);
in = inStream.getChannel();
out = outStream.getChannel();
in.transferTo(0, in.size(), out);
} catch (IOException e) {
e.printStackTrace();
} finally {
close(inStream);
close(in);
close(outStream);
close(out);
}
}
private static boolean nioBufferCopy(File source, File target) {
FileChannel in = null;
FileChannel out = null;
FileInputStream inStream = null;
FileOutputStream outStream = null;
try {
inStream = new FileInputStream(source);
outStream = new FileOutputStream(target);
in = inStream.getChannel();
out = outStream.getChannel();
ByteBuffer buffer = ByteBuffer.allocate(4096);
while (in.read(buffer) != -1) {
buffer.flip();
out.write(buffer);
buffer.clear();
}
} catch (IOException e) {
e.printStackTrace();
return false;
} finally {
close(inStream);
close(in);
close(outStream);
close(out);
}
return true;
}
public static void customBufferStreamCopy(File source, File target) {
InputStream fis = null;
OutputStream fos = null;
try {
fis = new FileInputStream(source);
fos = new FileOutputStream(target);
byte[] buf = new byte[4096];
int i;
while ((i = fis.read(buf)) != -1) {
fos.write(buf, 0, i);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
close(fis);
close(fos);
}
}
/**
* 复制单个文件
*
* @param srcFileName 待复制的文件名
* @param destFileName 目标文件名
* @param overlay 如果目标文件存在,是否覆盖
* @return 如果复制成功返回true,否则返回false
*/
public static boolean copyFile(String srcFileName, String destFileName, boolean overlay) {
File srcFile = new File(srcFileName);
// 判断源文件是否存在
if (!srcFile.exists()) {
log.info("input file not null");
return false;
} else if (!srcFile.isFile()) {
log.info("input file is not file");
return false;
}
// 判断目标文件是否存在
File destFile = new File(destFileName);
if (destFile.exists()) {
// 如果目标文件存在并允许覆盖
if (overlay) {
// 删除已经存在的目标文件,无论目标文件是目录还是单个文件
new File(destFileName).delete();
}
} else {
// 如果目标文件所在目录不存在,则创建目录
if (!destFile.getParentFile().exists()) {
// 目标文件所在目录不存在
if (!destFile.getParentFile().mkdirs()) {
// 复制文件失败:创建目标文件所在目录失败
return false;
}
}
}
boolean result = nioBufferCopy(srcFile, destFile);
return result;
}
/**
* 复制整个目录的内容
*
* @param srcDirName 待复制目录的目录名
* @param destDirName 目标目录名
* @param overlay 如果目标目录存在,是否覆盖
* @return 如果复制成功返回true,否则返回false
*/
public static boolean copyDirectory(String srcDirName, String destDirName, boolean overlay) {
// 判断源目录是否存在
File srcDir = new File(srcDirName);
if (!srcDir.exists()) {
log.info("srcDir not found");
return false;
} else if (!srcDir.isDirectory()) {
log.info("srcDir not Directory");
return false;
}
// 如果目标目录名不是以文件分隔符结尾,则加上文件分隔符
if (!destDirName.endsWith(File.separator)) {
destDirName = destDirName + File.separator;
}
File destDir = new File(destDirName);
// 如果目标文件夹存在
if (destDir.exists()) {
// 如果允许覆盖则删除已存在的目标目录
if (overlay) {
new File(destDirName).delete();
} else {
log.info("");
return false;
}
} else {
// 创建目的目录
System.out.println("目的目录不存在,准备创建。。。");
if (!destDir.mkdirs()) {
System.out.println("复制目录失败:创建目的目录失败!");
return false;
}
}
boolean flag = true;
File[] files = srcDir.listFiles();
for (int i = 0; i < files.length; i++) {
// 复制文件
if (files[i].isFile()) {
flag = FileHelper.copyFile(files[i].getAbsolutePath(), destDirName + files[i].getName(),
overlay);
if (!flag) {
break;
}
} else if (files[i].isDirectory()) {
flag = FileHelper.copyDirectory(files[i].getAbsolutePath(),
destDirName + files[i].getName(), overlay);
if (!flag) {
break;
}
}
}
if (!flag) {
log.info("copy Directory fail");
return false;
} else {
return true;
}
}
/**
* 关闭资源
* @param object 需要关闭的对象
*/
public static void close(Object object) {
if (null == object) {
return;
}
try {
if (object instanceof InputStream) {
((InputStream) object).close();
} else if (object instanceof OutputStream) {
((OutputStream) object).close();
} else if (object instanceof Channel) {
((Channel) object).close();
}
} catch (Exception exce) {
System.err.println(exce.getMessage());
}
}
/**
* 合并excel表格的sheet
*
* @param htmFilePath html文件路径
* @throws IOException 打开文件异常
*/
public static void mergeTable(String htmFilePath) throws IOException {
File htmFile = new File(htmFilePath);
// 以GB2312读取文件
Document doc = Jsoup.parse(htmFile, "utf-8");
Integer tableMaxSize = getMaxTableSize(doc);
Elements allTable = doc.getElementsByTag("tbody");
Element max = null;
for (Element table : allTable) {
Elements elements = table.children();
if (0 >= elements.size()) {
table.parent().remove();
continue;
}
int size = elements.first().children().size();
if (size >= tableMaxSize) {
max = table;
continue;
}
for (Element tr : elements) {
Elements td = tr.children();
for (int offset = tableMaxSize; offset > td.size(); offset--) {
Element tdd = doc.createElement("td");
tr.appendChild(tdd);
}
max.appendChild(tr);
}
table.parent().remove();
}
FileUtils.writeStringToFile(htmFile, doc.html(), "utf-8");
}
private static Integer getMaxTableSize(Document doc) {
Elements allTable = doc.getElementsByTag("tbody");
TreeSet<Integer> tableSize = new TreeSet<Integer>();
for (Element table : allTable) {
Elements elements = table.children();
int size = 0;
try {
size = elements.first().children().size();
} catch (Exception e) {
size = -1;
}
if (tableSize.contains(size)) {
size--;
}
tableSize.add(size);
}
return tableSize.last();
}
/**
* 获取文件css样式
* @param src 文件
* @return 文件css样式
* @throws IOException 打开文件异常
*/
public static final StringBuffer getHtmlCss(String src) throws IOException {
File htmFile = new File(src);
// 以GB2312读取文件
Document doc = Jsoup.parse(htmFile, "utf-8");
Elements styles = doc.getElementsByTag("style");
StringBuffer csStringBuffer = new StringBuffer();
for (Element style : styles) {
csStringBuffer.append(style.toString().replace("<style>", "").replace("</style>", ""));
}
Elements links = doc.getElementsByTag("link");
for (Element style : links) {
String href = style.attr("href");
String realPath = src + File.separator + href;
StringBuffer link = FileHelper.readFile(realPath);
csStringBuffer.append(link);
}
return csStringBuffer;
}
public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass,String fileName,boolean isCreateHeader, HttpServletResponse response){
ExportParams exportParams = new ExportParams(title, sheetName);
exportParams.setCreateHeadRows(isCreateHeader);
defaultExport(list, pojoClass, fileName, response, exportParams);
}
public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass,String fileName, HttpServletResponse response){
defaultExport(list, pojoClass, fileName, response, new ExportParams(title, sheetName));
}
public static void exportExcel(List<Map<String, Object>> list, String fileName, HttpServletResponse response){
defaultExport(list, fileName, response);
}
private static void defaultExport(List<?> list, Class<?> pojoClass, String fileName, HttpServletResponse response, ExportParams exportParams) {
Workbook workbook = ExcelExportUtil.exportExcel(exportParams,pojoClass,list);
if (workbook != null);
downLoadExcel(fileName, response, workbook);
}
private static void downLoadExcel(String fileName, HttpServletResponse response, Workbook workbook) {
try {
String name = new String(fileName.getBytes("UTF-8"), "ISO8859_1");
response.setHeader("content-Type", "application/vnd.ms-excel");
response.setHeader("Content-Disposition",
"attachment;filename=" + name);
workbook.write(response.getOutputStream());
} catch (IOException e) {
throw new YeeException(e.getMessage());
}
}
private static void defaultExport(List<Map<String, Object>> list, String fileName, HttpServletResponse response) {
Workbook workbook = ExcelExportUtil.exportExcel(list, ExcelType.HSSF);
if (workbook != null);
downLoadExcel(fileName, response, workbook);
}
public static <T> List<T> importExcel(String filePath,Integer titleRows,Integer headerRows, Class<T> pojoClass){
if (ObjectUtils.isEmpty(filePath)){
return null;
}
ImportParams params = new ImportParams();
params.setTitleRows(titleRows);
params.setHeadRows(headerRows);
List<T> list = null;
try {
list = ExcelImportUtil.importExcel(new File(filePath), pojoClass, params);
}catch (NoSuchElementException e){
throw new YeeException("模板不能为空");
} catch (Exception e) {
e.printStackTrace();
throw new YeeException(e.getMessage());
}
return list;
}
public static <T> List<T> importExcel(MultipartFile file, Integer titleRows, Integer headerRows, Class<T> pojoClass){
if (file == null){
return null;
}
ImportParams params = new ImportParams();
params.setTitleRows(titleRows);
params.setHeadRows(headerRows);
List<T> list = null;
try {
list = ExcelImportUtil.importExcel(file.getInputStream(), pojoClass, params);
}catch (NoSuchElementException e){
throw new YeeException("excel文件不能为空");
} catch (Exception e) {
e.printStackTrace();
throw new YeeException(e.getMessage());
}
return list;
}
public static void exportZip(List<Map<String, Object>> list, String fileName, HttpServletResponse response) {
try {
response.setContentType("multipart/form-data");
response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(fileName, "UTF-8"));
} catch (UnsupportedEncodingException e) {
throw new YeeException("下载文件名编码时出现错误.");
}
OutputStream outputStream = null;
ZipOutputStream zos = null;
try {
outputStream = response.getOutputStream();
zos = new ZipOutputStream(outputStream);
downloadZip(fileName.replace(".zip", ""), zos, list);
} catch (IOException e) {
throw new YeeException("下载文件名编码时出现错误.");
} finally {
if(zos != null) {
try {
zos.close();
} catch (Exception e2) {
throw new YeeException("下载文件名编码时出现错误.");
}
}
if(outputStream != null) {
try {
outputStream.close();
} catch (Exception e2) {
throw new YeeException("下载文件名编码时出现错误.");
}
}
}
}
public static void downloadZip(String baseDir, ZipOutputStream zos, List<Map<String, Object>> list) {
for (Map<String, Object> map : list) {
String checkId = map.get("id").toString();
//文件名称(带后缀)
String fileName = map.get("photoData").toString();
InputStream is = null;
BufferedInputStream in = null;
byte[] buffer = new byte[1024];
int len;
//创建zip实体(一个文件对应一个ZipEntry)
ZipEntry entry = new ZipEntry(baseDir + fileName.substring(fileName.lastIndexOf('/'), fileName.length()));
try {
//获取需要下载的文件流
URL url = new URL(fileName);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
//下载
is = conn.getInputStream();
// File file = new File(fileName);
// is = new FileInputStream(file);
in = new BufferedInputStream(is);
zos.putNextEntry(entry);
//文件流循环写入ZipOutputStream
while ((len = in.read(buffer)) != -1 ) {
zos.write(buffer, 0, len);
}
} catch (Exception e) {
e.printStackTrace();
}finally {
if(entry != null) {
try {
zos.closeEntry();
} catch (Exception e2) {
}
}
if(in != null) {
try {
in.close();
} catch (Exception e2) {
}
}
if(is != null) {
try {
is.close();
}catch (Exception e) {
}
}
}
}
}
/**
* @Title: createExcelTemplate
* @Description: 生成Excel导入模板
* @param @param filePath Excel文件路径
* @param @param handers Excel列标题(数组)
* @param @param downData 下拉框数据(数组)
* @param @param downRows 下拉列的序号(数组,序号从0开始)
* @return void
* @throws
*/
public static void createExcelTemplate(String fileName, String[] handers,
List<String[]> downData, String[] downRows, HttpServletResponse response){
HSSFWorkbook wb = new HSSFWorkbook();//创建工作薄
//表头样式
HSSFCellStyle style = wb.createCellStyle();
style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式
//字体样式
HSSFFont fontStyle = wb.createFont();
fontStyle.setFontName("微软雅黑");
fontStyle.setFontHeightInPoints((short)12);
fontStyle.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
style.setFont(fontStyle);
//新建sheet
HSSFSheet sheet1 = wb.createSheet("Sheet1");
HSSFSheet sheet2 = wb.createSheet("Sheet2");
HSSFSheet sheet3 = wb.createSheet("Sheet3");
//生成sheet1内容
HSSFRow rowFirst = sheet1.createRow(0);//第一个sheet的第一行为标题
//写标题
for(int i=0;i<handers.length;i++){
HSSFCell cell = rowFirst.createCell(i); //获取第一行的每个单元格
sheet1.setColumnWidth(i, 4000); //设置每列的列宽
cell.setCellStyle(style); //加样式
cell.setCellValue(handers[i]); //往单元格里写数据
}
//设置下拉框数据
String[] arr = {"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};
int index = 0;
HSSFRow row = null;
for(int r=0;r<downRows.length;r++){
String[] dlData = downData.get(r);//获取下拉对象
int rownum = Integer.parseInt(downRows[r]);
if(dlData==null){
continue;
}
if(dlData.length<5){ //255以内的下拉
//255以内的下拉,参数分别是:作用的sheet、下拉内容数组、起始行、终止行、起始列、终止列
sheet1.addValidationData(setDataValidation(sheet1, dlData, 1, 30000, rownum ,rownum)); //超过255个报错
} else { //255以上的下拉,即下拉列表元素很多的情况
//1、设置有效性
//String strFormula = "Sheet2!$A$1:$A$5000" ; //Sheet2第A1到A5000作为下拉列表来源数据
String strFormula = "Sheet2!$"+arr[index]+"$1:$"+arr[index]+"$5000"; //Sheet2第A1到A5000作为下拉列表来源数据
sheet2.setColumnWidth(r, 4000); //设置每列的列宽
//设置数据有效性加载在哪个单元格上,参数分别是:从sheet2获取A1到A5000作为一个下拉的数据、起始行、终止行、起始列、终止列
sheet1.addValidationData(SetDataValidation(strFormula, 1, 30000, rownum, rownum)); //下拉列表元素很多的情况
//2、生成sheet2内容
for(int j=0;j<dlData.length;j++){
if(index==0){ //第1个下拉选项,直接创建行、列
row = sheet2.createRow(j); //创建数据行
sheet2.setColumnWidth(j, 4000); //设置每列的列宽
row.createCell(0).setCellValue(dlData[j]); //设置对应单元格的值
} else { //非第1个下拉选项
int rowCount = sheet2.getLastRowNum();
//System.out.println("========== LastRowNum =========" + rowCount);
if(j<=rowCount){ //前面创建过的行,直接获取行,创建列
//获取行,创建列
sheet2.getRow(j).createCell(index).setCellValue(dlData[j]); //设置对应单元格的值
} else { //未创建过的行,直接创建行、创建列
sheet2.setColumnWidth(j, 4000); //设置每列的列宽
//创建行、创建列
sheet2.createRow(j).createCell(index).setCellValue(dlData[j]); //设置对应单元格的值
}
}
}
index++;
}
}
downLoadExcel(fileName, response, wb);
}
/**
*
* @Title: SetDataValidation
* @Description: 下拉列表元素很多的情况 (255以上的下拉)
* @param @param strFormula
* @param @param firstRow 起始行
* @param @param endRow 终止行
* @param @param firstCol 起始列
* @param @param endCol 终止列
* @param @return
* @return HSSFDataValidation
* @throws
*/
private static HSSFDataValidation SetDataValidation(String strFormula,
int firstRow, int endRow, int firstCol, int endCol) {
// 设置数据有效性加载在哪个单元格上。四个参数分别是:起始行、终止行、起始列、终止列
CellRangeAddressList regions = new CellRangeAddressList(firstRow, endRow, firstCol, endCol);
DVConstraint constraint = DVConstraint.createFormulaListConstraint(strFormula);
HSSFDataValidation dataValidation = new HSSFDataValidation(regions,constraint);
dataValidation.createErrorBox("Error", "Error");
dataValidation.createPromptBox("", null);
return dataValidation;
}
/**
*
* @Title: setDataValidation
* @Description: 下拉列表元素不多的情况(255以内的下拉)
* @param @param sheet
* @param @param textList
* @param @param firstRow
* @param @param endRow
* @param @param firstCol
* @param @param endCol
* @param @return
* @return DataValidation
* @throws
*/
private static DataValidation setDataValidation(Sheet sheet, String[] textList, int firstRow, int endRow, int firstCol, int endCol) {
DataValidationHelper helper = sheet.getDataValidationHelper();
//加载下拉列表内容
DataValidationConstraint constraint = helper.createExplicitListConstraint(textList);
//DVConstraint constraint = new DVConstraint();
constraint.setExplicitListValues(textList);
//设置数据有效性加载在哪个单元格上。四个参数分别是:起始行、终止行、起始列、终止列
CellRangeAddressList regions = new CellRangeAddressList((short) firstRow, (short) endRow, (short) firstCol, (short) endCol);
//数据有效性对象
DataValidation data_validation = helper.createValidation(constraint, regions);
//DataValidation data_validation = new DataValidation(regions, constraint);
return data_validation;
}
/**
* @Title: getExcel
* @Description: 下载指定路径的Excel文件
* @param @param url 文件路径
* @param @param fileName 文件名
* @param @param response
* @return void
* @throws
*/
public static void getExcel(String url, String fileName, HttpServletResponse response,HttpServletRequest request){
try {
//1.设置文件ContentType类型,这样设置,会自动判断下载文件类型
response.setContentType("multipart/form-data");
//2.设置文件头:最后一个参数是设置下载文件名
response.setHeader("Content-disposition", "attachment; filename=\""
+ encodeChineseDownloadFileName(request, fileName+".xls") +"\"");
// response.setHeader("Content-Disposition", "attachment;filename="
// + new String(fileName.getBytes("UTF-8"), "ISO-8859-1") + ".xls"); //中文文件名
//通过文件路径获得File对象
File file = new File(url);
FileInputStream in = new FileInputStream(file);
//3.通过response获取OutputStream对象(out)
OutputStream out = new BufferedOutputStream(response.getOutputStream());
int b = 0;
byte[] buffer = new byte[2048];
while ((b=in.read(buffer)) != -1){
out.write(buffer,0,b); //4.写到输出流(out)中
}
in.close();
out.flush();
out.close();
} catch (IOException e) {
log.error("下载Excel模板异常", e);
}
}
/**
*
* @Title: encodeChineseDownloadFileName
* @Description: TODO(这里用一句话描述这个方法的作用)
* @param @param request
* @param @param pFileName
* @param @return
* @param @throws UnsupportedEncodingException
* @return String
* @throws
*/
private static String encodeChineseDownloadFileName(HttpServletRequest request, String pFileName)
throws UnsupportedEncodingException {
String filename = null;
String agent = request.getHeader("USER-AGENT");
//System.out.println("agent==========》"+agent);
if (null != agent) {
if (-1 != agent.indexOf("Firefox")) {//Firefox
filename = "=?UTF-8?B?" + (new String(org.apache.commons.codec.binary.Base64.encodeBase64(pFileName.getBytes("UTF-8")))) + "?=";
} else if (-1 != agent.indexOf("Chrome")) {//Chrome
filename = new String(pFileName.getBytes(), "ISO8859-1");
} else {//IE7+
filename = java.net.URLEncoder.encode(pFileName, "UTF-8");
filename = StringUtils.replace(filename, "+", "%20");//替换空格
}
} else {
filename = pFileName;
}
return filename;
}
/**
* @Title: delFile
* @Description: 删除文件
* @param @param filePath 文件路径
* @return void
* @throws
*/
public static void delFile(String filePath) {
java.io.File delFile = new java.io.File(filePath);
delFile.delete();
}
}
package com.yeejoin.amos.latentdanger.business.util;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
public class FreemarkerUtil {
/**
* 日志记录器
*/
private static final Logger logger = LoggerFactory.getLogger(FreemarkerUtil.class);
private static Configuration conf = null;
private static Map<String, Template> allTemplates = null;
static {
conf = new Configuration(Configuration.VERSION_2_3_23);
conf.setDefaultEncoding("UTF-8");
conf.setClassForTemplateLoading(FreemarkerUtil.class, "/temp");
allTemplates = new HashMap<>();
try {
allTemplates.put("taskTemp", conf.getTemplate("taskTemp.ftl"));
} catch (IOException e) {
logger.error(e.getMessage(), e);
throw new RuntimeException(e);
}
}
/**
* 导出设备测试结果,生成Word文档
*
* @param resultMap 测试结果数据
* @param fileType 导出文件类型
*/
public static File getDocFile(Map<String, Object> resultMap, String tempType) {
File file = null;
// 调用createDoc方法生成Word文档
file = createDoc(resultMap, tempType);
return file;
}
private static File createDoc(Map<String, Object> dataMap, String fileType) {
Date date = new Date();
String name = "template_" + date.getTime() + ".doc";
File f = new File(name);
Template t = allTemplates.get(fileType);
try {
// 这个地方不能使用FileWriter因为需要指定编码类型否则生成的Word文档会因为有无法识别的编码而无法打开
Writer w = new OutputStreamWriter(new FileOutputStream(f), "utf-8");
t.process(dataMap, w);
w.close();
} catch (Exception ex) {
logger.error(ex.getMessage(), ex);
throw new RuntimeException(ex);
}
return f;
}
}
package com.yeejoin.amos.latentdanger.business.util;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Iterator;
import java.util.Map;
public class HttpUtil {
// utf-8字符编码
private static final String CHARSET_UTF_8 = "utf-8";
// HTTP内容类型。
private static final String CONTENT_TYPE_TEXT_HTML = "text/xml";
// HTTP内容类型。相当于form表单的形式,提交数据
private static final String CONTENT_TYPE_FORM_URL = "application/x-www-form-urlencoded";
// HTTP内容类型。相当于form表单的形式,提交数据
private static final String CONTENT_TYPE_JSON_URL = "application/json;charset=utf-8";
// 连接管理器
private static PoolingHttpClientConnectionManager pool;
// 请求配置
private static RequestConfig requestConfig;
static {
try {
//System.out.println("初始化HttpClientTest~~~开始");
SSLContextBuilder builder = new SSLContextBuilder();
builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
builder.build());
// 配置同时支持 HTTP 和 HTPPS
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create().register(
"http", PlainConnectionSocketFactory.getSocketFactory()).register(
"https", sslsf).build();
// 初始化连接管理器
pool = new PoolingHttpClientConnectionManager(
socketFactoryRegistry);
// 将最大连接数增加到200,实际项目最好从配置文件中读取这个值
pool.setMaxTotal(200);
// 设置最大路由
pool.setDefaultMaxPerRoute(2);
// 根据默认超时限制初始化requestConfig
int socketTimeout = 10000;
int connectTimeout = 10000;
int connectionRequestTimeout = 10000;
requestConfig = RequestConfig.custom().setConnectionRequestTimeout(
connectionRequestTimeout).setSocketTimeout(socketTimeout).setConnectTimeout(
connectTimeout).build();
//System.out.println("初始化HttpClientTest~~~结束");
} catch (Exception e) {
e.printStackTrace();
}
// 设置请求超时时间
requestConfig = RequestConfig.custom().setSocketTimeout(50000).setConnectTimeout(50000)
.setConnectionRequestTimeout(50000).build();
}
private static CloseableHttpClient getHttpClient() {
return HttpClients.custom()
// 设置连接池管理
.setConnectionManager(pool)
// 设置请求配置
.setDefaultRequestConfig(requestConfig)
// 设置重试次数
.setRetryHandler(new DefaultHttpRequestRetryHandler(0, false))
.build();
}
/**
* 发送Post请求
*/
private static String sendHttpPost(HttpPost httpPost) {
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
// 响应内容
String responseContent = null;
try {
// 创建默认的httpClient实例.
httpClient = getHttpClient();
// 配置请求信息
httpPost.setConfig(requestConfig);
// 执行请求
response = httpClient.execute(httpPost);
// 得到响应实例
HttpEntity entity = response.getEntity();
// 可以获得响应头
// Header[] headers = response.getHeaders(HttpHeaders.CONTENT_TYPE);
// for (Header header : headers) {
// System.out.println(header.getName());
// }
// 得到响应类型
// System.out.println(ContentType.getOrDefault(response.getEntity()).getMimeType());
// 判断响应状态
if (response.getStatusLine().getStatusCode() >= 300) {
throw new Exception(
"HTTP Request is not success, Response code is " + response.getStatusLine().getStatusCode());
}
if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode() || HttpStatus.SC_CREATED == response.getStatusLine().getStatusCode()) {
responseContent = EntityUtils.toString(entity, CHARSET_UTF_8);
EntityUtils.consume(entity);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
// 释放资源
if (response != null) {
response.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return responseContent;
}
/**
* 发送Post请求
*
* @param httpPut
* @return
*/
private static String sendHttpPut(HttpPut httpPut) {
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
// 响应内容
String responseContent = null;
try {
// 创建默认的httpClient实例.
httpClient = getHttpClient();
// 配置请求信息
httpPut.setConfig(requestConfig);
// 执行请求
response = httpClient.execute(httpPut);
// 得到响应实例
HttpEntity entity = response.getEntity();
// 可以获得响应头
// Header[] headers = response.getHeaders(HttpHeaders.CONTENT_TYPE);
// for (Header header : headers) {
// System.out.println(header.getName());
// }
// 得到响应类型
// System.out.println(ContentType.getOrDefault(response.getEntity()).getMimeType());
// 判断响应状态
if (response.getStatusLine().getStatusCode() >= 300) {
throw new Exception(
"HTTP Request is not success, Response code is " + response.getStatusLine().getStatusCode());
}
if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode() || HttpStatus.SC_CREATED == response.getStatusLine().getStatusCode()) {
responseContent = EntityUtils.toString(entity, CHARSET_UTF_8);
EntityUtils.consume(entity);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
// 释放资源
if (response != null) {
response.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return responseContent;
}
/**
* 发送Post请求
*
* @param httpDelete
* @return
*/
private static String sendHttpDelete(HttpDelete httpDelete) {
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
// 响应内容
String responseContent = null;
try {
// 创建默认的httpClient实例.
httpClient = getHttpClient();
// 配置请求信息
httpDelete.setConfig(requestConfig);
// 执行请求
response = httpClient.execute(httpDelete);
// 得到响应实例
HttpEntity entity = response.getEntity();
// 可以获得响应头
// Header[] headers = response.getHeaders(HttpHeaders.CONTENT_TYPE);
// for (Header header : headers) {
// System.out.println(header.getName());
// }
// 得到响应类型
// System.out.println(ContentType.getOrDefault(response.getEntity()).getMimeType());
// 判断响应状态
if (response.getStatusLine().getStatusCode() >= 300) {
throw new Exception(
"HTTP Request is not success, Response code is " + response.getStatusLine().getStatusCode());
}
if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode() || HttpStatus.SC_CREATED == response.getStatusLine().getStatusCode()) {
responseContent = EntityUtils.toString(entity, CHARSET_UTF_8);
EntityUtils.consume(entity);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
// 释放资源
if (response != null) {
response.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return responseContent;
}
/**
* 发送Get请求
*
* @param httpGet
* @return
*/
private static String sendHttpGet(HttpGet httpGet) {
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
// 响应内容
String responseContent = null;
try {
// 创建默认的httpClient实例.
httpClient = getHttpClient();
// 配置请求信息
httpGet.setConfig(requestConfig);
// 执行请求
response = httpClient.execute(httpGet);
// 得到响应实例
HttpEntity entity = response.getEntity();
// 可以获得响应头
// Header[] headers = response.getHeaders(HttpHeaders.CONTENT_TYPE);
// for (Header header : headers) {
// System.out.println(header.getName());
// }
// 得到响应类型
// System.out.println(ContentType.getOrDefault(response.getEntity()).getMimeType());
// 判断响应状态
if (response.getStatusLine().getStatusCode() >= 300) {
throw new Exception(
"HTTP Request is not success, Response code is " + response.getStatusLine().getStatusCode());
}
if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
responseContent = EntityUtils.toString(entity, CHARSET_UTF_8);
EntityUtils.consume(entity);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
// 释放资源
if (response != null) {
response.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return responseContent;
}
/**
* 发送 post请求
*
* @param httpUrl 地址
*/
public static String sendHttpPost(String httpUrl) {
// 创建httpPost
HttpPost httpPost = new HttpPost(httpUrl);
return sendHttpPost(httpPost);
}
/**
* 发送 delete请求
*
* @param httpUrl 地址
*/
public static String sendHttpDelete(String httpUrl) {
// 创建httpPost
HttpDelete httpDelete = new HttpDelete(httpUrl);
return sendHttpDelete(httpDelete);
}
/**
* 发送 post请求
*
* @param httpUrl 地址
*/
public static String sendHttpPostWithHeader(String httpUrl, Map<String, String> headerMap) {
// 创建httpPost
HttpPost httpPost = new HttpPost(httpUrl);
for (Map.Entry<String, String> entry : headerMap.entrySet()) {
httpPost.setHeader(entry.getKey(), entry.getValue());
}
return sendHttpPost(httpPost);
}
/**
* 发送 get请求
*
* @param httpUrl
*/
public static String sendHttpGet(String httpUrl) {
// 创建get请求
HttpGet httpGet = new HttpGet(httpUrl);
return sendHttpGet(httpGet);
}
/**
* 发送 delete请求带请求头
*/
public static String sendHttpDeleteWithHeader(String httpUrl, Map<String, String> headerMap) {
// 创建get请求
HttpDelete httpDelete = new HttpDelete(httpUrl);
for (Map.Entry<String, String> entry : headerMap.entrySet()) {
httpDelete.setHeader(entry.getKey(), entry.getValue());
}
return sendHttpDelete(httpDelete);
}
/**
* 发送 get请求带请求头
*/
public static String sendHttpGetWithHeader(String httpUrl, Map<String, String> headerMap) {
// 创建get请求
HttpGet httpGet = new HttpGet(httpUrl);
for (Map.Entry<String, String> entry : headerMap.entrySet()) {
httpGet.setHeader(entry.getKey(), entry.getValue());
}
return sendHttpGet(httpGet);
}
/**
* 发送 delete请求带请求头
*/
public static String sendHttpDeleteJsonWithHeader(String httpUrl, String paramsJson, Map<String, String> headerMap) {
StringBuffer content = new StringBuffer();
try {
URL url = new URL(httpUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("DELETE");
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
for (Map.Entry<String, String> entry : headerMap.entrySet()) {
connection.setRequestProperty(entry.getKey(), entry.getValue());
}
PrintWriter printWriter = new PrintWriter(connection.getOutputStream());
printWriter.write(paramsJson);
printWriter.flush();
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = br.readLine()) != null) {
content.append(line);
}
br.close();
connection.disconnect();
} catch (Exception e) {
}
return content.toString();
}
/**
* 发送 post请求
*
* @param httpUrl 地址
* @param params 参数(格式:key1=value1&key2=value2)
*/
public static String sendHttpPost(String httpUrl, String params) {
HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPost
try {
// 设置参数
if (params != null && params.trim().length() > 0) {
StringEntity stringEntity = new StringEntity(params, "UTF-8");
stringEntity.setContentType(CONTENT_TYPE_FORM_URL);
httpPost.setEntity(stringEntity);
}
} catch (Exception e) {
e.printStackTrace();
}
return sendHttpPost(httpPost);
}
/**
* 发送 post请求
*
* @param maps 参数
*/
public static String sendHttpPost(String httpUrl, Map<String, String> maps) {
String parem = convertStringParamter(maps);
return sendHttpPost(httpUrl, parem);
}
/**
* 发送 post请求 发送json数据
*
* @param httpUrl 地址
* @param paramsJson 参数(格式 json)
*/
public static String sendHttpPostJsonWithHeader(String httpUrl, String paramsJson, Map<String, String> headerMap) {
HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPost
try {
for (Map.Entry<String, String> entry : headerMap.entrySet()) {
httpPost.setHeader(entry.getKey(), entry.getValue());
}
// 设置参数
if (paramsJson != null && paramsJson.trim().length() > 0) {
StringEntity stringEntity = new StringEntity(paramsJson, "UTF-8");
stringEntity.setContentType(CONTENT_TYPE_JSON_URL);
httpPost.setEntity(stringEntity);
}
} catch (Exception e) {
e.printStackTrace();
}
return sendHttpPost(httpPost);
}
/**
* 发送 put请求 发送json数据
*
* @param httpUrl 地址
* @param paramsJson 参数(格式 json)
*/
public static String sendHttpPutJsonWithHeader(String httpUrl, String paramsJson, Map<String, String> headerMap) {
HttpPut httpPost = new HttpPut(httpUrl);// 创建HttpPut
try {
for (Map.Entry<String, String> entry : headerMap.entrySet()) {
httpPost.setHeader(entry.getKey(), entry.getValue());
}
// 设置参数
if (paramsJson != null && paramsJson.trim().length() > 0) {
StringEntity stringEntity = new StringEntity(paramsJson, "UTF-8");
stringEntity.setContentType(CONTENT_TYPE_JSON_URL);
httpPost.setEntity(stringEntity);
}
} catch (Exception e) {
e.printStackTrace();
}
return sendHttpPut(httpPost);
}
/**
* 发送 post请求 发送json数据
*
* @param httpUrl 地址
* @param paramsJson 参数(格式 json)
*/
public static String sendHttpPostJson(String httpUrl, String paramsJson) {
HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPost
try {
// 设置参数
if (paramsJson != null && paramsJson.trim().length() > 0) {
StringEntity stringEntity = new StringEntity(paramsJson, "UTF-8");
stringEntity.setContentType(CONTENT_TYPE_JSON_URL);
httpPost.setEntity(stringEntity);
}
} catch (Exception e) {
e.printStackTrace();
}
return sendHttpPost(httpPost);
}
/**
* 发送 post请求 发送xml数据
*
* @param httpUrl 地址
* @param paramsXml 参数(格式 Xml)
*/
public static String sendHttpPostXml(String httpUrl, String paramsXml) {
HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPost
try {
// 设置参数
if (paramsXml != null && paramsXml.trim().length() > 0) {
StringEntity stringEntity = new StringEntity(paramsXml, "UTF-8");
stringEntity.setContentType(CONTENT_TYPE_TEXT_HTML);
httpPost.setEntity(stringEntity);
}
} catch (Exception e) {
e.printStackTrace();
}
return sendHttpPost(httpPost);
}
/**
* 将map集合的键值对转化成:key1=value1&key2=value2 的形式
*
* @param parameterMap 需要转化的键值对集合
* @return 字符串
*/
private static String convertStringParamter(Map parameterMap) {
StringBuffer parameterBuffer = new StringBuffer();
if (parameterMap != null) {
Iterator iterator = parameterMap.keySet().iterator();
String key = null;
String value = null;
while (iterator.hasNext()) {
key = (String) iterator.next();
if (parameterMap.get(key) != null) {
value = (String) parameterMap.get(key);
} else {
value = "";
}
parameterBuffer.append(key).append("=").append(value);
if (iterator.hasNext()) {
parameterBuffer.append("&");
}
}
}
return parameterBuffer.toString();
}
}
\ No newline at end of file
package com.yeejoin.amos.latentdanger.business.util;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
public class RandomUtil {
public static String buildOrderNo() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
String newDate = sdf.format(new Date());
String result = "";
Random random = new Random();
for (int i = 0; i < 3; i++) {
result += random.nextInt(10);
}
return newDate + result;
}
}
package com.yeejoin.amos.latentdanger.business.util;
import java.math.BigDecimal;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class StringUtil {
private static Pattern NOT_ZERO_AT_THE_END = Pattern.compile("[1-9]+\\d*[1-9]+");
private static Pattern numericPattern = Pattern.compile("-?[0-9]+\\.?[0-9]*");
/**
* 鍒ゆ柇瀵硅薄鏄惁涓虹┖
*
* @param str
* @return
*/
public static boolean isNotEmpty(Object str) {
boolean flag = true;
if (str != null && !str.equals("")) {
if (str.toString().length() > 0) {
flag = true;
}
} else {
flag = false;
}
return flag;
}
/***************************************************************************
* repeat - 閫氳繃婧愬瓧绗︿覆閲嶅鐢熸垚N娆$粍鎴愭柊鐨勫瓧绗︿覆銆�
*
* @param src
* - 婧愬瓧绗︿覆 渚嬪: 绌烘牸(" "), 鏄熷彿("*"), "娴欐睙" 绛夌瓑...
* @param num
* - 閲嶅鐢熸垚娆℃暟
* @return 杩斿洖宸茬敓鎴愮殑閲嶅瀛楃涓�
* @version 1.0 (2006.10.10) Wilson Lin
**************************************************************************/
public static String repeat(String src, int num) {
StringBuffer s = new StringBuffer();
for (int i = 0; i < num; i++)
s.append(src);
return s.toString();
}
/**
* 鍒ゆ柇鏄惁鏁板瓧琛ㄧず
*
* @param
* @return 鏄惁鏁板瓧鐨勬爣蹇�
*/
public static boolean isNumeric(String str) {
// 璇ユ鍒欒〃杈惧紡鍙互鍖归厤鎵�鏈夌殑鏁板瓧 鍖呮嫭璐熸暟
String bigStr;
try {
bigStr = new BigDecimal(str).toString();
} catch (Exception e) {
return false;//寮傚父 璇存槑鍖呭惈闈炴暟瀛椼��
}
Matcher isNum = numericPattern.matcher(bigStr); // matcher鏄叏鍖归厤
if (!isNum.matches()) {
return false;
}
return true;
}
public static int toInt(String s) {
if (s != null && !"".equals(s.trim())) {
try {
return Integer.parseInt(s);
} catch (Exception e) {
return 0;
}
}
return 0;
}
/**
* 鎴彇鍓嶅悗閮戒笉鏄�0鐨勬暟瀛楀瓧绗︿覆
* <p>
* 12010102 => 12010102
* 12010100 => 120101
* ab1201100b => 12011
*
* @param str
* @return
*/
public static String delEndZero(String str) {
Matcher mat = NOT_ZERO_AT_THE_END.matcher(str);
boolean rs = mat.find();
if (rs) {
return mat.group(0);
}
return null;
}
/**
* <pre>
* 绉婚櫎瀛楃涓插悗闈㈢殑0
* </pre>
*
* @param s
* @return
*/
public static String removeSufixZero(String s) {
if (s == null) {
return "";
}
while (s.endsWith("0")) {
if (s.equals("0")) {
s = "";
break;
}
s = s.substring(0, s.length() - 1);
}
return s;
}
public static String notNull(String s){
return s!=null?s:"";
}
public static boolean isStartWithDigit(String str){
char firstCharacter = str.charAt(0);
return Character.isDigit(firstCharacter);
}
public static void main(String[] args){
System.out.println(isStartWithDigit("a3730e937-17e5-4720-8f69-99e8d87d2ee7"));
}
}
package com.yeejoin.amos.latentdanger.business.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.tika.Tika;
import org.apache.tika.exception.TikaException;
import org.apache.tika.metadata.Metadata;
import org.apache.tika.parser.AutoDetectParser;
import org.apache.tika.parser.ParseContext;
import org.apache.tika.parser.Parser;
import org.apache.tika.sax.BodyContentHandler;
import org.apache.tika.sax.ToHTMLContentHandler;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class TikaUtils {
/**
* 解析各种类型文件
*
* @param 文件路径
* @return 文件内容字符串
* @throws TikaException
* @throws IOException
*/
public static String parse(String path) throws IOException, TikaException {
Tika tika = new Tika();
return tika.parseToString(new File(path));
}
public static String fileToTxt(File file) {
org.apache.tika.parser.Parser parser = new AutoDetectParser();
try {
InputStream inputStream = new FileInputStream(file);
DefaultHandler handler = new BodyContentHandler();
Metadata metadata = new Metadata();
ParseContext parseContext = new ParseContext();
parseContext.set(Parser.class, parser);
parser.parse(inputStream, handler, metadata, parseContext);
/*
* for (String string : metadata.names()) {
* System.out.println(string+":"+metadata.get(string)); }
*/
inputStream.close();
return handler.toString();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static String parseToHTML(String fileName, String outPutFile)
throws IOException, SAXException, TikaException {
ContentHandler handler = new ToHTMLContentHandler();
AutoDetectParser parser = new AutoDetectParser();
Metadata metadata = new Metadata();
InputStream stream = null;
try {
stream = new FileInputStream(new File(fileName));
parser.parse(stream, handler, metadata);
FileHelper.writeFile(handler.toString(), outPutFile + ".html");
FileHelper.parse(outPutFile + ".html");
return null;
} catch (Exception e) {
e.printStackTrace();
} finally {
}
return null;
}
}
package com.yeejoin.amos.latentdanger.business.util;
//请求参数
public class Toke {
public String toke;
public String product;
public String appKey;
public String getToke() {
return toke;
}
public void setToke(String toke) {
this.toke = toke;
}
public String getProduct() {
return product;
}
public void setProduct(String product) {
this.product = product;
}
public String getAppKey() {
return appKey;
}
public void setAppKey(String appKey) {
this.appKey = appKey;
}
}
package com.yeejoin.amos.latentdanger.business.util;
import java.io.IOException;
import java.io.StringWriter;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import org.apache.commons.beanutils.BeanUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
import com.yeejoin.amos.latentdanger.core.util.StringUtil;
public class ToolUtils {
public static Document map2xml(Map<String, Object> map, String rootName) {
Document doc = DocumentHelper.createDocument();// 创建一个Document对象
Element root = DocumentHelper.createElement(rootName); // 创建根节点
doc.add(root);
map2xml(map, root);
return doc;
}
@SuppressWarnings({ "rawtypes", "unchecked" })
private static Element map2xml(Map<String, Object> map, Element body) {
Set<Entry<String, Object>> entries = map.entrySet();
for (Entry<String, Object> entry : entries) {
String key = entry.getKey();
Object value = entry.getValue();
if (key.startsWith("@")) {// 属性
body.addAttribute(key.substring(1, key.length()), value.toString());
} else if (key.equals("#text")) { // 有属性时的文本
body.setText(value.toString());
} else {
if (value instanceof java.util.List) {
List list = (List) value;
Object obj;
for (int i = 0; i < list.size(); i++) {
obj = list.get(i);
// list里是map或String,不会存在list里直接是list的
if (obj instanceof java.util.Map) {
Element subElement = body.addElement(key);
map2xml((Map) list.get(i), subElement);
} else {
body.addElement(key).setText((String) list.get(i));
}
}
} else if (value instanceof java.util.Map) {
Element subElement = body.addElement(key);
map2xml((Map) value, subElement);
} else {
body.addElement(key).setText(value.toString());
}
}
}
return body;
}
/**
* 格式化输出xml
*
* @param document
* @return
* @throws DocumentException
* @throws IOException
*/
public static String formatXml(Document document) throws DocumentException, IOException {
// 格式化输出格式
OutputFormat format = OutputFormat.createPrettyPrint();
// format.setEncoding("UTF-8");
StringWriter writer = new StringWriter();
// 格式化输出流
XMLWriter xmlWriter = new XMLWriter(writer, format);
// 将document写入到输出流
xmlWriter.write(document);
xmlWriter.close();
return writer.toString();
}
public static String map2Xml(Map<String, Object> map, String rootName) {
try {
return formatXml(map2xml(map, rootName));
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
// Map --> Bean 2: 利用org.apache.commons.beanutils 工具类实现 Map --> Bean
public static void transMap2Bean2(Map<String, Object> map, Object obj) {
if (map == null || obj == null) {
return;
}
try {
BeanUtils.populate(obj, map);
} catch (Exception e) {
System.out.println("transMap2Bean2 Error " + e);
}
}
// Map --> Bean 1: 利用Introspector,PropertyDescriptor实现 Map --> Bean
public static void transMap2Bean(Map<String, Object> map, Object obj) {
try {
BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor property : propertyDescriptors) {
String key = property.getName();
if (map.containsKey(key)) {
Object value = map.get(key);
// 得到property对应的setter方法
Method setter = property.getWriteMethod();
setter.invoke(obj, value);
}
}
} catch (Exception e) {
System.out.println("transMap2Bean Error " + e);
}
return;
}
// Bean --> Map 1: 利用Introspector和PropertyDescriptor 将Bean --> Map
public static Map<String, Object> transBean2Map(Object obj) {
if(obj == null){
return null;
}
Map<String, Object> map = new HashMap<String, Object>();
try {
BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor property : propertyDescriptors) {
String key = property.getName();
// 过滤class属性
if (!key.equals("class")) {
// 得到property对应的getter方法
Method getter = property.getReadMethod();
Object value = getter.invoke(obj);
map.put(key, value);
}
}
} catch (Exception e) {
System.out.println("transBean2Map Error " + e);
}
return map;
}
public static List<String> transBeanList(String s){
List<String> list = new ArrayList<String>();
if(StringUtil.isNotEmpty(s)){
String[] str = s.split(",");
list = Arrays.asList(str);
}
return list;
}
}
package com.yeejoin.amos.latentdanger.business.util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class WordFactory implements AbstractHtml {
private static final Logger log = LoggerFactory.getLogger(WordFactory.class);
/**
* 将word转换为html
*
* @param inputFile 需要转换的word文档
* @param outputFile 转换为html文件名称(全路径)
* @throws Exception
*/
@Override
public void createHtml(String inputFile, String outputFile) throws Exception {
log.info("将word转换为html文件开始,输出文件 [" + outputFile + ".html]......");
long startTime = System.currentTimeMillis();
AbstractHtml html = new WordHtml();
html.createHtml(inputFile, outputFile);
log.info("将word转换为html文件......ok");
log.info("Generate " + outputFile + ".html with " + (System.currentTimeMillis() - startTime)
+ " ms.");
}
}
package com.yeejoin.amos.latentdanger.business.util;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.converter.PicturesManager;
import org.apache.poi.hwpf.converter.WordToHtmlConverter;
import org.apache.poi.hwpf.usermodel.Picture;
import org.apache.poi.hwpf.usermodel.PictureType;
import org.apache.poi.xwpf.converter.core.FileImageExtractor;
import org.apache.poi.xwpf.converter.core.IURIResolver;
import org.apache.poi.xwpf.converter.core.IXWPFConverter;
import org.apache.poi.xwpf.converter.xhtml.XHTMLConverter;
import org.apache.poi.xwpf.converter.xhtml.XHTMLOptions;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import java.io.*;
import java.util.List;
public class WordHtml implements AbstractHtml {
private static final Logger log = LoggerFactory.getLogger(WordHtml.class);
@Override
public void createHtml(String inputFile, String outputFile) throws Exception {
log.info("将word转换为html文件开始,输出文件 [" + outputFile + ".html]......");
long startTime = System.currentTimeMillis();
InputStream is = null;
try {
File file = new File(outputFile);
if (!file.exists()) {
file.mkdirs();
}
File input = new File(inputFile);
if (!file.exists()) {
log.error("file not found:" + inputFile);
}
is = new FileInputStream(input);
if (FileHelper.isWord2003(input)) {
convertDoc2Html(is, outputFile);
} else if (FileHelper.isWord2007(input)) {
convertDocx2Html(is, outputFile);
} else {
TikaUtils.parseToHTML(inputFile, outputFile);
}
} finally {
try {
if (null != is) {
is.close();
}
} catch (Exception e) {
}
}
log.info("将word转换为html文件......ok");
log.info("Generate " + outputFile + ".html with " + (System.currentTimeMillis() - startTime)
+ " ms.");
}
/**
* 将doc文档转换为html文件
*
* @param fileName 需要转换的doc文件
* @param outPutFile 输出html文件的全路径
* @throws TransformerException
* @throws IOException
* @throws ParserConfigurationException
* @see
* @since 1.7
*/
private static void convertDoc2Html(InputStream is, String outPutFile)
throws TransformerException, IOException, ParserConfigurationException {
StreamResult streamResult = null;
ByteArrayOutputStream out = null;
try {
String[] outPutFiles = outPutFile.split("\\\\");
outPutFiles = outPutFiles[outPutFiles.length - 1].split("/");
final String root = outPutFiles[outPutFiles.length - 1];
// 将文件转换为poi数据结构
HWPFDocument wordDocument = new HWPFDocument(is);
Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
// 获取word转换为html的句柄
WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter(document);
// 设置html文件中图片引入路径
wordToHtmlConverter.setPicturesManager(new PicturesManager() {
public String savePicture(byte[] content, PictureType pictureType, String suggestedName,
float widthInches, float heightInches) {
return root + "/" + suggestedName;
}
});
wordToHtmlConverter.processDocument(wordDocument);
// #start save pictures
List<Picture> pics = wordDocument.getPicturesTable().getAllPictures();
if (pics != null) {
for (int i = 0; i < pics.size(); i++) {
Picture pic = (Picture) pics.get(i);
try {
// 指定doc文档中转换后图片保存的路径
pic.writeImageContent(
new FileOutputStream(outPutFile + "/" + pic.suggestFullFileName()));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
// #end save pictures
out = new ByteArrayOutputStream();
streamResult = new StreamResult(out);
TransformerFactory tf = TransformerFactory.newInstance();
// 创建执行从 Source 到 Result 的复制的新 Transformer。
Transformer serializer = tf.newTransformer();
serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); // 文件编码方式
serializer.setOutputProperty(OutputKeys.INDENT, "yes"); // indent 指定了当输出结果树时,Transformer
// 是否可以添加额外的空白;其值必须为 yes 或 no
serializer.setOutputProperty(OutputKeys.METHOD, "html"); // 指定输出文件的后缀名
Document htmlDocument = wordToHtmlConverter.getDocument();
DOMSource domSource = new DOMSource(htmlDocument);
serializer.transform(domSource, streamResult);
String content = new String(out.toByteArray());
FileHelper.writeFile(content, outPutFile + ".html");
// FileHelper.parseCharset(outPutFile + ".html");
// System.out.println(new String(out.toByteArray()));
} finally {
if (null != out) {
out.close();
}
}
}
/**
* 将docx文件转换为html @param is @param fileOutName 输出文件的具体路径 @throws IOException @see @since
* 1.7 @exception
*/
private static void convertDocx2Html(InputStream is, String fileOutName) throws IOException {
OutputStream out = null;
XWPFDocument document = null;
try {
// final String root = fileOutName.substring(fileOutName.lastIndexOf("/") + 1);
String[] outPutFiles = fileOutName.split("\\\\");
outPutFiles = outPutFiles[outPutFiles.length - 1].split("/");
final String root = outPutFiles[outPutFiles.length - 1];
long startTime = System.currentTimeMillis();
// 获取解析处理类
document = new XWPFDocument(is);
XHTMLOptions options = XHTMLOptions.create();// .indent(4);
// Extract image
File imageFolder = new File(fileOutName);
if (!imageFolder.exists()) {
imageFolder.mkdirs();
}
// 设置图片保存路径
options.setExtractor(new FileImageExtractor(imageFolder));
// URI resolver
options.URIResolver(new IURIResolver() {
@Override
public String resolve(String uri) {
return root + File.separatorChar + uri;
}
});
out = new FileOutputStream(new File(fileOutName + ".html"));
IXWPFConverter<XHTMLOptions> xhtmlCoverter = XHTMLConverter.getInstance();
xhtmlCoverter.convert(document, out, options);
// FileHelper.parseCharset(fileOutName + ".html");
log.info(
"Generate " + fileOutName + " with " + (System.currentTimeMillis() - startTime) + " ms.");
} finally {
try {
if (null != out) {
out.close();
}
if (null != document) {
document.close();
}
} catch (Exception e) {
}
}
}
public static void xml2Ttml(String docPath, String xsltPath, String hrmlPath){
FileInputStream fis= null;
FileInputStream fis1= null;
try {
//创建XML的文件输入流
fis = new FileInputStream(docPath);
Source source=new StreamSource(fis);
//创建XSL文件的输入流
fis1 = new FileInputStream(xsltPath);
Source template=new StreamSource(fis1);
PrintStream stm=new PrintStream(new File(hrmlPath));
//讲转换后的结果输出到 stm 中即 F:\123.html
Result result=new StreamResult(stm);
//根据XSL文件创建准个转换对象
Transformer transformer=TransformerFactory.newInstance().newTransformer(template);
//处理xml进行交换
transformer.transform(source, result);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (TransformerException e) {
e.printStackTrace();
} finally {
//关闭文件流
try {
if(null != fis1){
fis1.close();
}
if(null != fis){
fis.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
package com.yeejoin.amos.latentdanger.business.vo;
import lombok.Data;
import java.util.Date;
/**
* @author keyong
* @title: DangerTimeAxisVo
* <pre>
* @description: 隐患时间轴Vo
* </pre>
* @date 2021/3/11 15:30
*/
@Data
public class DangerTimeAxisVo {
private Long dangerId;
private Long executeUserId;
private String userName;
private Date createDate;
private Date updateDate;
private String executeResult;
private String dangerState;
private String dangerName;
private String structureId;
private String structureName;
private String reformType;
private Date reformLimitDate;
private Date delayLimitDate;
private String xAxis;
private String row1;
private String row2;
}
package com.yeejoin.amos.latentdanger.business.vo;
import lombok.Data;
import java.util.List;
/**
* 风险点信息
*
* @author DELL
*/
@Data
public class LatentDangerDetailRiskVo {
private String pointName;
private String pointNo;
private String belongDepartmentName;
private String pointLevel;
private List<String> basis;
/**
* 计划名称
*/
private String planName;
/**
* 检查时间
*/
private String checkTime;
/**
* 检查人
*/
private String checkUser;
}
package com.yeejoin.amos.latentdanger.business.vo;
import com.alibaba.fastjson.JSONObject;
import com.yeejoin.amos.latentdanger.business.entity.mybatis.extend.LatentDangerFlowRecordBo;
import lombok.Data;
import java.util.List;
@Data
public class LatentDangerDetailVo {
private Long dangerId;
private String dangerName;
private String level;
private String levelDesc;
private String remark;
private String position;
private String reformTypeDesc;
private String reformLimitDate;
private JSONObject reformJson;
private Long currentFlowRecordId;
private String dangerState;
private String dangerType;
private String dangerStateDesc;
private Boolean currentUserCanExcute;
private List<String> photoUrls;
private LatentDangerDetailRiskVo riskInfo;
private JSONObject reviewInfo;
private JSONObject reformInfo;
private JSONObject recheckInfo;
private List<LatentDangerFlowRecordBo> records;
private String delayLimitDate;
private String problemDescription;
private String reasonAnalysis;
private String inferOtherThings;
private String taskId;
}
package com.yeejoin.amos.latentdanger.business.vo;
import lombok.Data;
@Data
public class LatentDangerListVo {
private Long dangerId;
private String dangerName;
private String discovererUserName;
private String level;
private String levelDesc;
private String limitDesc;
private String state;
private String stateDesc;
private Integer overtimeState;
private String taskId;
}
package com.yeejoin.amos.latentdanger.common.remote;
import com.alibaba.fastjson.JSONObject;
import com.yeejoin.amos.latentdanger.business.feign.FeignConfiguration;
import com.yeejoin.amos.latentdanger.business.util.CommonResponse;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.*;
@FeignClient(name = "${Security.fegin.name}", configuration = FeignConfiguration.class)
public interface IAMOSSecurityServer {
@GetMapping(value = "/v1/company/tree")
CommonResponse listCompanyTree();
@GetMapping(value = "/v1/user/list")
CommonResponse listUserByMenuCode(@RequestParam("permissionType") String permissionType,
@RequestParam("path") String path);
@GetMapping(value = "/v1/department/{departmentId}")
CommonResponse getDepartmentByDeptId(@PathVariable("departmentId") String departmentId);
@GetMapping(value = "/v1/department/list/{departmentIds}")
CommonResponse listDepartmentByDeptIds(@PathVariable("departmentIds") String departmentIds);
/**
* 根据公司编号查询部门集合(数组)
*/
@GetMapping(value = "/v1/department/tree/{companyId}")
CommonResponse listDepartmentsByCompanyId(@PathVariable("companyId") String companyId);
/**
* 根据公司编号查询用户集合
*/
@GetMapping(value = "/v1/department/tree/{companyId}")
CommonResponse listUserByCompanyId(@PathVariable("companyId") String companyId);
@GetMapping(value = "/v1/user/list/role/{roleIds}")
CommonResponse listUserByRoleIds(@PathVariable("roleIds") String roleIds);
@GetMapping(value = "/v1/user/list/batch/{userIds}")
CommonResponse listUserByUserIds(@PathVariable("userIds") String userIds, @RequestParam(value="needDetail",required = false) Boolean needDetail);
@GetMapping(value = "/v1/user/{userId}")
CommonResponse getUserById(@PathVariable("userId") String userId);
@GetMapping(value = "/v1/user/me")
CommonResponse getUserByToken();
/**
* 根据公司组织机构代码查询用户集合
*/
@GetMapping(value = "/v1/company")
CommonResponse listUserByOrgCode(@RequestParam("orgCode") String orgCode);
@GetMapping(value = "/v1/user/list/dept/{departmentId}")
CommonResponse listUserByDepartmentId(@PathVariable("departmentId") String departmentId);
@GetMapping(value = "/v1/company/subtree/{companyId}")
CommonResponse getCompanyTreeByCompanyId(@PathVariable("companyId") String companyId);
@GetMapping(value = "/v1/department/tree/{companyId}")
CommonResponse getDepartmentTreeByCompanyId(@PathVariable("companyId") String companyId);
@GetMapping(value = "/v1/permission/tree/curruser")
CommonResponse listPermissionTree(@RequestParam("menuAgent") String menuAgent);
@GetMapping(value = "/v1/{dictCode}/values")
CommonResponse listDictionaryByDictCode(@RequestParam("dictCode") String dictCode);
@PostMapping(value = "/v1/system/appLogin")
CommonResponse loginFromApp(@RequestBody JSONObject appLoginParam);
@DeleteMapping(value = "/v1/system/loginOut")
CommonResponse loginOutFromApp();
@GetMapping(value = "/v1/user/tree/{companyId}")
CommonResponse listDepartmentUserTree(@PathVariable("companyId") String companyId);
@PutMapping(value = "/v1/user/{userId}/password")
CommonResponse editPassword(@PathVariable("userId") String userId,
@RequestBody JSONObject model);
@GetMapping(value = "/v1/permission/list/{userId}/{permissionType}/path")
CommonResponse getMenuPathByUserIdAndPermissionType(@PathVariable("userId") String userId,
@PathVariable("permissionType") String permissionType);
@GetMapping(value = "/v1/role/list")
CommonResponse listRoleByTypeAndPath(@RequestParam("permissionType") String permissionType,
@RequestParam("path") String path);
}
package com.yeejoin.amos.latentdanger.common.remote;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yeejoin.amos.latentdanger.business.util.HttpUtil;
import com.yeejoin.amos.latentdanger.common.enums.WorkFlowRiskFactorUriEnum;
import com.yeejoin.amos.latentdanger.core.common.request.LatentDangerResultPushSpcRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.util.Map;
@Service("remoteSpcService")
public class RemoteSpcService {
private final Logger logger = LoggerFactory.getLogger(RemoteSpcService.class);
@Value("${params.spc.address}")
private String address;
private static final String success = "SUCCESS";
private String buildUrl(String address, WorkFlowRiskFactorUriEnum workFlowRiskFactorUriEnum, Map<String, String> map) {
String uri = workFlowRiskFactorUriEnum.getUri();
String params = workFlowRiskFactorUriEnum.getParams();
if (!StringUtils.isEmpty(params) && map != null) {
String[] paramsArr = params.split(",");
for (String param : paramsArr) {
uri = uri.replace("{" + param + "}", map.get(param));
}
}
return address + uri;
}
private JSONObject handleResult(String resultStr) {
if (resultStr == null) {
return null;
}
JSONObject json = JSON.parseObject(resultStr);
if (success.equals(json.getString("result"))) {
return json;
}
return null;
}
public JSONObject pushLatentDangerExecuteResult(LatentDangerResultPushSpcRequest latentDangerResultPushSpcRequest) {
String url = buildUrl(address, WorkFlowRiskFactorUriEnum.隐患治理结果推送, null);
String stringJson = JSONObject.toJSONString(latentDangerResultPushSpcRequest);
String resultStr = HttpUtil.sendHttpPostJson(url, stringJson);
logger.info("\r\n请求路径=======================>" + url + "\r\n请求参数=======================>" + stringJson + "\r\n返回参数=======================>" + resultStr);
return handleResult(resultStr);
}
}
package com.yeejoin.amos.latentdanger.common.remote;
import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yeejoin.amos.latentdanger.business.util.Constants;
import com.yeejoin.amos.latentdanger.business.util.StringUtil;
import com.yeejoin.amos.latentdanger.core.common.response.WebStockResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import java.util.HashMap;
import java.util.Map;
@Service("remoteWebSocketServer")
public class RemoteWebSocketServer {
private final RestTemplate restTemplate;
@Value("${params.remoteWebsocketUrl}")
private String remoteWebsocketUrl;
@Value("${params.remoteWebSocketSendMsgUrl}")
private String remoteWebSocketSendMsgUrl;
private ObjectMapper objectMapper = new ObjectMapper();
public RemoteWebSocketServer()
{
this.restTemplate = new RestTemplate();
}
public Object sendMessage(String message) throws Exception
{
Map<String, String> map = new HashMap<String, String>();
map.put("filter", null);
map.put("message", message);
map.put("path", "spcMessage");
HttpHeaders headers = new HttpHeaders();
MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
headers.setContentType(type);
headers.add("Accept", MediaType.APPLICATION_JSON.toString());
HttpEntity<Map<String, String>> formEntity = new HttpEntity<Map<String, String>>(map, headers);
ResponseEntity responseEntity = restTemplate.exchange(remoteWebsocketUrl + "/generic/sendMessage",
HttpMethod.POST, formEntity, String.class);
responseEntity.getBody();
if (StringUtil.isNotEmpty(responseEntity.getBody())) {
Map commonResponse = objectMapper.readValue(responseEntity.getBody().toString(),Map.class);
if (commonResponse != null && commonResponse.get("result").equals(Constants.RESULT_SUCCESS) )
{
return commonResponse.get("dataList");
}
}
return null;
}
public Object sendMessage(String message, String path) throws Exception
{
Map<String, String> map = new HashMap<String, String>();
map.put("filter", null);
map.put("message", message);
map.put("path", path);
HttpHeaders headers = new HttpHeaders();
MediaType type = MediaType
.parseMediaType("application/json; charset=UTF-8");
headers.setContentType(type);
headers.add("Accept", MediaType.APPLICATION_JSON.toString());
HttpEntity<Map<String, String>> formEntity = new HttpEntity<Map<String, String>>(map, headers);
ResponseEntity responseEntity = restTemplate.exchange(remoteWebSocketSendMsgUrl + "/generic/sendMessage",
HttpMethod.POST, formEntity, String.class);
responseEntity.getBody();
if (StringUtil.isNotEmpty(responseEntity.getBody())) {
Map commonResponse = objectMapper.readValue(responseEntity.getBody().toString(),Map.class);
if (commonResponse != null && commonResponse.get("result").equals(Constants.RESULT_SUCCESS) )
{
return commonResponse.get("dataList");
}
}
return null;
}
@Async
public void wsDataRefresh(String content){
WebStockResponse response = new WebStockResponse();
response.setType("dataRefresh");
response.setContent(content);
try {
sendMessage(JSON.toJSONString(response));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
package com.yeejoin.amos.latentdanger.common.remote;
import java.util.Map;
import com.yeejoin.amos.latentdanger.common.enums.YesOrNoEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.typroject.tyboot.core.foundation.context.RequestContext;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.yeejoin.amos.latentdanger.business.constants.Constants;
import com.yeejoin.amos.latentdanger.business.util.HttpUtil;
import com.yeejoin.amos.latentdanger.common.enums.WorkFlowUriEnum;
@Service("remoteWorkFlowService")
public class RemoteWorkFlowService {
private final Logger logger = LoggerFactory.getLogger(RemoteWorkFlowService.class);
@Value("${params.work.flow.address}")
private String address;
private static final String success = "SUCCESS";
private static final String appKey = "8b193f7cb22c842b5a56e866c2e20dbf";
@Value("${params.work.flow.processDefinitionKey}")
private String processDefinitionKey;
private String buildUrl(String address, WorkFlowUriEnum workFlowUriEnum, Map<String, String> map) {
String uri = workFlowUriEnum.getUri();
String params = workFlowUriEnum.getParams();
if (!StringUtils.isEmpty(params) && map != null) {
String[] paramsArr = params.split(",");
for (String param : paramsArr) {
uri = uri.replace("{" + param + "}", map.get(param));
}
}
return address + uri;
}
private JSONObject handleResult(String resultStr) {
if (resultStr == null) {
return null;
}
JSONObject json = JSON.parseObject(resultStr);
if ("200".equals(json.getString("code"))) {
return json;
}
return null;
}
public JSONObject start(String businessKey, String processDefinitionKey) {
String url = buildUrl(address, WorkFlowUriEnum.启动流程, null);
JSONObject body = new JSONObject();
body.put("businessKey", businessKey);
body.put("processDefinitionKey", processDefinitionKey);
String resultStr = HttpUtil.sendHttpPostJson(url, body.toJSONString());
return handleResult(resultStr);
}
public JSONObject getChildNodeDetail(String instanceId) {
Map<String, String> map = Maps.newHashMap();
map.put("instanceId", instanceId);
String url = buildUrl(address, WorkFlowUriEnum.子节点信息, map);
Map<String, String> headerMap = Maps.newHashMap();
headerMap.put(Constants.TOKEN_KEY, RequestContext.getToken());
headerMap.put(Constants.PRODUCT, RequestContext.getProduct());
headerMap.put(Constants.APPKEY, RequestContext.getAppKey());
String resultStr = HttpUtil.sendHttpGetWithHeader(url, headerMap);
logger.info("\r\n请求路径=======================>" + url + "\r\n请求参数=======================>" + instanceId + "\r\n返回参数=======================>" + resultStr);
return handleResult(resultStr);
}
public JSONObject start(Long dangerId, String businessKey, String processDefinitionKey) {
String url = buildUrl(address, WorkFlowUriEnum.启动流程, null);
Map<String, String> headerMap = Maps.newHashMap();
headerMap.put(Constants.TOKEN_KEY, RequestContext.getToken());
headerMap.put(Constants.PRODUCT, RequestContext.getProduct());
headerMap.put(Constants.APPKEY, RequestContext.getAppKey());
JSONObject body = new JSONObject();
body.put("businessKey", businessKey);
body.put("processDefinitionKey", processDefinitionKey);
JSONArray variables = new JSONArray();
JSONObject dangerIdJson = new JSONObject();
dangerIdJson.put("dangerId", dangerId);
body.put("variables", dangerIdJson);
String resultStr = HttpUtil.sendHttpPostJsonWithHeader(url, body.toJSONString(), headerMap);
logger.info("\r\n请求路径=======================>" + url + "\r\n请求参数=======================>" + body + "\r\n返回参数=======================>" + resultStr);
return JSON.parseObject(resultStr);
}
public JSONObject startWithAppKey(JSONObject body) {
Map<String, String> map = Maps.newHashMap();
map.put(Constants.TOKEN_KEY, RequestContext.getToken());
map.put(Constants.PRODUCT, RequestContext.getProduct());
map.put(Constants.APPKEY, RequestContext.getAppKey());
String url = buildUrl(address, WorkFlowUriEnum.启动免登录流程, map);
String requestBody = body.toJSONString();
String resultStr = HttpUtil.sendHttpPostJson(url, requestBody);
logger.info("\r\n请求路径=======================>" + url + "\r\n请求参数=======================>" + requestBody + "\r\n返回参数=======================>" + resultStr);
return handleResult(resultStr);
}
public JSONObject startNew(Long dangerId, String businessKey, String processDefinitionKey) {
String url = buildUrl(address, WorkFlowUriEnum.合并启动流程, null);
Map<String, String> headerMap = Maps.newHashMap();
headerMap.put(Constants.TOKEN_KEY, RequestContext.getToken());
headerMap.put(Constants.PRODUCT, RequestContext.getProduct());
headerMap.put(Constants.APPKEY, RequestContext.getAppKey());
JSONObject body = new JSONObject();
body.put("businessKey", businessKey);
body.put("processDefinitionKey", processDefinitionKey);
JSONObject dangerIdJson = new JSONObject();
dangerIdJson.put("dangerId", dangerId);
body.put("variables", dangerIdJson);
String resultStr = HttpUtil.sendHttpPostJsonWithHeader(url, body.toJSONString(), headerMap);
logger.info("\r\n请求路径=======================>" + url + "\r\n请求参数=======================>" + body + "\r\n返回参数=======================>" + resultStr);
return JSON.parseObject(resultStr);
}
public JSONObject stop(String processInstanceId) {
Map<String, String> map = Maps.newHashMap();
map.put("processInstanceId", processInstanceId);
Map<String, String> headerMap = Maps.newHashMap();
headerMap.put(Constants.TOKEN_KEY, RequestContext.getToken());
headerMap.put(Constants.PRODUCT, RequestContext.getProduct());
headerMap.put(Constants.APPKEY, RequestContext.getAppKey());
String url = buildUrl(address, WorkFlowUriEnum.终止流程, map);
String resultStr = HttpUtil.sendHttpDeleteWithHeader(url, headerMap);
JSONObject json = handleResult(resultStr);
logger.info("\r\n请求路径=======================>" + url + "\r\n返回参数=======================>" + resultStr);
return json;
}
public JSONObject execute(String taskId, String requestBody) {
Map<String, String> map = Maps.newHashMap();
map.put("taskId", taskId);
Map<String, String> headerMap = Maps.newHashMap();
headerMap.put(Constants.TOKEN_KEY, RequestContext.getToken());
headerMap.put(Constants.PRODUCT, RequestContext.getProduct());
headerMap.put(Constants.APPKEY, RequestContext.getAppKey());
String url = buildUrl(address, WorkFlowUriEnum.执行流程, map);
String resultStr = HttpUtil.sendHttpPostJsonWithHeader(url, requestBody, headerMap);
JSONObject json = handleResult(resultStr);
logger.info("\r\n请求路径=======================>" + url + "\r\n请求参数=======================>" + requestBody + "\r\n返回参数=======================>" + resultStr);
return json;
}
public JSONObject currentTask(String instanceId) {
Map<String, String> map = Maps.newHashMap();
map.put("processInstanceId", instanceId);
String url = buildUrl(address, WorkFlowUriEnum.当前节点, map);
String resultStr = HttpUtil.sendHttpGet(url);
JSONObject json = handleResult(resultStr);
logger.info("\r\n当前任务请求路径=======================>" + url + "\r\n当前任务返回参数=======================>" + resultStr);
if (json == null) {
return null;
}
JSONArray reviewContent = json.getJSONObject("dataList").getJSONArray("content");
if (reviewContent != null && reviewContent.size() > 0) {
return reviewContent.getJSONObject(0);
}
return null;
}
public JSONObject allTasksInProcessInstanceId(String instanceId) {
Map<String, String> map = Maps.newHashMap();
map.put("processInstanceId", instanceId);
String url = buildUrl(address, WorkFlowUriEnum.工作流流水, map);
Map<String, String> headerMap = Maps.newHashMap();
headerMap.put(Constants.TOKEN_KEY, RequestContext.getToken());
headerMap.put(Constants.PRODUCT, RequestContext.getProduct());
headerMap.put(Constants.APPKEY, RequestContext.getAppKey());
String resultStr = HttpUtil.sendHttpGetWithHeader(url, headerMap);
JSONObject json = handleResult(resultStr);
logger.info("\r\n请求路径=======================>" + url + "\r\n返回参数=======================>" + resultStr);
if (json == null) {
return null;
}
JSONArray allContent = json.getJSONArray("dataList");
if (allContent != null && allContent.size() > 0) {
return allContent.getJSONObject(allContent.size() - 1);
}
return null;
}
public JSONObject pageTask(String userId,Integer BelongType) {
Map<String, String> map = Maps.newHashMap();
String url = "";
map.put("processDefinitionKey", processDefinitionKey);
if(Integer.parseInt(YesOrNoEnum.YES.getCode())==BelongType){
map.put("userId", userId);
url = buildUrl(address, WorkFlowUriEnum.我的代办有ID, map);
}else{
url = buildUrl(address, WorkFlowUriEnum.我的代办, map);
}
Map<String, String> headerMap = Maps.newHashMap();
headerMap.put(Constants.TOKEN_KEY, RequestContext.getToken());
headerMap.put(Constants.PRODUCT, RequestContext.getProduct());
headerMap.put(Constants.APPKEY, RequestContext.getAppKey());
String resultStr = HttpUtil.sendHttpGetWithHeader(url, headerMap);
JSONObject json = handleResult(resultStr);
logger.info("\r\n请求路径=======================>" + url + "\r\n返回参数=======================>" + resultStr);
return json;
}
public JSONObject completedPageTask(String userId,Integer BelongType) {
Map<String, String> map = Maps.newHashMap();
String url = "";
map.put("processDefinitionKey", processDefinitionKey);
if(Integer.parseInt(YesOrNoEnum.YES.getCode())==BelongType){
map.put("userId", userId);
url = buildUrl(address, WorkFlowUriEnum.已执行任务有ID, map);
}else{
url = buildUrl(address, WorkFlowUriEnum.已执行任务, map);
}
Map<String, String> headerMap = Maps.newHashMap();
headerMap.put(Constants.TOKEN_KEY, RequestContext.getToken());
headerMap.put(Constants.PRODUCT, RequestContext.getProduct());
headerMap.put(Constants.APPKEY, RequestContext.getAppKey());
String resultStr = HttpUtil.sendHttpGetWithHeader(url, headerMap);
JSONObject json = handleResult(resultStr);
logger.info("\r\n请求路径=======================>" + url + "\r\n返回参数=======================>" + resultStr);
return json;
}
public JSONObject queryTaskDetail(String taskId) {
Map<String, String> map = Maps.newHashMap();
map.put("taskId", taskId);
String url = buildUrl(address, WorkFlowUriEnum.流程详情, map);
Map<String, String> headerMap = Maps.newHashMap();
headerMap.put(Constants.TOKEN_KEY, RequestContext.getToken());
headerMap.put(Constants.PRODUCT, RequestContext.getProduct());
headerMap.put(Constants.APPKEY, RequestContext.getAppKey());
String resultStr = HttpUtil.sendHttpGetWithHeader(url, headerMap);
JSONObject json = handleResult(resultStr);
logger.info("\r\n请求路径=======================>" + url + "\r\n返回参数=======================>" + resultStr);
return json;
}
public JSONObject queryFinishTaskDetail(String taskId) {
Map<String, String> map = Maps.newHashMap();
map.put("taskId", taskId);
String url = buildUrl(address, WorkFlowUriEnum.所有已执行任务详情, map);
Map<String, String> headerMap = Maps.newHashMap();
headerMap.put(Constants.TOKEN_KEY, RequestContext.getToken());
headerMap.put(Constants.PRODUCT, RequestContext.getProduct());
headerMap.put(Constants.APPKEY, RequestContext.getAppKey());
String resultStr = HttpUtil.sendHttpGetWithHeader(url, headerMap);
JSONObject json = handleResult(resultStr);
logger.info("\r\n请求路径=======================>" + url + "\r\n返回参数=======================>" + resultStr);
return json;
}
}
package com.yeejoin.amos.latentdanger.config;
import cn.hutool.core.date.LocalDateTimeUtil;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
/**
* @author DELL
*/
@Configuration
public class JacksonCustomizerConfig {
/**
* description:适配自定义序列化和反序列化策略,返回前端指定数据类型的数据
*/
@Bean
public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
return builder -> {
builder.serializerByType(LocalDateTime.class, new LocalDateTimeSerializer());
builder.deserializerByType(LocalDateTime.class, new LocalDateTimeDeserializer());
};
}
/**
* description:序列化
* LocalDateTime序列化为毫秒级时间戳
*/
public static class LocalDateTimeSerializer extends JsonSerializer<LocalDateTime> {
@Override
public void serialize(LocalDateTime value, JsonGenerator gen, SerializerProvider serializers)
throws IOException {
if (value != null) {
long timestamp = LocalDateTimeUtil.toEpochMilli(value);
gen.writeNumber(timestamp);
}
}
}
/**
* description:反序列化
* 毫秒级时间戳序列化为LocalDateTime
*/
public static class LocalDateTimeDeserializer extends JsonDeserializer<LocalDateTime> {
@Override
public LocalDateTime deserialize(JsonParser p, DeserializationContext deserializationContext)
throws IOException {
long timestamp = p.getValueAsLong();
if (timestamp > 0) {
return LocalDateTimeUtil.of(timestamp, ZoneOffset.of("+8"));
} else {
return null;
}
}
}
}
/**
*
*/
package com.yeejoin.amos.latentdanger.context;
import com.yeejoin.amos.latentdanger.business.constants.Constants;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
/**
* iot-spring上下文
*
* @author as-youjun
*
*/
public class IotContext {
/**
* 实例
*/
private static IotContext instance;
/**
* spring上下文
*/
private ApplicationContext applicationContext;
/**
* 构造方法
*/
private IotContext() {
LoggerFactory.getLogger(this.getClass()).debug(Constants.CONSTRUCTOR);
}
/**
* 获取单例
*
* @return
*/
public static synchronized IotContext getInstance() {
if (instance == null) {
instance = new IotContext();
}
return instance;
}
/**
* 设置上下文
*
* @param applicationContext
*/
public void setApplicationContext(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
/**
* 获取上下文
*
* @param beanName
* @return
*/
public Object getBean(String beanName) {
return applicationContext.getBean(beanName);
}
/**
* 获取上下文
*
* @param requiredType
* @return
*/
public Object getBean(Class<?> requiredType) {
return applicationContext.getBean(requiredType);
}
}
package com.yeejoin.amos.latentdanger.core.aop;
import com.yeejoin.amos.boot.biz.common.utils.RedisUtils;
import com.yeejoin.amos.feign.systemctl.Systemctl;
import com.yeejoin.amos.feign.systemctl.model.DictionarieValueModel;
import com.yeejoin.amos.latentdanger.business.constants.Constants;
import com.yeejoin.amos.latentdanger.common.enums.LatentDangerLevelEnum;
import com.yeejoin.amos.latentdanger.common.enums.LatentDangerReformTypeEnum;
import com.yeejoin.amos.latentdanger.common.enums.LatentDangerStateEnum;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
/**
* @author DELL
*/
@Aspect
@Component
public class EnumFillAop {
@Pointcut("execution(public * com.yeejoin.amos.latentdanger.business.controller..*(..))")
public void fillEnum() {
}
@Before("fillEnum()")
public void doBefore(JoinPoint joinPoint) {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
String bizType = request.getHeader("bizType");
if (bizType == null) {
bizType = request.getParameter("bizType");
}
// 获取隐患等级枚举
if (ValidationUtil.isEmpty(LatentDangerLevelEnum.enumMap)) {
List<DictionarieValueModel> dicResult =
Systemctl.dictionarieClient.dictValues(bizType + LatentDangerLevelEnum.dictCode).getResult();
dicResult.forEach(dic -> LatentDangerLevelEnum.addEnumDynamic(dic.getDictDataDesc(), dic.getDictDataValue(), dic.getDictDataKey(),
"", dic.getOrderNum()));
}
// 获取治理方式枚举
if (ValidationUtil.isEmpty(LatentDangerReformTypeEnum.enumMap)) {
List<DictionarieValueModel> dicResult =
Systemctl.dictionarieClient.dictValues(bizType + LatentDangerReformTypeEnum.dictCode).getResult();
dicResult.forEach(dic -> LatentDangerReformTypeEnum.addEnumDynamic(dic.getDictDataDesc(), dic.getDictDataValue(), dic.getDictDataKey()));
}
// 获取治理状态枚举
if (ValidationUtil.isEmpty(LatentDangerStateEnum.enumMap)) {
List<DictionarieValueModel> dicResult =
Systemctl.dictionarieClient.dictValues(bizType + LatentDangerStateEnum.dictCode).getResult();
dicResult.forEach(dic -> LatentDangerStateEnum.addEnumDynamic(dic.getDictDataDesc(), dic.getDictDataValue(), dic.getDictDataKey()));
}
}
}
package com.yeejoin.amos.latentdanger.core.async;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.yeejoin.amos.latentdanger.business.param.JPushTypeEnum;
import com.yeejoin.amos.latentdanger.business.param.PushMsgParam;
import com.yeejoin.amos.latentdanger.business.util.Toke;
import com.yeejoin.amos.latentdanger.common.enums.MsgSubscribeEnum;
import com.yeejoin.amos.latentdanger.dao.entity.Msg;
import com.yeejoin.amos.latentdanger.feign.RemoteSecurityService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* 异步执行任务
*
* @author Administrator
*/
@Component(value = "asyncTask")
public class AsyncTask {
private static final String TAB = "\r\n";
private final Logger log = LoggerFactory.getLogger(AsyncTask.class);
// @Autowired
// private IMsgDao iMsgDao;
// @Autowired
// private IMessageService messageService;
@Autowired
private RemoteSecurityService remoteSecurityService;
/**
* 隐患待治理到期提醒
*/
@Async("asyncTaskExecutor")
public void pushLatentDangerReformLimitDateExpireMessage(String informerList, String orgCode,
String latentDangerName, String reformLimitDate,
Long latentDangerId, Integer state,
String userRealName) {
MsgSubscribeEnum msgTypeEnum = MsgSubscribeEnum.隐患治理推送;
String body = "";
body += "隐患治理提醒:您好,隐患治理即将到期,请及时处理!" + TAB;
body += "隐患名称:" + latentDangerName + TAB;
body += "治理日期:" + reformLimitDate;
saveAndSendMsg(orgCode, informerList, msgTypeEnum.getTitle(), body, msgTypeEnum.getMsgType(), latentDangerId, state, userRealName);
}
/**
* 隐患治理
*/
@Async("asyncTaskExecutor")
public void pushLatentDangerExecuteMessage(String informerList, String orgCode,
String latentDangerName, String pointName,
String exeDeptName, Long latentDangerId,
String exeUserRealName, String flowName,
String flowResult, String executeDate,
Integer state) {
MsgSubscribeEnum msgTypeEnum = MsgSubscribeEnum.隐患治理推送;
String body = "";
body += executeDate + TAB;
body += exeDeptName + " " + exeUserRealName + " " + flowName + ":" + flowResult + TAB;
body += "隐患名称:" + latentDangerName + TAB;
if (pointName != null) {
body += "关联检查点:" + pointName + TAB;
}
saveAndSendMsg(orgCode, informerList, msgTypeEnum.getTitle(), body, msgTypeEnum.getMsgType(), latentDangerId, state, "");
}
/**
* 隐患验证通过
*/
@Async("asyncTaskExecutor")
public void pushRiskWarnMessage(String informerList, String orgCode,
String latentDangerName, Long riskFactorId,
String riskFactorName, String pointName,
String executeDate) {
MsgSubscribeEnum msgTypeEnum = MsgSubscribeEnum.风险评价提醒推送;
String body = "";
body += latentDangerName + "管控措施失效,隐患治理验证完毕,需重新进行风险评价!" + TAB;
body += "关联危险源:" + pointName + TAB;
body += "关联危险因素:" + riskFactorName + TAB;
body += "执行时间:" + executeDate + TAB;
if (pointName != null) {
body += "关联检查点:" + pointName + TAB;
}
saveAndSendMsg(orgCode, informerList, msgTypeEnum.getTitle(), body, msgTypeEnum.getMsgType(), riskFactorId, null, "");
}
private void saveAndSendMsg(String orgCode, String informerList,
String title, String body, String msgType,
Long relationId, Integer state,
String userRealName) {
JSONArray array = JSONArray.parseArray(informerList);
Set<String> sendUserIds = new HashSet<>();
if (array.size() > 0) {
Date date = new Date();
List<Msg> msgs = Lists.newArrayList();
for (int i = 0; i < array.size(); i++) {
JSONObject user = array.getJSONObject(i);
Msg msg = new Msg();
msg.setOrgCode(orgCode);
msg.setUserId(user.getString("userId"));
msg.setTitle(title);
msg.setBody(body);
msg.setMsgType(msgType);
msg.setRelationId(relationId);
msg.setIsImmediately(true);
msg.setSendTime(date);
msg.setCreateDate(date);
msg.setTargetTel(user.getString("username"));
msg.setReciverName(user.getString("realName"));
sendUserIds.add(user.getString("userId"));
msgs.add(msg);
}
Map<String, String> extras = Maps.newHashMap();
extras.put("type", msgType);
extras.put("id", String.valueOf(relationId));
if (state != null) {
extras.put("state", String.valueOf(state));
}
PushMsgParam pushMsgParam = new PushMsgParam();
pushMsgParam.setContent(body);
pushMsgParam.setRecivers(Lists.newArrayList(sendUserIds));
pushMsgParam.setSubject(title);
pushMsgParam.setRelationId(String.valueOf(relationId));
pushMsgParam.setType(JPushTypeEnum.ALIAS.getCode());
pushMsgParam.setExtras(extras);
// iMsgDao.saveAll(msgs);
Toke toke = remoteSecurityService.getServerToken();
// messageService.pushMsg(toke.getToke(), toke.getProduct(), toke.getAppKey(), pushMsgParam);
}
}
}
package com.yeejoin.amos.latentdanger.core.async;
import java.util.concurrent.Executor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
/**
* @author DELL
*/
@Configuration(value = "taskExecutorPoolConfig")
public class TaskExecutorPoolConfig {
@Bean("asyncTaskExecutor")
public Executor taskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
//线程池维护线程的最少数量
executor.setCorePoolSize(10);
//线程池维护线程的最大数量
executor.setMaxPoolSize(100);
executor.setQueueCapacity(100);
//线程池维护线程所允许的空闲时间,TimeUnit.SECONDS
executor.setKeepAliveSeconds(30);
executor.setThreadNamePrefix("asyncTaskExecutor-");
return executor;
}
}
package com.yeejoin.amos.latentdanger.core.enums;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.enums.ValuedEnum;
/**
* 操作枚举
*
* @author as-youjun
*
*/
@SuppressWarnings("all")
public final class QueryOperatorEnum extends ValuedEnum {
private static final long serialVersionUID = -375127751242109017L;
public static final int LESS_VALUE = 1; // 小于
public static final int BIGGER_VALUE = 2; // 大于
public static final int EQUAL_VALUE = 3; // 等于
public static final int LESS_EQUAL_VALUE = 4; // 小于等于
public static final int BIGGER_EQUAL_VALUE = 5; // 大于等于
public static final int NOT_EQUAL_VALUE = 6; // 不等于
public static final int IN_VALUE = 7; // 包含
public static final int LIKE_VALUE = 8; // like
public static final int OR_VALUE = 9; // 或者
public static final int ORDER_VALUE = 10; // 排序
public static final int NOT_IN_VALUE = 11; // 不包含
public static final int IS_VALUE= 12; //是
public static final QueryOperatorEnum LESS = new QueryOperatorEnum("LESS", 1, "<");
public static final QueryOperatorEnum BIGGER = new QueryOperatorEnum("BIGGER", 2, ">");
public static final QueryOperatorEnum EQUAL = new QueryOperatorEnum("EQUAL", 3, "=");
public static final QueryOperatorEnum LESS_EQUAL = new QueryOperatorEnum("LESS_EQUAL", 4, "<=");
public static final QueryOperatorEnum BIGGER_EQUAL = new QueryOperatorEnum("BIGGER_EQUAL", 5, ">=");
public static final QueryOperatorEnum NOT_EQUAL = new QueryOperatorEnum("NOT_EQUAL", 6, "<>");
public static final QueryOperatorEnum IN = new QueryOperatorEnum("IN", 7, "IN");
public static final QueryOperatorEnum LIKE = new QueryOperatorEnum("LIKE", 8, "LIKE");
public static final QueryOperatorEnum OR = new QueryOperatorEnum("OR", 9, "OR");
public static final QueryOperatorEnum ORDER_BY = new QueryOperatorEnum("ORDER BY", 10, "ORDER BY");
public static final QueryOperatorEnum NOT_IN = new QueryOperatorEnum("NOT IN", 11, "NOT IN");
public static final QueryOperatorEnum IS = new QueryOperatorEnum("IS", 12, "IS");
public String condition;
public String getCondition() {
return condition;
}
public void setCondition(String condition) {
this.condition = condition;
}
protected QueryOperatorEnum(String arg0, int arg1, String condition) {
super(arg0, arg1);
this.condition = condition;
}
public static QueryOperatorEnum getEnum(String name) {
try {
return ((QueryOperatorEnum) getEnum(QueryOperatorEnum.class, name));
} catch (Exception ex) {
return null;
}
}
public static QueryOperatorEnum getEnum(int name) {
try {
return ((QueryOperatorEnum) getEnum(QueryOperatorEnum.class, name));
} catch (Exception ex) {
return null;
}
}
public static Map getMap() {
try {
return getEnumMap(QueryOperatorEnum.class);
} catch (Exception ex) {
return null;
}
}
public static List getList() {
try {
return getEnumList(QueryOperatorEnum.class);
} catch (Exception ex) {
return null;
}
}
public static Iterator iterator() {
try {
return iterator(QueryOperatorEnum.class);
} catch (Exception ex) {
return null;
}
}
}
package com.yeejoin.amos.latentdanger.core.framework;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ResponseBody;
import com.yeejoin.amos.latentdanger.business.util.CommonResponse;
import com.yeejoin.amos.latentdanger.business.util.CommonResponseUtil;
import com.yeejoin.amos.latentdanger.exception.PermissionException;
import com.yeejoin.amos.latentdanger.exception.YeeException;
/**
* @author DELL
*/
@ControllerAdvice
public class ExceptionHandler {
private static final Logger logger = LoggerFactory.getLogger(ExceptionHandler.class);
@org.springframework.web.bind.annotation.ExceptionHandler(PermissionException.class)
@ResponseBody
public CommonResponse handlePermissionException(HttpServletRequest request, HttpServletResponse resp, PermissionException ex) {
resp.setStatus(HttpStatus.UNAUTHORIZED.value());
return CommonResponseUtil.failure(ex.getMessage());
}
@org.springframework.web.bind.annotation.ExceptionHandler(YeeException.class)
@ResponseBody
public CommonResponse handleYeeException(HttpServletRequest request, YeeException ex) {
return CommonResponseUtil.failure(ex.getMessage());
}
@org.springframework.web.bind.annotation.ExceptionHandler(Exception.class)
@ResponseBody
public CommonResponse handleException(HttpServletRequest request, Exception ex) {
return CommonResponseUtil.failure(ex.getMessage());
}
}
package com.yeejoin.amos.latentdanger.core.framework;
import java.io.File;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import com.yeejoin.amos.latentdanger.business.constants.Constants;
@Configuration
public class PatrolApplicationConfig extends WebMvcConfigurerAdapter{
@Value("${windows.img.path}")
private String winImgPath;
@Value("${linux.img.path}")
private String linuxImgPath;
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
String localPath = "";
if ("\\".equals(File.separator)) {
localPath += winImgPath;
} else if ("/".equals(File.separator)) {
localPath += linuxImgPath;
}
registry.addResourceHandler("/upload/**").addResourceLocations("file:"+localPath.trim()+ Constants.UPLOAD_ROOT_PATH + File.separator);
// registry.addResourceHandler("/upload/video/**").addResourceLocations("file:G:/upload/video/");
super.addResourceHandlers(registry);
}
}
package com.yeejoin.amos.latentdanger.core.threadpool;
import com.yeejoin.amos.latentdanger.business.constants.Constants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* 线程池
*/
public class AmosThreadPool {
/**
* 日志记录器
*/
private static final Logger log = LoggerFactory.getLogger(AmosThreadPool.class);
/**
* 单例
*/
private static AmosThreadPool instance;
/**
* 执行服务
*/
private static ExecutorService executorService;
/**
* 获取单例
*
* @return
*/
public static AmosThreadPool getInstance() {
if (instance == null) {
synchronized (AmosThreadPool.class) {
if (instance == null) {
instance = new AmosThreadPool();
}
}
}
return instance;
}
static {
executorService = Executors
.newFixedThreadPool(Constants.AMOS_THREAD_NUM);
}
/**
* 执行线程
*
* @param task
*/
public void execute(Runnable task) {
executorService.execute(task);
}
}
package com.yeejoin.amos.latentdanger.core.util;
import com.yeejoin.amos.latentdanger.exception.YeeException;
import java.sql.Time;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
/**
* <pre>
* 日期
* </pre>
*
* @author as-chenjiajun
* @version $Id: DateUtil.java, v 0.1 2018年1月29日 下午5:08:40 as-chenjiajun Exp $
*/
public class DateUtil {
public static String LONG_PATTERN = "yyyy-MM-dd HH:mm:ss";
public static String MID_PATTERN = "yyyy-MM-dd HH:mm";
public static String SHORT_PATTERN = "yyyy-MM-dd";
public static long THREE_DAY_MILLSEC = 259200000L;
public static long ONE_DAY_MILLSEC = 86400000L;
public static long ONE_HOUR_MILLSEC = 3600000L;
public static long THREE_HOURS_MILLSEC = 10800000L;
public static long TWELVE_HOURS_MILLSEC = 43200000L;
public static Date EMPTY_DATE = null;
static {
Calendar calendar = Calendar.getInstance();
calendar.set(9999, 0, 0);
EMPTY_DATE = calendar.getTime();
}
/**
* <pre>
* 获取当前北京时间
* </pre>
*
* @return
*/
public static Date getCurrentDate() {
return getCurrentCalendar().getTime();
}
public static String getLongCurrentDate() {
return new SimpleDateFormat(LONG_PATTERN)
.format(getCurrentCalendar().getTime());
}
public static String getLongDate(Date date) {
if (null == date)
return getLongCurrentDate();
else
return new SimpleDateFormat(LONG_PATTERN).format(date);
}
public static String getLongDate(long value) {
return new SimpleDateFormat(LONG_PATTERN).format(new Date(value));
}
public static String getShortCurrentDate() {
return new SimpleDateFormat(SHORT_PATTERN).format(new Date());
}
public static String getShortDate(Date date) {
if (null == date)
return getShortCurrentDate();
else
return new SimpleDateFormat(SHORT_PATTERN).format(date);
}
public static String getShortDate(long value) {
return new SimpleDateFormat(SHORT_PATTERN).format(new Date(value));
}
public static Date getShortCurrentDate(String shortDateStr) throws ParseException {
return new SimpleDateFormat(SHORT_PATTERN).parse(shortDateStr);
}
public static Date getLongDate(String longDateStr) throws ParseException {
return new SimpleDateFormat(LONG_PATTERN).parse(longDateStr);
}
public static String getMidCurrentDate() {
return new SimpleDateFormat(MID_PATTERN).format(new Date());
}
public static String getMidDate(Date date) {
if (null == date)
return getMidCurrentDate();
else
return new SimpleDateFormat(MID_PATTERN).format(new Date());
}
public static String getMidDate(long value) {
return new SimpleDateFormat(MID_PATTERN).format(new Date(value));
}
public static Date str2Date(String strDate, String dateFormat) {
SimpleDateFormat formatter = new SimpleDateFormat(dateFormat);
ParsePosition pos = new ParsePosition(0);
Date strtodate = formatter.parse(strDate, pos);
return strtodate;
}
public static int getYear(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
int year = calendar.get(Calendar.YEAR);
return year;
}
public static int getMonth(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
int month = calendar.get(Calendar.MONTH) + 1;
return month;
}
public static int getDay(Date date) {
Calendar c = Calendar.getInstance();
c.setTime(date);
int day = c.get(Calendar.DATE);
return day;
}
public static int getHour(Date date) {
Calendar c = Calendar.getInstance();
c.setTime(date);
int hour = c.get(Calendar.HOUR_OF_DAY);
return hour;
}
public static int getMinite(Date date) {
Calendar c = Calendar.getInstance();
c.setTime(date);
int minite = c.get(Calendar.MINUTE);
return minite;
}
/**
* <pre>
* 获取当前北京时间
* </pre>
*
* @return
*/
public static Calendar getCurrentCalendar() {
TimeZone.setDefault(TimeZone.getTimeZone("Asia/Shanghai"));
return Calendar.getInstance();
}
/**
* <pre>
* 获取当前两个时间差
* </pre>
*
* @return
*/
public static String getTimeDifference(Date dateBefore, Date dateAfter) {
long l = dateAfter.getTime() - dateBefore.getTime();
long day = l / (24 * 60 * 60 * 1000);
long hour = (l / (60 * 60 * 1000) - day * 24);
long min = ((l / (60 * 1000)) - day * 24 * 60 - hour * 60);
long s = (l / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60);
return "" + day + "天" + hour + "小时" + min + "分" + s + "秒";
}
/**
* 获取某年某月的第一天日期
*
* @param date
* @param format
* @return
*/
public static String getStartMonthDate(String date, String format) {
if (date == null || date.length() < 6 || format == null) {
return null;
}
int year = Integer.parseInt(date.substring(0, 4));
int month = Integer.parseInt(date.substring(4, 6));
Calendar calendar = Calendar.getInstance();
calendar.set(year, month - 1, 1);
return new SimpleDateFormat(format).format(calendar.getTime());
}
/**
* 获取某年某月的最后一天日期
*
* @param date
* @param format
* @return
*/
public static String getEndMonthDate(String date, String format) {
if (date == null || date.length() < 6 || format == null) {
return null;
}
int year = Integer.parseInt(date.substring(0, 4));
int month = Integer.parseInt(date.substring(4, 6));
Calendar calendar = Calendar.getInstance();
calendar.set(year, month - 1, 1);
int day = calendar.getActualMaximum(5);
calendar.set(year, month - 1, day);
return new SimpleDateFormat(format).format(calendar.getTime());
}
/**
* 获取某天的间隔天数
*
* @param date
* @param interval 间隔天数。负数为前,正数为后
* @param format 输出格式化
* @return
*/
public static String getIntervalDateStr(Date date, int interval, String format) {
if (date == null || format == null) {
return null;
}
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.DATE, interval);
return new SimpleDateFormat(format).format(calendar.getTime());
}
/**
* 获取某天的年初第一天
*
* @param date
* @param format 输出格式化
* @return
*/
public static String getFirstDayOfYear(String date, String format) {
int year = Integer.parseInt(date.substring(0, 4));
Calendar calendar = Calendar.getInstance();
calendar.set(year, Calendar.JANUARY, 1);
return new SimpleDateFormat(format).format(calendar.getTime());
}
/**
* 获取某天的年初第一天
*
* @param date
* @param format 输出格式化
* @return date
*/
public static Date getFirstDayOfYearDate(String date) {
int year = Integer.parseInt(date.substring(0, 4));
Calendar calendar = Calendar.getInstance();
calendar.set(year, Calendar.JANUARY, 1);
return calendar.getTime();
}
/**
* 获取某天的年末最后一天
*
* @param date
* @param format 输出格式化
* @return date
*/
public static Date getLastDayOfYearDate(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
final int last = calendar.getActualMaximum(Calendar.DAY_OF_YEAR);
calendar.set(Calendar.DAY_OF_YEAR, last);
return calendar.getTime();
}
/**
* 获取某天的间隔天数
*
* @param date
* @param interval 间隔天数。负数为前,正数为后
* @param format 输出格式化
* @return
*/
public static Date getIntervalDate(Date date, int interval) {
if (date == null) {
return null;
}
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.DATE, interval);
return calendar.getTime();
}
/**
* 获得指定日期的间隔周末
*
* @param exeDate
* @param init
* @return
*/
public static Date getIntervalWeekDate(Date exeDate, int init) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(exeDate);
calendar.add(Calendar.DATE, init * 7);
calendar.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
return calendar.getTime();
}
/**
* 获得制定日期间隔的上个月最后一天
*
* @param exeDate
* @param inter
* @return
*/
public static Date getEndMonthDate(Date exeDate, int inter) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(exeDate);
calendar.add(Calendar.MONTH, inter - 1);
calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
return calendar.getTime();
}
/**
* 获取间隔周的
*
* @param mounthFirstDate
* @param whatWeek
* @param weekDay
* @return
*/
public static Date getIntMonthWeekDate(Date mounthFirstDate, int week, int day) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(mounthFirstDate);
if (day == 7) {
day = 1;
week = week + 1;
} else {
day = day + 1;
}
calendar.set(Calendar.WEEK_OF_MONTH, week);
calendar.set(Calendar.DAY_OF_WEEK, day);
return calendar.getTime();
}
/**
* 获取间隔的年日期
*
* @param planDegin
* @param init
* @return
*/
public static String getIntervalYearDate(Date planDegin, int init) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(planDegin);
calendar.add(Calendar.YEAR, init);
return new SimpleDateFormat("yyyy-MM-dd").format(calendar.getTime());
}
/**
* 格式化日期
*
* @param beginDate
* @param string
* @return
*/
public static String formatDatrToStr(Date beginDate, String formart) {
SimpleDateFormat df = new SimpleDateFormat(formart);
String strDate = df.format(beginDate);
return strDate;
}
public static Time formatStrToTime(String strDate) {
String str = strDate;
SimpleDateFormat format = new SimpleDateFormat("hh:mm:ss");
Date d = null;
try {
d = format.parse(str);
} catch (Exception e) {
e.printStackTrace();
}
Time date = new Time(d.getTime());
return date;
}
/**
* 获得间隔分钟的时间
*
* @param strBeginTime 被操作时间
* @param duration 间隔分钟数
* @param string 格式化的格式
* @return
*/
public static String getIntMinStrDate(String strBeginTime, int duration, String formart) {
SimpleDateFormat df = new SimpleDateFormat(formart);
Date date;
try {
date = df.parse(strBeginTime);
} catch (ParseException e) {
throw new YeeException("格式化日期失败");
}
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.MINUTE, duration);
String strDate = df.format(calendar.getTime());
return strDate;
}
public static String cronTime(Date date) {
StringBuilder cron = new StringBuilder();
cron.append(date.getSeconds()).append(" ")
.append(date.getMinutes()).append(" ")
.append(date.getHours()).append(" ")
.append(date.getDay()).append(" ")
.append(date.getMonth()).append(" ")
.append("?").append(" ")
.append(date.getYear());
return cron.toString();
}
/**
* 获取指定日期的周一
*/
public static Date getThisWeekMonday(Date date) {
Calendar cal = getCurrentCalendar();
cal.setTime(date);
// 获得当前日期是一个星期的第几天
int dayWeek = cal.get(Calendar.DAY_OF_WEEK);
if (1 == dayWeek) {
cal.add(Calendar.DAY_OF_MONTH, -1);
}
// 设置一个星期的第一天,按中国的习惯一个星期的第一天是星期一
cal.setFirstDayOfWeek(Calendar.MONDAY);
// 获得当前日期是一个星期的第几天
int day = cal.get(Calendar.DAY_OF_WEEK);
// 根据日历的规则,给当前日期减去星期几与一个星期第一天的差值
cal.add(Calendar.DATE, cal.getFirstDayOfWeek() - day);
return cal.getTime();
}
/**
* 获取指定日期的月份第一天
*/
public static Date getThisMonthFirstDay(Date date) {
Calendar cal = getCurrentCalendar();
cal.setTime(date);
//获取某月最小天数
int firstDay = cal.getMinimum(Calendar.DATE);
//设置日历中月份的最小天数
cal.set(Calendar.DAY_OF_MONTH, firstDay);
return cal.getTime();
}
public static Date getCurrYearFirst() {
Calendar currCal = getCurrentCalendar();
int currentYear = currCal.get(Calendar.YEAR);
return getYearFirst(currentYear);
}
public static Date getCurrYearLast() {
Calendar currCal = getCurrentCalendar();
int currentYear = currCal.get(Calendar.YEAR);
return getYearLast(currentYear);
}
public static Date getYearFirst(int year) {
Calendar calendar = getCurrentCalendar();
calendar.clear();
calendar.set(Calendar.YEAR, year);
return calendar.getTime();
}
public static Date getYearLast(int year) {
Calendar calendar = getCurrentCalendar();
calendar.clear();
calendar.set(Calendar.YEAR, year);
calendar.roll(Calendar.DAY_OF_YEAR, -1);
return calendar.getTime();
}
}
package com.yeejoin.amos.latentdanger.core.util;
import java.math.BigDecimal;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.springframework.util.Assert;
/**
* 字符串工具类
*
* @author as-youjun
*
*/
public class StringUtil {
private static Pattern NOT_ZERO_AT_THE_END = Pattern.compile("[1-9](\\d*[1-9])?");
private static Pattern numericPattern = Pattern.compile("-?[0-9]+\\.?[0-9]*");
/**
* 判断对象是否为空
*
* @param str
* @return
*/
public static boolean isNotEmpty(Object str) {
boolean flag = true;
if (str != null && !str.equals("")) {
if (str.toString().length() > 0) {
flag = true;
}
} else {
flag = false;
}
return flag;
}
/***************************************************************************
* repeat - 通过源字符串重复生成N次组成新的字符串。
*
* @param src
* - 源字符串 例如: 空格(" "), 星号("*"), "浙江" 等等...
* @param num
* - 重复生成次数
* @return 返回已生成的重复字符串
* @version 1.0 (2006.10.10) Wilson Lin
**************************************************************************/
public static String repeat(String src, int num) {
StringBuffer s = new StringBuffer();
for (int i = 0; i < num; i++)
s.append(src);
return s.toString();
}
/**
* 判断是否数字表示
*
* @param src
* 源字符串
* @return 是否数字的标志
*/
public static boolean isNumeric(String str) {
// 该正则表达式可以匹配所有的数字 包括负数
String bigStr;
try {
bigStr = new BigDecimal(str).toString();
} catch (Exception e) {
return false;// 异常 说明包含非数字。
}
Matcher isNum = numericPattern.matcher(bigStr); // matcher是全匹配
if (!isNum.matches()) {
return false;
}
return true;
}
public static int toInt(String s) {
if (s != null && !"".equals(s.trim())) {
try {
return Integer.parseInt(s);
} catch (Exception e) {
return 0;
}
}
return 0;
}
/**
* 截取前后都不是0的数字字符串
*
* 12010102 => 12010102 12010100 => 120101 ab1201100b => 12011
*
* @param str
* @return
*/
public static String delEndZero(String str) {
Matcher mat = NOT_ZERO_AT_THE_END.matcher(str);
boolean rs = mat.find();
if (rs) {
return mat.group(0);
}
return null;
}
/**
*
* <pre>
* 移除字符串后面的0
* </pre>
*
* @param s
* @return
*/
public static String removeSufixZero(String s) {
if (s == null) {
return "";
}
while (s.endsWith("0")) {
if (s.equals("0")) {
s = "";
break;
}
s = s.substring(0, s.length() - 1);
}
return s;
}
public static String transforCode(String code) {
if (code.endsWith("0000000")) {
code = code.substring(0, 1);
} else if (code.endsWith("000000")) {
code = code.substring(0, 2);
} else if (code.endsWith("0000")) {
code = code.substring(0, 4);
} else if (code.endsWith("00")) {
code = code.substring(0, 6);
}
return code;
}
/**
* 获取支队orgCode
*
* @param orgCode
* @return
*/
public static String getDetachmentOrgCode(String orgCode) {
Assert.notNull(orgCode, "组织结构orgCode不能为空!");
String[] codes = orgCode.split("\\*");
if (codes.length < 2) {
throw new IllegalArgumentException("组织结构orgCode为总队,不能获取支队orgCode!");
} else {
return codes[0] + "*" + codes[1];
}
}
}
package com.yeejoin.amos.latentdanger.exception;
import org.springframework.http.HttpStatus;
public class PermissionException extends RuntimeException{
private static final long serialVersionUID = -6126611364667754200L;
public PermissionException(String message) {
super(message);
}
public PermissionException(String message, Throwable cause) {
super(message, cause);
}
public HttpStatus getStatus() {
return HttpStatus.FORBIDDEN; // 403
}
}
package com.yeejoin.amos.latentdanger.exception;
/**
*
* <pre>
* 自定义异常
* </pre>
*
* @author as-youjun
* @version $Id: YeeException.java, v 0.1 2017年7月18日 上午9:34:21 as-youjun Exp $
*/
public class YeeException extends RuntimeException {
/** * <pre>
*
* </pre>
*/
private static final long serialVersionUID = -1963401137898098411L;
private int errorCode = 0;
public YeeException(int errorCode) {
this.errorCode = errorCode;
}
public YeeException(String message, int errorCode) {
super(message);
this.errorCode = errorCode;
}
public YeeException(String message) {
super(message);
}
public YeeException(String message, Throwable cause, int errorCode) {
super(message, cause);
this.errorCode = errorCode;
}
public YeeException(Throwable cause, int errorCode) {
super(cause);
this.errorCode = errorCode;
}
public YeeException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace,
int errorCode) {
super(message, cause, enableSuppression, writableStackTrace);
this.errorCode = errorCode;
}
/**
* Getter method for property <tt>errorCode</tt>.
*
* @return property value of errorCode
*/
public int getErrorCode() {
return errorCode;
}
/**
* Setter method for property <tt>errorCode</tt>.
*
* @param errorCode
* value to be assigned to property errorCode
*/
public void setErrorCode(int errorCode) {
this.errorCode = errorCode;
}
}
//package com.yeejoin.amos.latentdanger.feign;
//
//import feign.codec.Encoder;
//import feign.form.spring.SpringFormEncoder;
//import org.springframework.beans.factory.ObjectFactory;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
//import org.springframework.cloud.openfeign.support.SpringEncoder;
//import org.springframework.context.annotation.Bean;
//import org.springframework.context.annotation.Configuration;
//import org.springframework.web.context.request.RequestContextListener;
//
///**
// * @Author: xinglei
// * @Description:
// * @Date: 2020/3/30 16:26
// */
//@Configuration
//public class MultipartSupportConfig {
//
// @Autowired
// private ObjectFactory<HttpMessageConverters> messageConverters;
//
// @Bean
// public Encoder feignFormEncoder() {
// return new SpringFormEncoder(new SpringEncoder(messageConverters));
// }
//
// /**
// * 创建Feign请求拦截器,在发送请求前设置认证的token,各个微服务将token设置到环境变量中来达到通用
// * @return
// */
// @Bean
// public RequestContextListener requestInterceptor() {
// return new RequestContextListener();
// }
//}
//package com.yeejoin.amos.latentdanger.feign;
//import com.yeejoin.amos.latentdanger.business.param.PushMsgParam;
//import org.springframework.web.bind.annotation.RequestMapping;
//import org.springframework.web.bind.annotation.RequestMethod;
//import org.springframework.web.bind.annotation.RequestParam;
//import com.yeejoin.amos.latentdanger.business.util.CommonResponse;
//import org.springframework.web.bind.annotation.RequestBody;
//import org.springframework.cloud.openfeign.FeignClient;
//
//
//
////推送
//@FeignClient(name = "${Push.fegin.name}", configuration={MultipartSupportConfig.class})
//public interface PushFeign {
//
// @RequestMapping(value = "/api/user/sendMessageone", method = RequestMethod.POST)
// CommonResponse sendMessageone( @RequestBody PushMsgParam responses);
//
//
// @RequestMapping(value = "/api/user/pushNoticeMany", method = RequestMethod.POST)
// CommonResponse pushNoticeMany( @RequestBody PushMsgParam responses);
//
// @RequestMapping(value = "/api/user/buildPushPayload", method = RequestMethod.POST)
// CommonResponse buildPushPayload( @RequestBody PushMsgParam responses);
//
// @RequestMapping(value = "/api/user/pushDevice", method = RequestMethod.GET)
// CommonResponse PushDevice( @RequestParam("alias") String alias);
//
// @RequestMapping(value = "/api/user/PushDeviceRegistration", method = RequestMethod.GET)
// CommonResponse PushDeviceRegistration( @RequestParam("registrationId") String registrationId,@RequestParam("alias") String alias);
//}
package com.yeejoin.amos.latentdanger.feign;
import com.yeejoin.amos.feign.systemctl.Systemctl;
import com.yeejoin.amos.feign.systemctl.model.MessageModel;
import com.yeejoin.amos.latentdanger.business.param.PushMsgParam;
import org.springframework.stereotype.Service;
import java.util.List;
@Service("pushFeignServer-danger")
public class PushFeignServer {
public void sendMessage(String toke, String product, String appKey, List<PushMsgParam> pushMsgParam) {
try {
pushMsgParam.forEach(action -> {
sendJP(action);
});
} catch (Exception e) {
e.printStackTrace();
}
}
public void sendMessage(String toke, String product, String appKey, PushMsgParam pushMsgParam) {
try {
sendJP(pushMsgParam);
} catch (Exception e) {
e.printStackTrace();
}
}
private void sendJP(PushMsgParam pushMsgParam) {
MessageModel model = new MessageModel();
model.setRelationId(pushMsgParam.getRelationId());
model.setTitle(pushMsgParam.getSubject());
model.setBody(pushMsgParam.getContent());
model.setMsgType("patrolSystem");
model.setRecivers(pushMsgParam.getRecivers());
model.setExtras(pushMsgParam.getExtras());
Systemctl.messageClient.create(model);
}
}
package com.yeejoin.amos.latentdanger.feign;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.typroject.tyboot.core.foundation.context.RequestContext;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Joiner;
import com.yeejoin.amos.boot.biz.common.bo.CompanyBo;
import com.yeejoin.amos.boot.biz.common.bo.DepartmentBo;
import com.yeejoin.amos.component.feign.config.InnerInvokException;
import com.yeejoin.amos.component.feign.config.TokenOperation;
import com.yeejoin.amos.component.feign.model.FeignClientResult;
import com.yeejoin.amos.feign.privilege.Privilege;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;
import com.yeejoin.amos.feign.privilege.model.CompanyModel;
import com.yeejoin.amos.feign.privilege.model.DepartmentModel;
import com.yeejoin.amos.feign.privilege.model.IdPasswordAuthModel;
import com.yeejoin.amos.feign.privilege.model.PermissionModel;
import com.yeejoin.amos.feign.privilege.util.DesUtil;
import com.yeejoin.amos.feign.systemctl.Systemctl;
import com.yeejoin.amos.feign.systemctl.model.DictionarieValueModel;
import com.yeejoin.amos.latentdanger.business.util.CommonResponse;
import com.yeejoin.amos.latentdanger.business.util.Toke;
import com.yeejoin.amos.latentdanger.common.remote.IAMOSSecurityServer;
@Service("remoteSecurityService-danger")
public class RemoteSecurityService {
@Value("${security.password}")
private String password;
@Value("${security.loginId}")
private String loginId;
@Value("${security.productWeb}")
private String productWeb;
@Value("${security.appKey}")
private String appKey;
@Value("${security.productApp}")
private String productApp;
private static final Logger log = LoggerFactory.getLogger(RemoteSecurityService.class);
@Autowired
private RedisTemplate<String, String> redisTemplate;
@Autowired
private IAMOSSecurityServer iAmosSecurityServer;
//根据公司名称获取公司人
public List<CompanyModel> listCompanyTree(String toke, String product, String appKey, String companyName) {
RequestContext.setToken(toke);
RequestContext.setProduct(product);
RequestContext.setAppKey(appKey);
List<CompanyModel> userModel = null;
FeignClientResult feignClientResult;
try {
feignClientResult = Privilege.companyClient.queryAgencyTree(companyName);
userModel = (List<CompanyModel>) feignClientResult.getResult();
} catch (InnerInvokException e) {
e.printStackTrace();
}
return userModel;
}
public List<AgencyUserModel> listUserByMenuCode(String permissionType, String path) {
CommonResponse commonResponse = iAmosSecurityServer.listUserByMenuCode(permissionType, path);
return handleArray(commonResponse, AgencyUserModel.class);
}
public List<AgencyUserModel> listUserByMenuCode(String token, String product, String appKey, String permissionType, String path) {
CommonResponse commonResponse = iAmosSecurityServer.listUserByMenuCode(permissionType, path);
return handleArray(commonResponse, AgencyUserModel.class);
}
public JSONArray getMenuPathByUserIdAndPermissionType(String userId, String permissionType) {
CommonResponse commonResponse = iAmosSecurityServer.getMenuPathByUserIdAndPermissionType(userId, permissionType);
if (commonResponse != null && commonResponse.isSuccess()) {
String jsonStr = JSON.toJSONString(commonResponse.getDataList());
return JSONArray.parseArray(jsonStr);
}
return null;
}
public Toke getServerToken() {
IdPasswordAuthModel dPasswordAuthModel = new IdPasswordAuthModel();
dPasswordAuthModel.setLoginId(loginId);
dPasswordAuthModel.setPassword(DesUtil.encode(password, "qaz"));
Toke toke = null;
try {
toke = JSON.parseObject(redisTemplate.opsForValue().get(buildKey(loginId)), Toke.class);
if (ObjectUtils.isEmpty(toke)) {
toke = getLogin(dPasswordAuthModel);
} else {
RequestContext.setProduct(productWeb);
if (!TokenOperation.refresh(toke.getToke())) {
toke = getLogin(dPasswordAuthModel);
}
}
} catch (InnerInvokException e) {
e.printStackTrace();
}
return toke;
}
private Toke getLogin(IdPasswordAuthModel dPasswordAuthModel) {
Toke toke = new Toke();
RequestContext.setProduct(productWeb);
FeignClientResult feignClientResult = Privilege.authClient.idpassword(dPasswordAuthModel);
Map map = (Map) feignClientResult.getResult();
if (map != null) {
toke.setToke(map.get("token").toString());
toke.setProduct(productWeb);
toke.setAppKey(appKey);
redisTemplate.opsForValue().set(buildKey(dPasswordAuthModel.getLoginId()), JSONObject.toJSONString(toke), 28, TimeUnit.DAYS);
}
return toke;
}
//redi缓存系统用户token信息
private String buildKey(String username) {
return "system_" + username;
}
//部门id获取部门信息
public DepartmentModel getDepartmentByDeptId(String toke, String product, String appKey, String deparmentId) {
if (deparmentId == null || deparmentId.equals("")) {
return null;
}
// CommonResponse commonResponse = iAmosSecurityServer.getDepartmentByDeptId(deparmentId);
// return handleObj(commonResponse, DepartmentBo.class);
RequestContext.setToken(toke);
RequestContext.setProduct(product);
RequestContext.setAppKey(appKey);
DepartmentModel departmentModel = null;
FeignClientResult feignClientResult;
try {
feignClientResult = Privilege.departmentClient.seleteOne(Long.valueOf(deparmentId));
departmentModel = (DepartmentModel) feignClientResult.getResult();
} catch (InnerInvokException e) {
e.printStackTrace();
}
return departmentModel;
}
//查询指定部门数
public List<DepartmentModel> listDepartmentsByCompanyId(String toke, String product, String appKey, String companyId) {
if (companyId == null || companyId.equals("")) {
return null;
}
RequestContext.setToken(toke);
RequestContext.setProduct(product);
RequestContext.setAppKey(appKey);
List<DepartmentModel> departmentModel = null;
FeignClientResult feignClientResult;
try {
feignClientResult = Privilege.departmentClient.queryDeptTree(null, Long.valueOf(companyId));
departmentModel = (List<DepartmentModel>) feignClientResult.getResult();
} catch (InnerInvokException e) {
e.printStackTrace();
}
return departmentModel;
//CommonResponse commonResponse = iAmosSecurityServer.listDepartmentsByCompanyId(companyId);
//return handleArray(commonResponse, DepartmentBo.class);
}
// * 根据公司id查询机构用户
public List<AgencyUserModel> listUserByCompanyId(String toke, String product, String appKey, String companyId) {
if (companyId == null || companyId.equals("")) {
return null;
}
RequestContext.setToken(toke);
RequestContext.setProduct(product);
RequestContext.setAppKey(appKey);
List<AgencyUserModel> AgencyUserModel = null;
FeignClientResult feignClientResult;
try {
feignClientResult = Privilege.agencyUserClient.queryByCompanyId(Long.valueOf(companyId), null, null, true);
AgencyUserModel = (List<AgencyUserModel>) feignClientResult.getResult();
} catch (InnerInvokException e) {
e.printStackTrace();
}
return AgencyUserModel;
}
// * 根据公司RoleIds
public List<AgencyUserModel> getUserByRoleIds(String toke, String product, String appKey, String RoleIds) {
if (RoleIds == null || RoleIds.equals("")) {
return null;
}
RequestContext.setToken(toke);
RequestContext.setProduct(product);
RequestContext.setAppKey(appKey);
List<AgencyUserModel> agencyUserModel = null;
FeignClientResult feignClientResult;
try {
feignClientResult = Privilege.agencyUserClient.queryByRoleId(RoleIds, null);
agencyUserModel = (List<AgencyUserModel>) feignClientResult.getResult();
} catch (InnerInvokException e) {
e.printStackTrace();
}
return agencyUserModel;
}
//用户id批量获取用户信息
public List<AgencyUserModel> listUserByUserIds(String toke, String product, String appKey, String userIds) {
RequestContext.setToken(toke);
RequestContext.setProduct(product);
RequestContext.setAppKey(appKey);
List<AgencyUserModel> agencyUserModel = null;
FeignClientResult feignClientResult;
try {
feignClientResult = Privilege.agencyUserClient.queryByIds(userIds, null);
agencyUserModel = (List<AgencyUserModel>) feignClientResult.getResult();
} catch (InnerInvokException e) {
e.printStackTrace();
}
return agencyUserModel;
}
public List<AgencyUserModel> listUserByUserIds(String userIds) {
CommonResponse commonResponse = iAmosSecurityServer.listUserByUserIds(userIds,true);
return handleArray(commonResponse, AgencyUserModel.class);
}
public AgencyUserModel getUserById(String userId) {
if (userId == null || userId.equals("")) {
return null;
}
CommonResponse commonResponse = iAmosSecurityServer.getUserById(userId);
return handleObj(commonResponse, AgencyUserModel.class);
}
public DepartmentBo getDepartmentByDeptId(String deparmentId) {
if (deparmentId == null || deparmentId.equals("")) {
return null;
}
CommonResponse commonResponse = iAmosSecurityServer.getDepartmentByDeptId(deparmentId);
return handleObj(commonResponse, DepartmentBo.class);
}
public List<DepartmentBo> listDepartmentByDeptIds(String departmentIds) {
CommonResponse commonResponse = iAmosSecurityServer.listDepartmentByDeptIds(departmentIds);
return handleArray(commonResponse, DepartmentBo.class);
}
public List<DepartmentBo> getDepartmentTreeByCompanyId(String companyId) {
if (companyId == null || companyId.equals("")) {
return null;
}
CommonResponse commonResponse = iAmosSecurityServer.getDepartmentTreeByCompanyId(companyId);
return handleArray(commonResponse, DepartmentBo.class);
}
public List<CompanyBo> listCompanyTree() {
CommonResponse commonResponse = iAmosSecurityServer.listCompanyTree();
return handleArray(commonResponse, CompanyBo.class);
}
//用户id获取用户信息
public AgencyUserModel getUserById(String toke, String product, String appKey, String userId) {
if (userId == null || userId.equals("")) {
return null;
}
RequestContext.setToken(toke);
RequestContext.setProduct(product);
RequestContext.setAppKey(appKey);
AgencyUserModel agencyUserModel = null;
FeignClientResult feignClientResult;
try {
feignClientResult = Privilege.agencyUserClient.queryByUserId(userId);
agencyUserModel = (AgencyUserModel) feignClientResult.getResult();
} catch (InnerInvokException e) {
e.printStackTrace();
}
return agencyUserModel;
}
//根据orgCode查询机构用户
public List<AgencyUserModel> listUserByOrgCode(String toke, String product, String appKey, String orgCode) {
if (orgCode == null || orgCode.equals("")) {
return null;
}
RequestContext.setToken(toke);
RequestContext.setProduct(product);
RequestContext.setAppKey(appKey);
List<AgencyUserModel> agencyUserModel = null;
FeignClientResult feignClientResult;
try {
feignClientResult = Privilege.agencyUserClient.queryByOrgCode(orgCode, null);
HashSet<AgencyUserModel> agencyUserModelSet = (HashSet<AgencyUserModel>) feignClientResult.getResult();
agencyUserModel = new ArrayList<AgencyUserModel>(agencyUserModelSet);
} catch (InnerInvokException e) {
e.printStackTrace();
}
return agencyUserModel;
}
//根据orgCode查询机构
public Map<String, Object> listByOrgCode(String toke, String product, String appKey, String orgCode) {
if (orgCode == null || orgCode.equals("")) {
return null;
}
RequestContext.setToken(toke);
RequestContext.setProduct(product);
RequestContext.setAppKey(appKey);
Map<String, Object> agencyUserModel = null;
FeignClientResult feignClientResult;
try {
feignClientResult = Privilege.companyClient.queryByOrgcode(orgCode);
agencyUserModel = (Map<String, Object>) feignClientResult.getResult();
} catch (InnerInvokException e) {
e.printStackTrace();
}
return agencyUserModel;
}
// 根据部门id查询机构用户
public List<AgencyUserModel> listUserByDepartmentId(String toke, String product, String appKey, String departmentId) {
if (departmentId == null || departmentId.equals("")) {
return null;
}
RequestContext.setToken(toke);
RequestContext.setProduct(product);
RequestContext.setAppKey(appKey);
List<AgencyUserModel> agencyUserModel = null;
FeignClientResult feignClientResult;
try {
feignClientResult = Privilege.agencyUserClient.queryByDepartmentId(Long.valueOf(departmentId), null, null, null);
agencyUserModel = (List<AgencyUserModel>) feignClientResult.getResult();
} catch (InnerInvokException e) {
e.printStackTrace();
}
return agencyUserModel;
}
//* 获取子公司信息树结构
public List<CompanyModel> getCompanyTreeByCompanyId(String toke, String product, String appKey, String companyId) {
if (companyId == null || companyId.equals("")) {
return null;
}
RequestContext.setToken(toke);
RequestContext.setProduct(product);
RequestContext.setAppKey(appKey);
List<CompanyModel> companyModel = null;
FeignClientResult feignClientResult;
try {
feignClientResult = Privilege.companyClient.querySubAgencyTree(Long.valueOf(companyId));
companyModel = (List<CompanyModel>) feignClientResult.getResult();
} catch (InnerInvokException e) {
e.printStackTrace();
}
return companyModel;
}
//查询指定公司的部门树
public List<DepartmentModel> getDepartmentTreeByCompanyId(String toke, String product, String appKey, String companyId) {
if (companyId == null || companyId.equals("")) {
return null;
}
RequestContext.setToken(toke);
RequestContext.setProduct(product);
RequestContext.setAppKey(appKey);
List<DepartmentModel> departmentModel = null;
FeignClientResult feignClientResult;
try {
feignClientResult = Privilege.departmentClient.queryDeptTree(null, Long.valueOf(companyId));
departmentModel = (List<DepartmentModel>) feignClientResult.getResult();
} catch (InnerInvokException e) {
e.printStackTrace();
}
return departmentModel;
}
//根据id批量获取部门信息
public List<LinkedHashMap> listDepartmentByDeptIds(String toke, String product, String appKey, String departmentIds) {
RequestContext.setToken(toke);
RequestContext.setProduct(product);
RequestContext.setAppKey(appKey);
List<LinkedHashMap> departmentModel = null;
FeignClientResult feignClientResult;
try {
feignClientResult = Privilege.departmentClient.queryDeptByIds(departmentIds);
departmentModel = (List<LinkedHashMap>) feignClientResult.getResult();
} catch (InnerInvokException e) {
e.printStackTrace();
}
return departmentModel;
}
private <T> List<T> handleArray(CommonResponse commonResponse, Class<T> t) {
if (commonResponse != null && commonResponse.isSuccess()) {
String jsonStr = JSON.toJSONString(commonResponse.getDataList());
return JSONArray.parseArray(jsonStr, t);
}
return null;
}
private <T> T handleObj(CommonResponse commonResponse, Class<T> t) {
if (commonResponse != null && commonResponse.isSuccess()) {
String jsonStr = JSON.toJSONString(commonResponse.getDataList());
return JSONObject.parseObject(jsonStr, t);
}
return null;
}
/**
* 基础平台全部菜单权限树,用于平台登录前端初始化路由
*/
public CommonResponse searchPermissionTree(String toke, String product, String appKey, String appType) {
RequestContext.setToken(toke);
RequestContext.setProduct(product);
RequestContext.setAppKey(appKey);
List<PermissionModel> dictionarieModel = null;
FeignClientResult feignClientResult;
try {
feignClientResult = Privilege.permissionClient.queryPermissionTree(appType, null, null, null, null);
dictionarieModel = (List<PermissionModel>) feignClientResult.getResult();
} catch (InnerInvokException e) {
e.printStackTrace();
}
CommonResponse commonResponse = new CommonResponse("SUCCESS", dictionarieModel);
return commonResponse;
}
public JSONArray getMenuPathByUserIdAndPermissionType(String toke, String product, String appKey, String userId, String permissionType) {
RequestContext.setToken(toke);
RequestContext.setProduct(product);
RequestContext.setAppKey(appKey);
Object dictionarieModel = null;
FeignClientResult feignClientResult;
try {
feignClientResult = Privilege.permissionClient.queryPathForListByUser(permissionType, null, userId);
dictionarieModel = feignClientResult.getResult();
} catch (InnerInvokException e) {
e.printStackTrace();
}
if (dictionarieModel != null) {
String jsonStr = JSON.toJSONString(dictionarieModel);
return JSONArray.parseArray(jsonStr);
}
return null;
}
//根据Code查询指定的字典信息.
public JSONArray listDictionaryByDictCode(String toke, String product, String appKey, String dictCode) {
RequestContext.setToken(toke);
RequestContext.setProduct(product);
RequestContext.setAppKey(appKey);
List<DictionarieValueModel> dictionarieModel = null;
FeignClientResult feignClientResult;
try {
feignClientResult = Systemctl.dictionarieClient.dictValues(dictCode);
dictionarieModel = (List<DictionarieValueModel>) feignClientResult.getResult();
} catch (InnerInvokException e) {
e.printStackTrace();
}
if (dictionarieModel != null) {
String jsonStr = JSON.toJSONString(dictionarieModel);
return JSONArray.parseArray(jsonStr);
}
return null;
}
/**
* 查询指定公司信息与其部门用户树
*/
public CompanyModel listUserByCompanyId1(String toke, String product, String appKey, String companyId) {
if (companyId == null || companyId.equals("")) {
return null;
}
RequestContext.setToken(toke);
RequestContext.setProduct(product);
RequestContext.setAppKey(appKey);
CompanyModel companyModel = null;
FeignClientResult feignClientResult;
try {
feignClientResult = Privilege.companyClient.withDeptAndUsers(Long.valueOf(companyId));
companyModel = (CompanyModel) feignClientResult.getResult();
} catch (InnerInvokException e) {
e.printStackTrace();
}
return companyModel;
}
public JSONObject loginFromApp(String userName, String password) {
IdPasswordAuthModel dPasswordAuthModel = new IdPasswordAuthModel();
dPasswordAuthModel.setLoginId(userName);
dPasswordAuthModel.setPassword(DesUtil.decode(password, "yeejoin"));
Map map = null;
FeignClientResult feignClientResult = new FeignClientResult();
RequestContext.setProduct(productApp);
Toke oked = new Toke();
try {
feignClientResult = Privilege.authClient.idpassword(dPasswordAuthModel);
map = (Map) feignClientResult.getResult();
map.put("appKey", appKey);
map.put("product", productApp);
} catch (InnerInvokException e) {
e.printStackTrace();
}
if (map != null) {
String jsonStr = JSON.toJSONString(map);
return JSONObject.parseObject(jsonStr);
}
return null;
}
public boolean loginOutFromApp(String toke, String product, String appKey) {
RequestContext.setToken(toke);
RequestContext.setProduct(product);
RequestContext.setAppKey(appKey);
boolean flag = false;
FeignClientResult feignClientResult;
try {
feignClientResult = Privilege.authClient.removeToken();
flag = true;
} catch (InnerInvokException e) {
e.printStackTrace();
}
return flag;
}
public JSONArray listDepartmentUserTree(String toke, String product, String appKey, String companyId) {
RequestContext.setToken(toke);
RequestContext.setProduct(product);
RequestContext.setAppKey(appKey);
CompanyModel companyModel = null;
FeignClientResult feignClientResult;
try {
feignClientResult = Privilege.companyClient.withDeptAndUsers(Long.valueOf(companyId));
companyModel = (CompanyModel) feignClientResult.getResult();
} catch (InnerInvokException e) {
e.printStackTrace();
}
if (companyModel != null) {
String jsonStr = null;
jsonStr = JSON.toJSONString(companyModel.getChildren());
return JSONArray.parseArray(jsonStr);
}
return null;
}
public boolean editPassword(String toke, String product, String appKey, String userId, String oldPassword, String newPassword) {
boolean flag = false;
RequestContext.setToken(toke);
RequestContext.setProduct(product);
RequestContext.setAppKey(appKey);
AgencyUserModel agencyUserModel = new AgencyUserModel();
agencyUserModel.setPassword(newPassword);
agencyUserModel.setRePassword(newPassword);
agencyUserModel.setOriginalPassword(oldPassword);
AgencyUserModel agencyUserModel2 = null;
FeignClientResult feignClientResult;
try {
feignClientResult = Privilege.agencyUserClient.modifyPassword(userId, agencyUserModel);
agencyUserModel2 = (AgencyUserModel) feignClientResult.getResult();
} catch (InnerInvokException e) {
e.printStackTrace();
}
if (agencyUserModel2 != null) {
flag = true;
}
return flag;
}
public AgencyUserModel getAgencyUserModel(String token) {
RequestContext.setToken(token);
RequestContext.setAppKey(appKey);
RequestContext.setProduct(productWeb);
try {
AgencyUserModel result = Privilege.agencyUserClient.getme().getResult();
return result;
} catch (InnerInvokException e) {
e.printStackTrace();
}
return null;
}
/**
* 基础平台全部菜单权限树,用于平台登录前端初始化路由
*/
public CommonResponse searchPermissionTree(long id, String toke, String product, String appKey, String appType) {
RequestContext.setToken(toke);
RequestContext.setProduct(product);
RequestContext.setAppKey(appKey);
List<PermissionModel> dictionarieModel = null;
FeignClientResult feignClientResult;
try {
feignClientResult = Privilege.permissionClient.treeByRole(id, appType, null, null);
dictionarieModel = (List<PermissionModel>) feignClientResult.getResult();
} catch (InnerInvokException e) {
e.printStackTrace();
}
CommonResponse commonResponse = new CommonResponse("SUCCESS", dictionarieModel);
return commonResponse;
}
/**
* 根据用户ids获取用户实体列表
*
* @param toke
* @param product
* @param appKey
* @param userIds
* @return
*/
public Map<String, AgencyUserModel> getUsersMap(String toke, String product, String appKey, Set<Object> userIds) {
List<AgencyUserModel> users = listUserByUserIds(toke, product, appKey, Joiner.on(",").join(userIds));
Map<String, AgencyUserModel> userMap = new HashMap<>();
if (users != null) {
userMap = users.stream().collect(Collectors.toMap(AgencyUserModel::getUserId, v -> v, (v1, v2) -> v1));
}
return userMap;
}
/**
* 根据用户ids获取用户名称列表
*
* @param toke
* @param product
* @param appKey
* @param userIds
* @return
*/
public Map<String, String> getUserRealName(String toke, String product, String appKey, Set<Object> userIds) {
List<AgencyUserModel> users = listUserByUserIds(toke, product, appKey, Joiner.on(",").join(userIds));
Map<String, String> userMap = new HashMap<>();
if (users != null) {
userMap = users.stream().collect(Collectors.toMap(AgencyUserModel::getUserId, AgencyUserModel::getRealName));
}
return userMap;
}
/**
* 根据部门ids获取部门名称
*
* @param toke
* @param product
* @param appKey
* @param depIds
* @return
*/
public Map<Long, String> getDepName(String toke, String product, String appKey, Set<Object> depIds) {
List<DepartmentModel> depts = new ArrayList<>();
if (!CollectionUtils.isEmpty(depIds)) {
depts = this.getlistDepartmentByDeptIds(toke, product, appKey, Joiner.on(",").join(depIds));
}
Map<Long, String> deptMap = new HashMap<>();
if (depts != null) {
deptMap = depts.stream().collect(Collectors.toMap(DepartmentModel::getSequenceNbr, DepartmentModel::getDepartmentName));
}
return deptMap;
}
/**
* 根据id批量获取部门信息
*
* @param toke token
* @param product product
* @param appKey appKey
* @param "200".equals(feignClientResult.getStatus())departmentIds 部门ids
* @return List<DepartmentModel>
*/
public List<DepartmentModel> getlistDepartmentByDeptIds(String toke, String product, String appKey, String departmentIds) {
RequestContext.setToken(toke);
RequestContext.setProduct(product);
RequestContext.setAppKey(appKey);
FeignClientResult feignClientResult = new FeignClientResult();
try {
feignClientResult = Privilege.departmentClient.queryDeptByIds(departmentIds);
} catch (InnerInvokException e) {
e.printStackTrace();
}
return handleArray(feignClientResult, DepartmentModel.class);
}
private <T> List<T> handleArray(FeignClientResult feignClientResult, Class<T> t) {
List<T> list = new ArrayList<>();
if (feignClientResult != null && feignClientResult.getStatus() == 200) {
String jsonStr = JSON.toJSONString(feignClientResult.getResult());
list = JSONArray.parseArray(jsonStr, t);
}
return list;
}
}
package com.yeejoin.amos.latentdanger.mqtt;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttPersistenceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.typroject.tyboot.component.emq.EmqKeeper;
@Component(value = "webMqttComponent-danger")
public class WebMqttComponent {
@Autowired
private EmqKeeper emqKeeper;
public void publish(String topic, String jsonStr) {
try {
this.emqKeeper.getMqttClient().publish(topic, jsonStr.getBytes(), 1, false);
} catch (MqttPersistenceException e) {
e.printStackTrace();
} catch (MqttException e) {
e.printStackTrace();
}
}
}
package com.yeejoin.amos.latentdanger.schedule;
import com.yeejoin.amos.latentdanger.business.service.intfc.ILatentDangerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
/**
* 隐患定时任务
* @author DELL
*/
@Configuration("latentDangerScheduled")
@EnableScheduling
public class LatentDangerScheduled {
@Autowired
private ILatentDangerService iLatentDangerService;
/**
* 每1分钟执行一次:查询逾期的隐患,修改状态
*/
@Scheduled(cron = "0 0/1 * * * ?")
public void updateDangerStateOfOvertime() {
iLatentDangerService.updateDangerStateOfOvertime();
}
}
\ No newline at end of file
<?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>
<artifactId>amos-biz-boot</artifactId>
<groupId>com.amosframework.boot</groupId>
<version>1.0.0</version>
</parent>
<artifactId>amos-boot-system-latentdanger</artifactId>
<version>1.0.0</version>
<dependencies>
<dependency>
<groupId>com.amosframework.boot</groupId>
<artifactId>amos-boot-module-latentdanger-api</artifactId>
<version>${amos-biz-boot.version}</version>
</dependency>
<dependency>
<groupId>com.amosframework.boot</groupId>
<artifactId>amos-boot-module-latentdanger-biz</artifactId>
<version>1.0.0</version>
<scope>compile</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
package com.yeejoin.amos;
import org.mybatis.spring.annotation.MapperScan;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.FilterType;
import org.springframework.core.env.Environment;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.client.RestTemplate;
import org.typroject.tyboot.core.restful.config.JsonSerializerManage;
import org.typroject.tyboot.core.restful.exception.GlobalExceptionHandler;
import java.io.IOException;
import java.net.InetAddress;
import java.net.URISyntaxException;
import java.net.UnknownHostException;
/**
* <pre>
* 隐患服务启动类
* </pre>
*
* @author amos
* @version $Id: LatentDangerApplication.java, v 0.1 2018年11月26日 下午4:56:29 amos Exp $
*/
@SpringBootApplication
@EnableTransactionManagement
@EnableConfigurationProperties
@ServletComponentScan
@EnableJpaAuditing
@EnableDiscoveryClient
@EnableFeignClients
@EnableAsync
@EnableEurekaClient
@ComponentScan(value = {"org.typroject", "com.yeejoin.amos"}, excludeFilters = {
@ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, classes = {JsonSerializerManage.class})})
@MapperScan(basePackages = {"com.yeejoin.amos.latentdanger.business.dao.mapper", "org.typroject.tyboot.core.auth.face" +
".orm.dao", "com.yeejoin.amos.boot.biz.common.dao.mapper"})
public class LatentDangerApplication {
private static final Logger logger = LoggerFactory.getLogger(LatentDangerApplication.class);
@Bean
@LoadBalanced
RestTemplate initRestTemplate() {
return new RestTemplate();
}
/**
* 启动amosop-server
*
* @param args
* @throws IOException
* @throws URISyntaxException
*/
public static void main(String[] args) throws UnknownHostException {
logger.info("start Service..........");
ConfigurableApplicationContext context = SpringApplication.run(LatentDangerApplication.class, args);
GlobalExceptionHandler.setAlwaysOk(true);
Environment env = context.getEnvironment();
String ip = InetAddress.getLocalHost().getHostAddress();
String port = env.getProperty("server.port");
String path = env.getProperty("server.servlet.context-path");
GlobalExceptionHandler.setAlwaysOk(true);
logger.info("\n----------------------------------------------------------\n\t" +
"Application Amos-Biz-Boot is running! Access URLs:\n\t" +
"Swagger文档: \thttp://" + ip + ":" + port + path + "/doc.html\n" +
"----------------------------------------------------------");
}
}
\ No newline at end of file
eureka.client.serviceUrl.defaultZone=http://172.16.10.72:10001/eureka/
eureka.client.registry-fetch-interval-seconds=5
eureka.instance.prefer-ip-address=true
management.endpoint.health.show-details=always
management.endpoints.web.exposure.include=*
eureka.instance.health-check-url-path=/actuator/health
eureka.instance.lease-expiration-duration-in-seconds=10
eureka.instance.lease-renewal-interval-in-seconds=5
eureka.instance.metadata-map.management.context-path=${server.servlet.context-path}/actuator
eureka.instance.status-page-url-path=/actuator/info
ribbon.eureka.enabled = true
ribbon.ConnectTimeout = 5000
ribbon.ReadTimeout = 6000
ribbon.OkToRetryOnAllOperations = true
ribbon.MaxAutoRetriesNextServer = 2
ribbon.MaxAutoRetries = 1
#DB properties:
spring.datasource.url = jdbc:mysql://172.16.6.60:3306/amos-jcs-biz?useUnicode=true&characterEncoding=utf-8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=Asia/Shanghai
spring.datasource.username= root
spring.datasource.password= root_123
spring.datasource.driver-class-name = com.mysql.jdbc.Driver
spring.datasource.hikari.maxLifetime = 1765000
spring.datasource.hikari.maximum-pool-size = 10
spring.datasource.testWhileIdle = true
spring.datasource.validationQuery = SELECT 1
security.password=a1234560
security.loginId=jc_wjk006
security.productWeb=STUDIO_APP_WEB
security.productApp=STUDIO_APP_MOBILE
security.appKey=studio_normalapp_3168830
#redis 配置
spring.redis.database=0
spring.redis.host=172.16.10.85
spring.redis.port=6379
spring.redis.password=amos2019Redis
spring.redis.jedis.pool.max-active=200
spring.redis.jedis.pool.max-wait=-1
spring.redis.jedis.pool.max-idle=10
spring.redis.jedis.pool.min-idle=0
spring.redis.timeout=1000
#巡检计划定时任务
jobs.cron = 0 0/1 22-23 * * ?
#邮件配置
#params.mailPush = false
#spring.mail.host:
#spring.mail.username:
#spring.mail.password:
#spring.mail.port=
#mail.fromMail.addr =
#spring.mail.default-encoding=UTF-8
#spring.mail.properties.mail.smtp.auth: true
#spring.mail.properties.mail.smtp.starttls.enable: true
#spring.mail.properties.mail.smtp.starttls.required: true
#spring.mail.properties.mail.smtp.ssl.enable:true
#jpush 推送配置项
params.isPush = false
params.work.flow.processDefinitionKey=hazardManagement
params.work.flow.address=http://172.16.10.80:30040
params.spc.address=http://172.16.3.89:9001
#websocket
params.remoteWebsocketUrl=http://39.100.241.164:8080/
#websocket send message url
params.remoteWebSocketSendMsgUrl=http://39.100.241.164:10601/
#上传文件配置
spring.http.multipart.maxFileSize = 80480000
spring.http.multipart.MaxRequestSize = 80480000
windows.img.path = D:\\
linux.img.path = /
## emqx
emqx.clean-session=true
emqx.client-id=${spring.application.name}-${random.int[1024,65536]}-1
emqx.broker=tcp://172.16.10.85:1883
emqx.user-name=super
emqx.password=a123456
emqx.max-inflight=1000
file.url=http://39.98.45.134:9000/
iot.fegin.name=AMOS-API-IOT
control.fegin.name=JCS-API-CONTROL
supervision.feign.name=AMOS-SUPERVISION-API
\ No newline at end of file
eureka.client.serviceUrl.defaultZone=http://172.16.10.72:10001/eureka/
eureka.client.register-with-eureka = true
eureka.client.fetch-registry = true
eureka.client.healthcheck.enabled = true
eureka.client.fetchRegistry = true
eureka.instance.prefer-ip-address=true
ribbon.eureka.enabled = true
ribbon.ConnectTimeout = 5000
ribbon.ReadTimeout = 6000
ribbon.OkToRetryOnAllOperations = true
ribbon.MaxAutoRetriesNextServer = 2
ribbon.MaxAutoRetries = 1
#DB properties:
spring.datasource.url = jdbc:mysql://172.16.10.66:3306/safety-business-3.0.1?useUnicode=true&characterEncoding=utf-8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=Asia/Shanghai
spring.datasource.username= root
spring.datasource.password= root_123
spring.datasource.driver-class-name = com.mysql.jdbc.Driver
spring.datasource.hikari.maxLifetime = 1765000
spring.datasource.hikari.maximum-pool-size = 10
spring.datasource.testWhileIdle = true
spring.datasource.validationQuery = SELECT 1
security.password=a1234560
security.loginId=jc_wjk006
security.productWeb=STUDIO_APP_WEB
security.productApp=STUDIO_APP_MOBILE
security.appKey=studio_normalapp_3168830
#redis 配置
spring.redis.database=0
spring.redis.host=172.16.10.85
spring.redis.port=6379
spring.redis.password=amos2019Redis
spring.redis.jedis.pool.max-active=200
spring.redis.jedis.pool.max-wait=-1
spring.redis.jedis.pool.max-idle=10
spring.redis.jedis.pool.min-idle=0
spring.redis.timeout=1000
#巡检计划定时任务
jobs.cron = 0 0/1 22-23 * * ?
#邮件配置
#params.mailPush = false
#spring.mail.host:
#spring.mail.username:
#spring.mail.password:
#spring.mail.port=
#mail.fromMail.addr =
#spring.mail.default-encoding=UTF-8
#spring.mail.properties.mail.smtp.auth: true
#spring.mail.properties.mail.smtp.starttls.enable: true
#spring.mail.properties.mail.smtp.starttls.required: true
#spring.mail.properties.mail.smtp.ssl.enable:true
#jpush 推送配置项
params.isPush = false
params.work.flow.processDefinitionKey=hazardManagement
params.work.flow.address=http://172.16.10.80:30040
params.spc.address=http://172.16.3.89:9001
#websocket
params.remoteWebsocketUrl=http://39.100.241.164:8080/
#websocket send message url
params.remoteWebSocketSendMsgUrl=http://39.100.241.164:10601/
#上传文件配置
spring.http.multipart.maxFileSize = 80480000
spring.http.multipart.MaxRequestSize = 80480000
windows.img.path = D:\\
linux.img.path = /
## emqx
emqx.clean-session=true
emqx.client-id=${spring.application.name}-${random.int[1024,65536]}-1
emqx.broker=tcp://172.16.10.85:1883
emqx.user-name=super
emqx.password=a123456
emqx.max-inflight=1000
file.url=http://39.98.45.134:9000/
\ No newline at end of file
eureka.client.serviceUrl.defaultZone=http://172.16.10.72:10001/eureka/
eureka.client.register-with-eureka = true
eureka.client.fetch-registry = true
eureka.client.healthcheck.enabled = true
eureka.client.fetchRegistry = true
eureka.instance.prefer-ip-address=true
ribbon.eureka.enabled = true
ribbon.ConnectTimeout = 5000
ribbon.ReadTimeout = 6000
ribbon.OkToRetryOnAllOperations = true
ribbon.MaxAutoRetriesNextServer = 2
ribbon.MaxAutoRetries = 1
#DB properties:
spring.datasource.url = jdbc:mysql://172.16.10.66:3306/safety-business-3.0.1?useUnicode=true&characterEncoding=utf-8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=Asia/Shanghai
spring.datasource.username= root
spring.datasource.password= root_123
spring.datasource.driver-class-name = com.mysql.jdbc.Driver
spring.datasource.hikari.maxLifetime = 1765000
spring.datasource.hikari.maximum-pool-size = 10
spring.datasource.testWhileIdle = true
spring.datasource.validationQuery = SELECT 1
security.password=a1234560
security.loginId=jc_wjk006
security.productWeb=STUDIO_APP_WEB
security.productApp=STUDIO_APP_MOBILE
security.appKey=studio_normalapp_3168830
#redis 配置
spring.redis.database=0
spring.redis.host=172.16.10.85
spring.redis.port=6379
spring.redis.password=amos2019Redis
spring.redis.jedis.pool.max-active=200
spring.redis.jedis.pool.max-wait=-1
spring.redis.jedis.pool.max-idle=10
spring.redis.jedis.pool.min-idle=0
spring.redis.timeout=1000
#巡检计划定时任务
jobs.cron = 0 0/1 22-23 * * ?
#邮件配置
#params.mailPush = false
#spring.mail.host:
#spring.mail.username:
#spring.mail.password:
#spring.mail.port=
#mail.fromMail.addr =
#spring.mail.default-encoding=UTF-8
#spring.mail.properties.mail.smtp.auth: true
#spring.mail.properties.mail.smtp.starttls.enable: true
#spring.mail.properties.mail.smtp.starttls.required: true
#spring.mail.properties.mail.smtp.ssl.enable:true
#jpush 推送配置项
params.isPush = false
params.work.flow.processDefinitionKey=hazardManagement
params.work.flow.address=http://172.16.10.80:30040
params.spc.address=http://172.16.3.89:9001
#websocket
params.remoteWebsocketUrl=http://39.100.241.164:8080/
#websocket send message url
params.remoteWebSocketSendMsgUrl=http://39.100.241.164:10601/
#上传文件配置
spring.http.multipart.maxFileSize = 80480000
spring.http.multipart.MaxRequestSize = 80480000
windows.img.path = D:\\
linux.img.path = /
## emqx
emqx.clean-session=true
emqx.client-id=${spring.application.name}-${random.int[1024,65536]}-1
emqx.broker=tcp://172.16.10.85:1883
emqx.user-name=super
emqx.password=a123456
emqx.max-inflight=1000
file.url=http://39.98.45.134:9000/
\ No newline at end of file
spring.application.name = AMOS-LATENT-DANGER
server.servlet.context-path=/latentDanger
server.port = 8086
spring.profiles.active=dev
spring.jackson.serialization.write-dates-as-timestamps=true
feign.httpclient.enabled= true
logging.config=classpath:logback-${spring.profiles.active}.xml
#鏃堕棿杩斿洖绫诲瀷閰嶇疆
spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
spring.jackson.time-zone = Asia/Shanghai
#DB properties:
spring.jpa.show-sql = true
spring.jpa.hibernate.ddl-auto = none
spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy
spring.jpa.database-platform = org.hibernate.dialect.MySQLDialect
mybatis.mapper-locations = classpath:db/mapper/*.xml
mybatis-plus.mapper-locations=classpath:db/mapper/*.xml
mybatis.type-aliases-package = com.yeejoin.amos.patrol.business.entity.mybatis
mybatis.configuration.mapUnderscoreToCamelCase=true
spring.liquibase.change-log=classpath:/db/changelog/changelog-master.xml
spring.liquibase.enabled=true
mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
equip.fegin.name=AMOS-EQUIPMANAGE
equip.fegin.prefix=/equip
input.custom.prefix = QYZD
input.statute.prefix = FG
Security.fegin.name=AMOS-API-PRIVILEGE
amos.feign.gennerator.use-gateway=true
Business.fegin.name=AMOS-AUTOSYS
Push.fegin.name=APPMESSAGEPUSHSERVICE
amos.flowWork.topic =/STATE_GRID/hazardManagement
amosRefresh.danger.topic =patrolDangerInsertOrUpdate
amosRefresh.patrol.topic =patrolCheckInsert
#停止通过WEB公开所有端点
management.endpoints.web.exposure.exclude=*
## redis失效时间
redis.cache.failure.time=10800
danger.biz.type=supervision
workflow.process.definition.key=fire_supervision_hazard_management
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<databaseChangeLog
xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog
http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.4.xsd">
<include file="latent-danger-init-table.xml" relativeToChangelogFile="true"/>
<include file="latent-danger-1.0.0.xml" relativeToChangelogFile="true"/>
</databaseChangeLog>
\ No newline at end of file
/*
Navicat Premium Data Transfer
Source Server : 172.16.6.60
Source Server Type : MySQL
Source Server Version : 50722
Source Host : 172.16.6.60:3306
Source Schema : amos-jcs-biz
Target Server Type : MySQL
Target Server Version : 50722
File Encoding : 65001
Date: 18/09/2021 11:18:50
*/
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for cb_latent_danger
-- ----------------------------
DROP TABLE IF EXISTS `cb_latent_danger`;
CREATE TABLE `cb_latent_danger` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键自增',
`biz_type` varchar(30) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '业务类型(不同业务创建的隐患以此区分)',
`business_key` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '业务唯一标识',
`org_code` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '公司',
`danger_name` varchar(500) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '隐患名称',
`current_flow_record_id` bigint(20) NULL DEFAULT NULL COMMENT '当前工作流记录编号',
`instance_id` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '工作流实例编号',
`danger_level` tinyint(4) NOT NULL DEFAULT 1 COMMENT '隐患等级(1:一般隐患;2:重大隐患;0:安全问题)',
`danger_position` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '隐患地点',
`longitude` varchar(30) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '隐患地址经度',
`latitude` varchar(30) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '隐患地址纬度',
`danger_type` tinyint(4) NOT NULL DEFAULT 1 COMMENT '隐患类型(1:无码无计划隐患;2:巡检隐患;3:有码无计划隐患;4:随手拍)',
`remark` text CHARACTER SET utf8 COLLATE utf8_general_ci NULL COMMENT '备注',
`overtime_state` tinyint(4) NOT NULL DEFAULT 0 COMMENT '是否逾期(0:否;1:是)',
`reform_type` tinyint(4) NULL DEFAULT NULL COMMENT '整改类型(1:常规整改;2:安措计划;3:延期治理)',
`reform_limit_date` datetime NULL DEFAULT NULL COMMENT '整改限制时间',
`reform_json` text CHARACTER SET utf8 COLLATE utf8_general_ci NULL COMMENT '整改对象',
`danger_state` tinyint(4) NOT NULL DEFAULT 1 COMMENT '隐患状态(1:待评审;2:待治理;3:安措计划中;4:待验证;5:治理完毕;6:已撤销;7:延期治理中;8:延期治理待车间部门审核;9:延期治理待公司审核',
`discoverer_user_id` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '发现人',
`discoverer_department_id` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '发现人部门编号',
`photo_urls` text CHARACTER SET utf8 COLLATE utf8_general_ci NULL COMMENT '图片',
`deleted` tinyint(4) NOT NULL DEFAULT 0 COMMENT '是否删除(0:否;1:是)',
`create_date` datetime NULL DEFAULT CURRENT_TIMESTAMP COMMENT '记录创建时间',
`update_date` datetime NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP COMMENT '记录修改时间',
`delay_limit_date` datetime NULL DEFAULT NULL COMMENT '延期治理时间',
`problem_description` varchar(500) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '问题描述',
`reason_analysis` varchar(500) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '原因分析',
`infer_other_things` varchar(500) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '举一反三',
`check_input_id` bigint(20) NULL DEFAULT NULL COMMENT '检查记录创建隐患对应check_input_id',
`structure_id` bigint(20) NULL DEFAULT NULL COMMENT '建筑ID',
`structure_name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '建筑名称',
`instance_key` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '流程实例key',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 321 CHARACTER SET = utf8 COLLATE = utf8_general_ci COMMENT = '隐患表' ROW_FORMAT = Dynamic;
SET FOREIGN_KEY_CHECKS = 1;
/*
Navicat Premium Data Transfer
Source Server : 172.16.6.60
Source Server Type : MySQL
Source Server Version : 50722
Source Host : 172.16.6.60:3306
Source Schema : amos-jcs-biz
Target Server Type : MySQL
Target Server Version : 50722
File Encoding : 65001
Date: 18/09/2021 11:18:58
*/
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for cb_latent_danger_flow_record
-- ----------------------------
DROP TABLE IF EXISTS `cb_latent_danger_flow_record`;
CREATE TABLE `cb_latent_danger_flow_record` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键自增',
`danger_id` bigint(20) NOT NULL COMMENT '隐患编号',
`action_flag` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '执行标志',
`flow_task_name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '当前节点名称',
`flow_task_user_ids` text CHARACTER SET utf8 COLLATE utf8_general_ci NULL COMMENT '当前节点可执行人(多个逗号分开)',
`flow_task_id` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '当前节点编号',
`excute_state` tinyint(4) NOT NULL DEFAULT 1 COMMENT '执行状态(1:未执行;2:通过;3:驳回)',
`excute_user_id` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '执行人',
`excute_department_id` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '执行部门编号',
`excute_result` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '执行结果',
`remark` text CHARACTER SET utf8 COLLATE utf8_general_ci NULL COMMENT '备注',
`flow_json` text CHARACTER SET utf8 COLLATE utf8_general_ci NULL COMMENT '上传数据',
`deleted` tinyint(4) NOT NULL DEFAULT 0 COMMENT '是否删除(0:否;1:是)',
`create_date` datetime NULL DEFAULT CURRENT_TIMESTAMP COMMENT '记录创建时间',
`update_date` datetime NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP COMMENT '记录修改时间',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 449 CHARACTER SET = utf8 COLLATE = utf8_general_ci COMMENT = '隐患工作流记录表' ROW_FORMAT = Dynamic;
SET FOREIGN_KEY_CHECKS = 1;
<?xml version="1.0" encoding="utf-8"?>
<databaseChangeLog
xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog
http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.4.xsd">
</databaseChangeLog>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<databaseChangeLog
xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog
http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-2.0.xsd">
<!-- 插入基础表结构 -->
<changeSet author="tb" id="2021-09-18-1">
<comment>init database structure</comment>
<sqlFile path="./init/create-latent-danger-table.sql" relativeToChangelogFile="true"/>
</changeSet>
</databaseChangeLog>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.yeejoin.amos.latentdanger.business.dao.mapper.LatentDangerFlowRecordMapper">
<insert id="save" keyColumn="id" keyProperty="id"
parameterType="com.yeejoin.amos.latentdanger.business.entity.mybatis.extend.LatentDangerFlowRecordBo"
useGeneratedKeys="true">
insert into cb_latent_danger_flow_record
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="dangerId != null">
danger_id,
</if>
<if test="actionFlag != null">
action_flag,
</if>
<if test="flowTaskName != null">
flow_task_name,
</if>
<if test="flowTaskUserIds != null">
flow_task_user_ids,
</if>
<if test="flowTaskId != null">
flow_task_id,
</if>
<if test="excuteState != null">
excute_state,
</if>
<if test="excuteUserId != null">
excute_user_id,
</if>
<if test="excuteDepartmentId != null">
excute_department_id,
</if>
<if test="excuteResult != null">
excute_result,
</if>
<if test="remark != null">
remark,
</if>
<if test="flowJson != null">
flow_json,
</if>
<if test="deleted != null">
deleted,
</if>
<if test="createDate != null">
create_date,
</if>
<if test="updateDate != null">
update_date,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="dangerId != null">
#{dangerId},
</if>
<if test="actionFlag != null">
#{actionFlag},
</if>
<if test="flowTaskName != null">
#{flowTaskName},
</if>
<if test="flowTaskUserIds != null">
#{flowTaskUserIds},
</if>
<if test="flowTaskId != null">
#{flowTaskId},
</if>
<if test="excuteState != null">
#{excuteState},
</if>
<if test="excuteUserId != null">
#{excuteUserId},
</if>
<if test="excuteDepartmentId != null">
#{excuteDepartmentId},
</if>
<if test="excuteResult != null">
#{excuteResult},
</if>
<if test="remark != null">
#{remark},
</if>
<if test="flowJson != null">
#{flowJson},
</if>
<if test="deleted != null">
#{deleted},
</if>
<if test="createDate != null">
#{createDate},
</if>
<if test="updateDate != null">
#{updateDate},
</if>
</trim>
</insert>
<update id="update" parameterType="com.yeejoin.amos.latentdanger.business.entity.mybatis.extend.LatentDangerFlowRecordBo">
update cb_latent_danger_flow_record
<set>
<if test="dangerId != null">
danger_id = #{dangerId},
</if>
<if test="actionFlag != null">
action_flag = #{actionFlag},
</if>
<if test="flowTaskName != null">
flow_task_name = #{flowTaskName},
</if>
<if test="flowTaskUserIds != null">
flow_task_user_ids = #{flowTaskUserIds},
</if>
<if test="flowTaskId != null">
flow_task_id = #{flowTaskId},
</if>
<if test="excuteState != null">
excute_state = #{excuteState},
</if>
<if test="excuteUserId != null">
excute_user_id = #{excuteUserId},
</if>
<if test="excuteDepartmentId != null">
excute_department_id = #{excuteDepartmentId},
</if>
<if test="excuteResult != null">
excute_result = #{excuteResult},
</if>
<if test="remark != null">
remark = #{remark},
</if>
<if test="flowJson != null">
flow_json = #{flowJson},
</if>
<if test="deleted != null">
deleted = #{deleted},
</if>
<if test="createDate != null">
create_date = #{createDate},
</if>
<if test="updateDate != null">
update_date = #{updateDate},
</if>
</set>
where id = #{id}
</update>
<select id="getById" resultType="com.yeejoin.amos.latentdanger.business.entity.mybatis.extend.LatentDangerFlowRecordBo">
select * from cb_latent_danger_flow_record where deleted = 0 and id = #{id} limit 1
</select>
<select id="getNewestRecordByDangerId" resultType="com.yeejoin.amos.latentdanger.business.entity.mybatis.extend.LatentDangerFlowRecordBo">
select * from cb_latent_danger_flow_record where deleted = 0 and danger_id = #{dangerId} order by create_date desc limit 1
</select>
<select id="listPassByDangerId" resultType="com.yeejoin.amos.latentdanger.business.entity.mybatis.extend.LatentDangerFlowRecordBo">
select
*
from
cb_latent_danger_flow_record
where
id in
(
select
max(id)
from
cb_latent_danger_flow_record
where
deleted = 0
and
danger_id = #{dangerId}
and
excute_state = 2
group by action_flag
)
</select>
<select id="listByDangerId" resultType="com.yeejoin.amos.latentdanger.business.entity.mybatis.extend.LatentDangerFlowRecordBo">
select
*
from
cb_latent_danger_flow_record
where
deleted = 0
and
danger_id = #{dangerId}
</select>
<select id="getByDangerIdAndActionFlag" resultType="com.yeejoin.amos.latentdanger.business.entity.mybatis.extend.LatentDangerFlowRecordBo">
select
*
from
cb_latent_danger_flow_record
where
danger_id = #{dangerId}
and
action_flag = #{actionFlag}
order by create_date desc
limit 1
</select>
<select id="getByDangerIdAndCreate" resultType="com.yeejoin.amos.latentdanger.business.entity.mybatis.extend.LatentDangerFlowRecordBo">
select
*
from
cb_latent_danger_flow_record
where
danger_id = #{dangerId}
order by create_date desc
limit 1
</select>
<select id="listNewestRecordByDangerIds" resultType="com.yeejoin.amos.latentdanger.business.entity.mybatis.extend.LatentDangerFlowRecordBo">
select
a.*,b.overtime_state as dangerOvertimeState,b.danger_state as dangerState
from
cb_latent_danger_flow_record as a
left join
cb_latent_danger as b on a.danger_id = b.id
where
a.id in
(
select
max(id)
from
cb_latent_danger_flow_record
where
deleted = 0
and
danger_id in
<foreach collection="list" item="item" index="index" open="(" separator="," close=")">
#{item}
</foreach>
and
excute_state in (2,3)
group by danger_id
)
</select>
<delete id="deleteByLatentDangerIds">
update cb_latent_danger_flow_record set deleted = 1 where danger_id in
<foreach collection="list" index="index" item="dangerId" open="(" separator="," close=")">
#{dangerId}
</foreach>
</delete>
<select id="listExecuteLog" resultType="com.yeejoin.amos.latentdanger.business.vo.DangerTimeAxisVo">
SELECT
pld.id AS dangerId,
pldfr.excute_user_id AS executeUserId,
pldfr.excute_result AS executeResult,
pld.create_date AS createDate,
pld.update_date AS updateDate,
pld.danger_name AS dangerName,
pld.danger_state AS dangerState,
pld.structure_id AS structureId,
pld.reform_limit_date AS reformLimitDate,
pld.reform_type AS reformType,
pld.delay_limit_date AS delayLimitDate
# wws.full_name AS structureName
FROM
cb_latent_danger pld
LEFT JOIN cb_latent_danger_flow_record pldfr ON pldfr.id = pld.current_flow_record_id
# LEFT JOIN wl_warehouse_structure wws ON wws.id = pld.structure_id
<!-- WHERE-->
<!-- <if test="beginTime != null and beginTime != ''">-->
<!-- pld.reform_limit_date <![CDATA[>=]]> #{beginTime}-->
<!-- </if>-->
ORDER BY
pld.update_date DESC
</select>
<select id="getByIdOderByDate"
resultType="com.yeejoin.amos.latentdanger.business.entity.mybatis.extend.LatentDangerFlowRecordBo">
select * from cb_latent_danger_flow_record where deleted = 0 and danger_id = #{dangerId} ORDER BY create_date DESC LIMIT 1
</select>
</mapper>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.yeejoin.amos.latentdanger.business.dao.mapper.LatentDangerMapper">
<insert id="save" keyColumn="id" keyProperty="id"
parameterType="com.yeejoin.amos.latentdanger.business.entity.mybatis.extend.LatentDangerBo"
useGeneratedKeys="true">
insert into cb_latent_danger
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="businessKey != null">
business_key,
</if>
<if test="orgCode != null">
org_code,
</if>
<if test="dangerName != null">
danger_name,
</if>
<if test="currentFlowRecordId != null">
current_flow_record_id,
</if>
<if test="instanceId != null">
instance_id,
</if>
<if test="dangerLevel != null">
danger_level,
</if>
<if test="dangerPosition != null">
danger_position,
</if>
<if test="dangerType != null">
danger_type,
</if>
<if test="remark != null">
remark,
</if>
<if test="overtimeState != null">
overtime_state,
</if>
<if test="reformType != null">
reform_type,
</if>
<if test="reformLimitDate != null">
reform_limit_date,
</if>
<if test="reformJson != null">
reform_json,
</if>
<if test="dangerState != null">
danger_state,
</if>
<if test="discovererUserId != null">
discoverer_user_id,
</if>
<if test="discovererDepartmentId != null">
discoverer_department_id,
</if>
<if test="photoUrls != null">
photo_urls,
</if>
<if test="deleted != null">
deleted,
</if>
<if test="createDate != null">
create_date,
</if>
<if test="updateDate != null">
update_date,
</if>
<if test="problemDescription != null">
problem_description,
</if>
<if test="checkInputId != null">
check_input_id,
</if>
<if test="structureId != null">
structure_id,
</if>
<if test="structureName != null">
structure_name,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="businessKey != null">
#{businessKey},
</if>
<if test="orgCode != null">
#{orgCode},
</if>
<if test="dangerName != null">
#{dangerName},
</if>
<if test="currentFlowRecordId != null">
#{currentFlowRecordId},
</if>
<if test="instanceId != null">
#{instanceId},
</if>
<if test="dangerLevel != null">
#{dangerLevel},
</if>
<if test="dangerPosition != null">
#{dangerPosition},
</if>
<if test="dangerType != null">
#{dangerType},
</if>
<if test="remark != null">
#{remark},
</if>
<if test="overtimeState != null">
#{overtimeState},
</if>
<if test="reformType != null">
#{reformType},
</if>
<if test="reformLimitDate != null">
#{reformLimitDate},
</if>
<if test="reformJson != null">
#{reformJson},
</if>
<if test="dangerState != null">
#{dangerState},
</if>
<if test="discovererUserId != null">
#{discovererUserId},
</if>
<if test="discovererDepartmentId != null">
#{discovererDepartmentId},
</if>
<if test="photoUrls != null">
#{photoUrls},
</if>
<if test="deleted != null">
#{deleted},
</if>
<if test="createDate != null">
#{createDate},
</if>
<if test="updateDate != null">
#{updateDate},
</if>
<if test="problemDescription != null">
#{problemDescription},
</if>
<if test="checkInputId != null">
#{checkInputId},
</if>
<if test="structureId != null">
#{structureId},
</if>
<if test="structureName != null">
#{structureName},
</if>
</trim>
</insert>
<update id="update" parameterType="com.yeejoin.amos.latentdanger.business.entity.mybatis.extend.LatentDangerBo">
update cb_latent_danger
<set>
<if test="businessKey != null">
business_key = #{businessKey},
</if>
<if test="orgCode != null">
org_code = #{orgCode},
</if>
<if test="dangerName != null">
danger_name = #{dangerName},
</if>
<if test="currentFlowRecordId != null">
current_flow_record_id = #{currentFlowRecordId},
</if>
<if test="instanceId != null">
instance_id = #{instanceId},
</if>
<if test="dangerLevel != null">
danger_level = #{dangerLevel},
</if>
<if test="dangerPosition != null">
danger_position = #{dangerPosition},
</if>
<if test="dangerType != null">
danger_type = #{dangerType},
</if>
<if test="remark != null">
remark = #{remark},
</if>
<if test="overtimeState != null">
overtime_state = #{overtimeState},
</if>
<if test="currentFlowRecordId != null">
current_flow_record_id = #{currentFlowRecordId},
</if>
<if test="reformType != null">
reform_type = #{reformType},
</if>
<if test="reformLimitDate != null">
reform_limit_date = #{reformLimitDate},
</if>
<if test="reformJson != null">
reform_json = #{reformJson},
</if>
<if test="dangerState != null">
danger_state = #{dangerState},
</if>
<if test="discovererUserId != null">
discoverer_user_id = #{discovererUserId},
</if>
<if test="discovererDepartmentId != null">
discoverer_department_id = #{discovererDepartmentId},
</if>
<if test="photoUrls != null">
photo_urls = #{photoUrls},
</if>
<if test="deleted != null">
deleted = #{deleted},
</if>
<if test="createDate != null">
create_date = #{createDate},
</if>
<if test="updateDate != null">
update_date = #{updateDate},
</if>
<if test="delayLimitDate != null">
delay_limit_date = #{delayLimitDate},
</if>
<if test="reasonAnalysis != null">
reason_analysis = #{reasonAnalysis},
</if>
<if test="inferOtherThings != null">
infer_other_things = #{inferOtherThings},
</if>
<if test="problemDescription != null">
problem_description = #{problemDescription},
</if>
</set>
where id = #{id}
</update>
<update id="deleteByIds">
update cb_latent_danger set deleted = 1 where id in
<foreach collection="list" index="index" item="id" open="(" separator="," close=")">
#{id}
</foreach>
</update>
<select id="getById" resultType="com.yeejoin.amos.latentdanger.business.entity.mybatis.extend.LatentDangerBo">
select * from cb_latent_danger where deleted = 0 and id = #{id}
</select>
<select id="getByInstanceId" resultType="com.yeejoin.amos.latentdanger.business.entity.mybatis.extend.LatentDangerBo">
select * from cb_latent_danger where deleted = 0 and instance_id = #{instanceId} and danger_state = 3 limit 1
</select>
<select id="listByMap" resultType="com.yeejoin.amos.latentdanger.business.entity.mybatis.extend.LatentDangerBo">
select
a.*
from
cb_latent_danger as a
left join
cb_latent_danger_flow_record as b on a.current_flow_record_id = b.id
<where>
<!-- case-->
<!-- when a.danger_type = 1 and find_in_set(b.action_flag, 'B_3,B_4') then-->
<!-- 1=1-->
<!-- <if test="userId != null and userId != ''">-->
<!-- and find_in_set( #{userId}, b.flow_task_user_ids )-->
<!-- </if>-->
<!-- else-->
<!-- 1=1-->
<!-- <if test="userId != null and userId != ''">-->
<!-- and (find_in_set(#{userId}, b.flow_task_user_ids) or find_in_set(b.action_flag, #{permissions}))-->
<!-- </if>-->
<!-- end-->
<!-- and a.deleted = 0-->
<!-- and b.deleted = 0-->
<if test="dangerLevel != null and dangerLevel != -1">
and a.danger_level=#{dangerLevel}
</if>
<if test="dangerState != null and dangerState != ''">
and a.danger_state=#{dangerState}
</if>
<if test="states != null">
and a.danger_state in
<foreach collection="states" item="item" index="index" open="(" separator="," close=")">
#{item}
</foreach>
</if>
<if test="dangerName != null and dangerName != ''">
and a.danger_name like concat('%',#{dangerName},'%')
</if>
<if test="org_code != null and org_code != ''">
and a.org_code = #{org_code}
</if>
<!-- <if test="discoverer_department_id != null and discoverer_department_id != ''">-->
<!-- and (a.discoverer_department_id = #{discoverer_department_id} or ISNULL(a.discoverer_department_id))-->
<!-- </if>-->
</where>
order by a.create_date desc
<if test="limit != null and offset != null">
limit #{offset},#{limit}
</if>
</select>
<select id="countByMap" resultType="java.lang.Long">
select
count(1)
from
cb_latent_danger as a
left join
cb_latent_danger_flow_record as b on a.current_flow_record_id = b.id
<where>
case
when a.danger_type = 1 and find_in_set(b.action_flag, 'B_3,B_4') then
1=1
<if test="userId != null and userId != ''">
and find_in_set( #{userId}, b.flow_task_user_ids )
</if>
else
1=1
<if test="userId != null and userId != ''">
and (find_in_set(#{userId}, b.flow_task_user_ids) or find_in_set(b.action_flag, #{permissions}))
</if>
end
and a.deleted = 0
and b.deleted = 0
<if test="dangerLevel != null and dangerLevel != -1">
and a.danger_level=#{dangerLevel}
</if>
<if test="dangerState != null and dangerState != ''">
and a.danger_state=#{dangerState}
</if>
<if test="states != null">
and a.danger_state in
<foreach collection="states" item="item" index="index" open="(" separator="," close=")">
#{item}
</foreach>
</if>
<if test="dangerName != null and dangerName != ''">
and a.danger_name like concat('%',#{dangerName},'%')
</if>
<if test="org_code != null and org_code != ''">
and a.org_code = #{org_code}
</if>
<if test="discoverer_department_id != null and discoverer_department_id != ''">
and (a.discoverer_department_id = #{discoverer_department_id} or ISNULL(a.discoverer_department_id))
</if>
</where>
</select>
<select id="listOfOvertime" resultType="com.yeejoin.amos.latentdanger.business.entity.mybatis.extend.LatentDangerBo">
select * from cb_latent_danger where now()>reform_limit_date and overtime_state = 0 and deleted = 0 and danger_state in (2,3,4)
</select>
<select id="countNotFinishByFlowId" resultType="java.lang.Integer">
select
count(1)
from
cb_latent_danger
where
deleted = 0
and
danger_state in (1,2,3,4)
and
id in
(
select
latent_danger_id
from
cb_latent_danger_patrol
where
risk_factor_flow_id = #{value}
and
deleted = 0
)
</select>
<select id="listNotFinishByPointId" resultType="com.yeejoin.amos.latentdanger.business.entity.mybatis.extend.LatentDangerBo">
select
*
from
cb_latent_danger
where
deleted = 0
and
danger_state in (1,2,3,4)
and
id in
(
select
latent_danger_id
from
cb_latent_danger_patrol
where
point_id = #{pointId}
and
deleted = 0
)
and id !=#{dangerId}
</select>
<select id="countByFlowUserIds" resultType="java.lang.Long">
select
count(1)
from
cb_latent_danger as a
left join
cb_latent_danger_flow_record as b on a.current_flow_record_id = b.id
where
find_in_set(#{userId},b.flow_task_user_ids)
and
a.deleted = 0
and
a.danger_state in (1,2,4)
</select>
<select id="countNotFinishByTypeAndDeptId" resultType="java.lang.Long">
SELECT
count(1)
FROM
cb_latent_danger a,
cb_latent_danger_patrol b,
p_point c,
spc_risk_source d
WHERE
a.danger_level = #{type}
<if test="departmentId != null and departmentId != -1">
and d.belong_department_id = #{departmentId}
</if>
and a.danger_type IN (2, 3)
AND (
a.danger_state IN (2, 3, 4)
OR a.danger_state = 5
AND DATEDIFF(a.update_date, CURDATE()) = 0
)
and b.latent_danger_id = a.id
and b.point_id = c.id
and c.original_id = d.id
</select>
<select id="getNotFinishIdsByTypeAndDeptId" resultType="java.lang.String">
SELECT
GROUP_CONCAT(DISTINCT a.id ) extraIds
FROM
cb_latent_danger a,
cb_latent_danger_patrol b,
p_point c,
spc_risk_source d
WHERE
a.danger_level = #{type} -- (1,2)
<if test="departmentId != null and departmentId != -1">
and d.belong_department_id = #{departmentId}
</if>
AND a.danger_type IN ( 2, 3 ) -- 2:巡检隐患;3:有码无计划隐患
AND (
a.danger_state IN ( 2, 3, 4 ) -- 2:待治理;3:安措计划中;4:待验证;5:治理完毕
OR a.danger_state = 5
AND DATEDIFF( a.update_date, CURDATE( ) ) = 0
)
AND b.latent_danger_id = a.id
AND b.point_id = c.id
AND c.original_id = d.id;
</select>
<select id="listNeedNoticeDanger"
resultType="com.yeejoin.amos.latentdanger.business.entity.mybatis.extend.LatentDangerNoticeBo">
SELECT
ld.id dangerId,
ld.org_code orgCode,
ld.danger_state dangerState,
ld.danger_name dangerName,
ld.instance_id instanceId,
ld.reform_limit_date reformLimitDate
FROM
cb_latent_danger ld
WHERE
TIMESTAMPDIFF( MINUTE, now(), ld.reform_limit_date ) = TIMESTAMPDIFF( MINUTE, (SELECT DATE_ADD(CURDATE(),
INTERVAL 8 HOUR)), ld.reform_limit_date ) -- 截止日期到当天早上8:00:00分钟数
AND ld.overtime_state = 0
AND ld.deleted = 0
AND ld.danger_state = 2;
</select>
<select id="getReViewInfo" resultType="java.util.HashMap">
SELECT
f.id,
f.danger_id dangerId,
f.action_flag actionFlag,
f.flow_task_name flowTaskName,
CASE
WHEN f.excute_state = 2 THEN
'通过'
WHEN f.excute_state = 3 THEN
'驳回'
END executeState,
f.excute_user_id executeUserId,
f.update_date reViewDate,
ld.reform_limit_date reformLimitDate,
f.flow_json flowJson,
f.remark,
ld.infer_other_things inferOtherThings,
(select ff.flow_task_user_ids from cb_latent_danger_flow_record ff where ff.danger_id = f.danger_id and
ff.action_flag = 'B_3' limit 1 ) handleUserIds,
CASE
WHEN ld.reform_type = 1 THEN
'常规整改'
WHEN ld.reform_type = 2 THEN
'安措计划'
WHEN ld.reform_type = 3 THEN
'延期治理'
END reformTypeName,
ld.reform_type reformType,
ld.delay_limit_date delayLimitDate
FROM
cb_latent_danger_flow_record f
LEFT JOIN cb_latent_danger ld ON ld.id = f.danger_id
WHERE
f.action_flag != 'B_1'
AND NOT ISNULL( f.update_date )
AND f.excute_state != 1
AND f.danger_id = #{dangerId}
</select>
<select id="dangerListByMap" resultType="com.yeejoin.amos.latentdanger.core.common.response.DangerListResponse">
SELECT
*
FROM
(
SELECT
pld.id,
pld.danger_name dangerName,
pld.danger_position dangerPosition,
pld.danger_level dangerLevel,
pld.reform_type reformType,
pld.reform_limit_date deadlineDate,
pld.danger_state dangerState,
pld.overtime_state overtimeState,
pld.problem_description problemDescription,
pld.reason_analysis reasonAnalysis,
pld.infer_other_things inferOtherThings,
pld.remark,
pp.plan_type planType,
pp.`name` planName,
pr.`name` routeName,
pld.danger_type dangerType,
pc.check_time checkTimeDate,
pii.`name` checkContent,
pc.user_id checkUser,
pc.error checkResult,
pc.is_ok checkStatus,
pld.id dangerId,
pld.reform_json measures,
pld.instance_id processInstanceId,
pld.discoverer_user_id discoverUser,
p.original_id riskSourceId,
pld.structure_id structureId,
pld.structure_name structureName
FROM
cb_latent_danger pld
LEFT JOIN cb_latent_danger_patrol ldp ON pld.id = ldp.latent_danger_id
LEFT JOIN p_point p ON p.id = ldp.point_id
LEFT JOIN p_point_classify ppc ON ppc.id = ldp.point_classify_id
LEFT JOIN p_input_item pii ON pii.id = ldp.item_id
LEFT JOIN p_check pc ON pc.id = ldp.check_id
LEFT JOIN p_plan pp ON pp.id = pc.plan_id
LEFT JOIN p_route pr ON pr.id = pc.route_id
<where>
<if test="dangerIds != null">
pld.id IN
<foreach collection="dangerIds" item="id" index="index" open="(" separator="," close=")" >
#{id}
</foreach>
</if>
</where>
) temp
WHERE
1 = 1
<if test="type != null and type !=''">
AND type = #{type}
</if>
<if test="eqCode != null and eqCode !=''">
AND eqCode LIKE concat('%',#{eqCode},'%')
</if>
<if test="dangerName != null and dangerName !=''">
AND dangerName LIKE concat('%',#{dangerName},'%')
</if>
<if test="planType != null and planType !=''">
AND planType = #{planType}
</if>
<if test="structureId != null and structureId.size > 0">
AND structureId in
<foreach collection="structureId" open="(" close=")" separator="," item="sid">
#{sid}
</foreach>
</if>
<if test="routeName != null and routeName !=''">
AND routeName LIKE concat('%',#{routeName},'%')
</if>
<if test="planName != null and planName !=''">
AND planName LIKE concat('%',#{planName},'%')
</if>
<if test="beginCheckTime != null and beginCheckTime !=''">
AND checkTimeDate <![CDATA[>=]]> #{beginCheckTime}
</if>
<if test="endCheckTime != null and endCheckTime !=''">
AND checkTimeDate <![CDATA[<=]]> #{endCheckTime}
</if>
<if test="checkDep != null and checkDep !=''">
AND checkDep = #{checkDep}
</if>
<if test="checkUser != null and checkUser !=''">
AND checkUser = #{checkUser}
</if>
<if test="checkResult != null and checkResult !=''">
AND checkResult LIKE concat('%',#{checkResult},'%')
</if>
<if test="beginDeadline != null and beginDeadline !=''">
AND deadlineDate <![CDATA[>=]]> #{beginDeadline}
</if>
<if test="endDeadline != null and endDeadline !=''">
AND deadlineDate <![CDATA[<=]]> #{endDeadline}
</if>
<if test="governDep != null and governDep !=''">
AND governDep = #{governDep}
</if>
<if test="governUser != null and governUser !=''">
AND governUser = #{governUser}
</if>
<if test="dangerLevel != null and dangerLevel !=''">
AND dangerLevel = #{dangerLevel}
</if>
<if test="dangerType != null and dangerType !=''">
AND dangerType = #{dangerType}
</if>
<if test="reformType != null and reformType !=''">
AND reformType = #{reformType}
</if>
<if test="overtimeState != null and overtimeState !=''">
AND overtimeState = #{overtimeState}
</if>
<if test="dangerState != null and dangerState !=''">
AND dangerState = #{dangerState}
</if>
<if test="verifyDep != null and verifyDep !=''">
AND verifyDep = #{verifyDep}
</if>
<if test="verifyUser != null and verifyUser !=''">
AND verifyUser = #{verifyUser}
</if>
<if test="riskSourceId != null and riskSourceId !=''">
AND riskSourceId = #{riskSourceId}
</if>
ORDER BY temp.id desc
<if test="offset != null and pageSize != null">
limit #{offset},#{pageSize}
</if>
</select>
<select id="countDangerListByMap" resultType="java.lang.Long">
SELECT
COUNT(1)
FROM
(
SELECT
pld.danger_name dangerName,
pld.danger_position dangerPosition,
pld.structure_name structureName,
pld.structure_id structureId,
pld.danger_level dangerLevel,
pld.reform_type reformType,
pld.reform_limit_date deadlineDate,
pld.danger_state dangerState,
pld.overtime_state overtimeState,
pp.plan_type planType,
pp.`name` planName,
pr.`name` routeName,
pld.danger_type dangerType,
pc.check_time checkTimeDate,
pii.`name` checkContent,
pc.user_id checkUser,
pc.error checkResult,
pc.is_ok checkStatus,
pld.id dangerId,
dangerFlow.governDep,
dangerFlow.governUser,
dangerFlow.governDate,
dangerFlow.verifyDep,
dangerFlow.verifyUser,
dangerFlow.verifyResult,
pld.reform_json measures
FROM
cb_latent_danger pld
LEFT JOIN cb_latent_danger_patrol ldp ON pld.id = ldp.latent_danger_id
LEFT JOIN p_point_classify ppc ON ppc.id = ldp.point_classify_id
LEFT JOIN p_input_item pii ON pii.id = ldp.item_id
LEFT JOIN p_check pc ON pc.id = ldp.check_id
LEFT JOIN p_plan pp ON pp.id = pc.plan_id
LEFT JOIN p_route pr ON pr.id = pc.route_id
LEFT JOIN (
SELECT
GROUP_CONCAT(
CASE
WHEN action_flag = 'B_3' THEN
excute_department_id
ELSE
NULL
END
) governDep,
GROUP_CONCAT(
CASE
WHEN action_flag = 'B_3' THEN
excute_user_id
ELSE
NULL
END
) governUser,
GROUP_CONCAT(
CASE
WHEN action_flag = 'B_3' THEN
update_date
ELSE
NULL
END
) governDate,
GROUP_CONCAT(
CASE
WHEN action_flag = 'B_4' THEN
excute_department_id
ELSE
NULL
END
) verifyDep,
GROUP_CONCAT(
CASE
WHEN action_flag = 'B_4' THEN
excute_user_id
ELSE
NULL
END
) verifyUser,
GROUP_CONCAT(
CASE
WHEN action_flag = 'B_4' THEN
pldfr.excute_result
ELSE
NULL
END
) verifyResult,
pldfr.danger_id dangerId
FROM
(
SELECT
*
FROM
cb_latent_danger_flow_record
WHERE
id IN (
SELECT
max(id)
FROM
cb_latent_danger_flow_record
WHERE
deleted = 0
AND action_flag IN ('B_3', 'B_4')
GROUP BY
action_flag,
danger_id
)
) pldfr
GROUP BY
pldfr.danger_id
) dangerFlow ON dangerFlow.dangerId = pld.id
<where>
<if test="dangerIds != null">
pld.id IN
<foreach collection="dangerIds" item="id" index="index" open="(" separator="," close=")" >
#{id}
</foreach>
</if>
</where>
) temp
WHERE
1 = 1
<if test="type != null and type !=''">
AND type = #{type}
</if>
<if test="eqCode != null and eqCode !=''">
AND eqCode LIKE concat('%',#{eqCode},'%')
</if>
<if test="dangerName != null and dangerName !=''">
AND dangerName LIKE concat('%',#{dangerName},'%')
</if>
<if test="planType != null and planType !=''">
AND planType = #{planType}
</if>
<if test="structureId != null and structureId.size > 0">
AND structureId in
<foreach collection="structureId" open="(" close=")" separator="," item="sid">
#{sid}
</foreach>
</if>
<if test="routeName != null and routeName !=''">
AND routeName LIKE concat('%',#{routeName},'%')
</if>
<if test="planName != null and planName !=''">
AND planName LIKE concat('%',#{planName},'%')
</if>
<if test="beginCheckTime != null and beginCheckTime !=''">
AND checkTimeDate <![CDATA[>=]]> #{beginCheckTime}
</if>
<if test="endCheckTime != null and endCheckTime !=''">
AND checkTimeDate <![CDATA[<=]]> #{endCheckTime}
</if>
<if test="checkDep != null and checkDep !=''">
AND checkDep = #{checkDep}
</if>
<if test="checkUser != null and checkUser !=''">
AND checkUser = #{checkUser}
</if>
<if test="checkResult != null and checkResult !=''">
AND checkResult LIKE concat('%',#{checkResult},'%')
</if>
<if test="beginDeadline != null and beginDeadline !=''">
AND deadlineDate <![CDATA[>=]]> #{beginDeadline}
</if>
<if test="endDeadline != null and endDeadline !=''">
AND deadlineDate <![CDATA[<=]]> #{endDeadline}
</if>
<if test="governDep != null and governDep !=''">
AND governDep = #{governDep}
</if>
<if test="governUser != null and governUser !=''">
AND governUser = #{governUser}
</if>
<if test="dangerLevel != null and dangerLevel !=''">
AND dangerLevel = #{dangerLevel}
</if>
<if test="dangerType != null and dangerType !=''">
AND dangerType = #{dangerType}
</if>
<if test="reformType != null and reformType !=''">
AND reformType = #{reformType}
</if>
<if test="overtimeState != null and overtimeState !=''">
AND overtimeState = #{overtimeState}
</if>
<if test="dangerState != null and dangerState !=''">
AND dangerState = #{dangerState}
</if>
<if test="verifyDep != null and verifyDep !=''">
AND verifyDep = #{verifyDep}
</if>
<if test="verifyUser != null and verifyUser !=''">
AND verifyUser = #{verifyUser}
</if>
<if test="riskSourceId != null and riskSourceId !=''">
AND riskSourceId = #{riskSourceId}
</if>
</select>
<select id="getByBathBusinessKeys" resultType="com.yeejoin.amos.latentdanger.business.entity.mybatis.extend.LatentDangerBo">
SELECT
*
FROM
cb_latent_danger pld
WHERE
pld.business_key IN
<foreach collection = "businessKeys" item = "businessKey" index="index" open = "(" close = ")" separator = "," >
#{businessKey}
</foreach>
<if test="latentDangerListParam.dangerLevel != null and latentDangerListParam.dangerLevel != -1">
and pld.danger_level=#{latentDangerListParam.dangerLevel}
</if>
<if test="latentDangerListParam.dangerState != null and latentDangerListParam.dangerState != ''">
and pld.danger_state=#{latentDangerListParam.dangerState}
</if>
<if test="latentDangerListParam.userId != null and latentDangerListParam.userId != ''">
and pld.discoverer_user_id=#{latentDangerListParam.userId}
</if>
<if test="latentDangerListParam.dangerName != null and latentDangerListParam.dangerName !=''">
AND pld.danger_name LIKE concat('%',#{latentDangerListParam.dangerName},'%')
</if>
ORDER BY create_date DESC
<if test="latentDangerListParam.pageSize != null and latentDangerListParam.offset != null">
limit #{latentDangerListParam.offset}, #{latentDangerListParam.pageSize}
</if>
</select>
<select id="countByBathBusinessKeys" resultType="java.lang.Integer">
SELECT
count(*)
FROM
cb_latent_danger pld
WHERE
pld.business_key IN
<foreach collection = "businessKeys" item = "businessKey" index="index" open = "(" close = ")" separator = "," >
#{businessKey}
</foreach>
<if test="latentDangerListParam.dangerLevel != null and latentDangerListParam.dangerLevel != -1">
and pld.danger_level=#{latentDangerListParam.dangerLevel}
</if>
<if test="latentDangerListParam.dangerState != null and latentDangerListParam.dangerState != ''">
and pld.danger_state=#{latentDangerListParam.dangerState}
</if>
<if test="latentDangerListParam.userId != null and latentDangerListParam.userId != ''">
and pld.discoverer_user_id=#{latentDangerListParam.userId}
</if>
<if test="latentDangerListParam.dangerName != null and latentDangerListParam.dangerName !=''">
AND pld.danger_name LIKE concat('%',#{latentDangerListParam.dangerName},'%')
</if>
</select>
<select id="countByStatus" resultType="java.lang.Integer">
SELECT
count(*)
FROM
cb_latent_danger pld
WHERE
pld.deleted = 0
AND
pld.danger_state in (1,2,4,7,8,9)
AND
pld.business_key IN
<foreach collection = "businessKeys" item = "businessKey" index="index" open = "(" close = ")" separator = "," >
#{businessKey}
</foreach>
</select>
<update id="updateCheckInputDangerState">
update
p_check_input
set danger_handle_state = #{code}
where id = #{id};
</update>
<select id="getbyBusinessKey" resultType="com.yeejoin.amos.latentdanger.business.entity.mybatis.extend.LatentDangerBo">
SELECT
*
FROM
cb_latent_danger pld
WHERE
pld.business_key = #{businessKey}
</select>
</mapper>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.yeejoin.amos.latentdanger.business.dao.mapper.LatentDangerPatrolMapper">
<insert id="save" keyColumn="id" keyProperty="id"
parameterType="com.yeejoin.amos.latentdanger.business.entity.mybatis.extend.LatentDangerPatrolBo"
useGeneratedKeys="true">
insert into p_latent_danger_patrol
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="latentDangerId != null">
latent_danger_id,
</if>
<if test="pointClassifyId != null">
point_classify_id,
</if>
<!-- <if test="riskFactorFlowId != null">-->
<!-- risk_factor_flow_id,-->
<!-- </if>-->
<if test="checkId != null">
check_id,
</if>
<if test="itemId != null">
item_id,
</if>
<if test="pointId != null">
point_id,
</if>
<if test="routeId != null">
route_id,
</if>
<if test="routePointItemId != null">
route_point_item_id,
</if>
<if test="deleted != null">
deleted,
</if>
<if test="createDate != null">
create_date,
</if>
<if test="updateDate != null">
update_date,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="latentDangerId != null">
#{latentDangerId},
</if>
<if test="pointClassifyId != null">
#{pointClassifyId},
</if>
<!-- <if test="riskFactorFlowId != null">-->
<!-- #{riskFactorFlowId},-->
<!-- </if>-->
<if test="checkId != null">
#{checkId},
</if>
<if test="itemId != null">
#{itemId},
</if>
<if test="pointId != null">
#{pointId},
</if>
<if test="routeId != null">
#{routeId},
</if>
<if test="routePointItemId != null">
#{routePointItemId},
</if>
<if test="deleted != null">
#{deleted},
</if>
<if test="createDate != null">
#{createDate},
</if>
<if test="updateDate != null">
#{updateDate},
</if>
</trim>
</insert>
<update id="update" parameterType="com.yeejoin.amos.latentdanger.business.entity.mybatis.extend.LatentDangerPatrolBo">
update p_latent_danger_patrol
<set>
<if test="latentDangerId != null">
latent_danger_id = #{latentDangerId},
</if>
<if test="pointClassifyId != null">
point_classify_id = #{pointClassifyId},
</if>
<if test="checkId != null">
check_id = #{checkId},
</if>
<if test="riskFactorFlowId != null">
risk_factor_flow_id = #{riskFactorFlowId},
</if>
<if test="itemId != null">
item_id = #{itemId},
</if>
<if test="pointId != null">
point_id = #{pointId},
</if>
<if test="routeId != null">
route_id = #{routeId},
</if>
<if test="routePointItemId != null">
route_point_item_id = #{routePointItemId},
</if>
<if test="deleted != null">
deleted = #{deleted},
</if>
<if test="createDate != null">
create_date = #{createDate},
</if>
<if test="updateDate != null">
update_date = #{updateDate},
</if>
</set>
where id = #{id}
</update>
<delete id="deleteByLatentDangerIds">
update p_latent_danger_patrol set deleted = 1 where latent_danger_id in
<foreach collection="list" index="index" item="latentDangerId" open="(" separator="," close=")">
#{latentDangerId}
</foreach>
</delete>
<select id="getByDangerId" resultType="com.yeejoin.amos.latentdanger.business.entity.mybatis.extend.LatentDangerPatrolBo">
select
a.*,
b.name as itemName,
b.original_id as itemOriginalId,
b.basis_json as itemBasis,
b.remark as itemRemark,
c.name as pointName,
c.point_no as pointNo,
c.level as pointLevel,
c.charge_dept_id as pointDepartMentId,
c.original_id as pointOriginalId,
d.name as routeName,
e.check_time as checkTime,
e.user_id as checkUserId,
e.dep_id as checkDepartmentId,
f.name as planName,
f.plan_type as planType,
f.execute_rate as executeRate,
g.original_id as classifyOriginalId,
g.name as classifyName
from
p_latent_danger_patrol as a
left join
p_input_item as b on a.item_id = b.id
left join
p_point as c on a.point_id = c.id
left join
p_route as d on a.route_id = d.id
left join
p_check as e on a.check_id = e.id
left join
p_plan as f on e.plan_id = f.id
left join
p_point_classify as g on a.point_classify_id = g.id
where
a.deleted = 0
and
a.latent_danger_id = #{dangerId}
</select>
<select id="listByMap" resultType="com.yeejoin.amos.latentdanger.business.entity.mybatis.extend.LatentDangerPatrolBo">
select
a.*
from
p_latent_danger_patrol as a
left join
p_latent_danger as b
<where>
<if test="pointId != null">
and a.point_id = #{pointId}
</if>
<if test="itemId != null">
and a.item_id = #{itemId}
</if>
<if test="pointClassifyId != null">
and a.point_classify_id = #{pointClassifyId}
</if>
<if test="dangerType != null">
and b.danger_type = #{dangerType}
</if>
</where>
</select>
<select id="listByPointId" resultType="com.yeejoin.amos.latentdanger.business.entity.mybatis.extend.LatentDangerPatrolBo">
select
*
from
p_latent_danger_patrol
where
point_id = #{pointId}
</select>
<select id="queryByPointClassifyIds"
resultType="com.yeejoin.amos.latentdanger.business.entity.mybatis.extend.LatentDangerPatrolBo">
select * from p_latent_danger_patrol where point_classify_id in
<foreach collection="list" index="index" item="pointClassifyId" open="(" separator="," close=")">
#{pointClassifyId}
</foreach>
</select>
</mapper>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<configuration debug="false">
<!--定义日志文件的存储地址 勿在 LogBack 的配置中使用相对路径-->
<property name="LOG_HOME" value="log" />
<!-- 按照每天生成日志文件 -->
<appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<!--日志文件输出的文件名-->
<FileNamePattern>${LOG_HOME}/patrol.log.%d{yyyy-MM-dd}.%i.log</FileNamePattern>
<!--日志文件保留天数-->
<MaxHistory>30</MaxHistory>
<!--日志文件大小-->
<MaxFileSize>30mb</MaxFileSize>
</rollingPolicy>
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<!--格式化输出:%d表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度%msg:日志消息,%n是换行符-->
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
</encoder>
</appender>
<!-- 控制台输出 -->
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<!--格式化输出:%d表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度%msg:日志消息,%n是换行符-->
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
</encoder>
</appender>
<!-- show parameters for hibernate sql 专为 Hibernate 定制
<logger name="org.hibernate.type.descriptor.sql.BasicBinder" level="TRACE" />
<logger name="org.hibernate.type.descriptor.sql.BasicExtractor" level="DEBUG" />
<logger name="org.hibernate.SQL" level="DEBUG" />
<logger name="org.hibernate.engine.QueryParameters" level="DEBUG" />
<logger name="org.hibernate.engine.query.HQLQueryPlan" level="DEBUG" />
-->
<!--myibatis log configure-->
<logger name="com.apache.ibatis" level="DEBUG"/>
<logger name="org.mybatis" level="DEBUG" />
<logger name="java.sql.Connection" level="DEBUG"/>
<logger name="java.sql.Statement" level="DEBUG"/>
<logger name="java.sql.PreparedStatement" level="DEBUG"/>
<logger name="org.springframework" level="DEBUG"/>
<!-- 日志输出级别 -->
<root level="DEBUG">
<appender-ref ref="FILE" />
<appender-ref ref="STDOUT" />
</root>
</configuration>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<configuration debug="false">
<!--定义日志文件的存储地址 勿在 LogBack 的配置中使用相对路径-->
<property name="LOG_HOME" value="log" />
<!-- 按照每天生成日志文件 -->
<appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<!--日志文件输出的文件名-->
<FileNamePattern>${LOG_HOME}/patrol.log.%d{yyyy-MM-dd}.%i.log</FileNamePattern>
<!--日志文件保留天数-->
<MaxHistory>30</MaxHistory>
<!--日志文件大小-->
<MaxFileSize>30mb</MaxFileSize>
</rollingPolicy>
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<!--格式化输出:%d表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度%msg:日志消息,%n是换行符-->
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
</encoder>
</appender>
<!-- 控制台输出 -->
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<!--格式化输出:%d表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度%msg:日志消息,%n是换行符-->
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
</encoder>
</appender>
<!-- show parameters for hibernate sql 专为 Hibernate 定制
<logger name="org.hibernate.type.descriptor.sql.BasicBinder" level="TRACE" />
<logger name="org.hibernate.type.descriptor.sql.BasicExtractor" level="DEBUG" />
<logger name="org.hibernate.SQL" level="DEBUG" />
<logger name="org.hibernate.engine.QueryParameters" level="DEBUG" />
<logger name="org.hibernate.engine.query.HQLQueryPlan" level="DEBUG" />
-->
<!--myibatis log configure-->
<logger name="com.apache.ibatis" level="DEBUG"/>
<logger name="org.mybatis" level="DEBUG" />
<logger name="java.sql.Connection" level="DEBUG"/>
<logger name="java.sql.Statement" level="DEBUG"/>
<logger name="java.sql.PreparedStatement" level="DEBUG"/>
<logger name="org.springframework" level="DEBUG"/>
<!-- 日志输出级别 -->
<root level="DEBUG">
<appender-ref ref="FILE" />
<appender-ref ref="STDOUT" />
</root>
</configuration>
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment