Commit 91738d0d authored by 韩桐桐's avatar 韩桐桐

feat(ys):验收服务初始化

parent 0c7c3e1b
<?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">
<parent>
<artifactId>amos-boot-module-ys</artifactId>
<groupId>com.amosframework.boot</groupId>
<version>1.0.1</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>amos-boot-module-ys-api</artifactId>
<dependencies>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-elasticsearch</artifactId>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.amosframework.boot</groupId>
<artifactId>amos-boot-module-ymt-api</artifactId>
<version>${amos-boot-biz.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.amosframework.boot</groupId>
<artifactId>amos-boot-module-common-api</artifactId>
<version>${amos-boot-biz.version}</version>
</dependency>
<dependency>
<groupId>net.javacrumbs.shedlock</groupId>
<artifactId>shedlock-spring</artifactId>
</dependency>
<dependency>
<groupId>net.javacrumbs.shedlock</groupId>
<artifactId>shedlock-provider-redis-spring</artifactId>
</dependency>
<dependency>
<artifactId>amos-component-rule</artifactId>
<groupId>com.yeejoin</groupId>
</dependency>
</dependencies>
</project>
\ No newline at end of file
package com.yeejoin.amos.boot.module.ys.api.common;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import lombok.Data;
import java.io.Serializable;
import java.util.Date;
/**
* @description: 公共实体
* @author: duanwei
**/
@Data
public class BaseEntity implements Serializable {
private static final long serialVersionUID = -5464322936854328207L;
@TableId(type = IdType.ID_WORKER)
private Long id;
/**
* 创建时间
*/
@TableField(value = "create_date", fill = FieldFill.INSERT)
private Date createDate;
/**
* 更新时间
*/
@TableField(value = "update_time", fill = FieldFill.UPDATE)
private Date updateTime;
}
package com.yeejoin.amos.boot.module.ys.api.common;
import com.yeejoin.amos.boot.module.ys.api.enums.BaseExceptionEnum;
/**
* @Author cpp
* @Description基础异常类
* @Date 2023/4/23
*/
public class BaseException extends RuntimeException {
private static final long serialVersionUID = 194906846739586857L;
/**
* 错误码
*/
private int code;
/**
* 错误内容
*/
private String msg;
public BaseException(String msg) {
super(msg);
}
public BaseException(int code, String msg) {
super(msg);
this.code = code;
this.msg = msg;
}
public BaseException(BaseExceptionEnum baseExceptionEnum) {
super(baseExceptionEnum.getMsg());
this.msg = baseExceptionEnum.getMsg();
this.code = baseExceptionEnum.getCode();
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
package com.yeejoin.amos.boot.module.ys.api.common;
/**
* @Description: 通用常量类
* @Author: DELL
* @Date: 2021/5/26
*/
public interface BizCommonConstant {
/**
* 所有平台企业数据redisKey
*/
String COMPANY_TREE_REDIS_KEY = "REGULATOR_UNIT_TREE";
}
package com.yeejoin.amos.boot.module.ys.api.common;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import org.apache.commons.lang3.StringUtils;
import org.typroject.tyboot.core.foundation.utils.DateTimeUtil;
import java.io.IOException;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* @author yangyang
* @version v1.0
* @JsonComponent 会覆盖JsonFormat, 这里解析字段提升JsonFormat优先级
* <p>
* ProjectName: amos-boot-biz
* PackageName: com.yeejoin.amos.boot.module.ys.biz.config
* @date 2023/12/18 17:35
*/
public class BizCustomDateSerializer extends JsonSerializer<Date> {
private List<String> customFields = Arrays.asList("createDate", "acceptDate", "expiryDate", "applicationDate", "noticeDate", "installStartDate", "handleDate", "auditPassDate", "applyDate");
public BizCustomDateSerializer() {
}
@Override
public void serialize(Date value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
try {
Class<?> clazz = jgen.getCurrentValue().getClass();
if (Objects.equals(clazz, HashMap.class)) {
// 分页参数
if (customFields.contains(jgen.getOutputContext().getCurrentName())) {
SimpleDateFormat formatter = new SimpleDateFormat(DateTimeUtil.ISO_DATE);
jgen.writeString(formatter.format(value));
return;
}
} else {
Field field = clazz.getDeclaredField(jgen.getOutputContext().getCurrentName());
if (Objects.equals(field.getType(), Date.class)) {
if (field.isAnnotationPresent(JsonFormat.class)) {
String pattern = field.getAnnotation(JsonFormat.class).pattern();
if (StringUtils.isNotBlank(pattern)) {
SimpleDateFormat formatter = new SimpleDateFormat(pattern);
jgen.writeString(formatter.format(value));
return;
}
}
}
}
jgen.writeString(defaultFormattedDate(value));
} catch (Exception e) {
jgen.writeString(defaultFormattedDate(value));
}
}
private String defaultFormattedDate(Date value) {
SimpleDateFormat formatter = new SimpleDateFormat(DateTimeUtil.ISO_DATE_HOUR24_MIN_SEC);
String formattedDate = formatter.format(value);
return formattedDate;
}
}
\ No newline at end of file
package com.yeejoin.amos.boot.module.ys.api.common;
import com.yeejoin.amos.boot.module.ys.api.enums.CommonErrorEnum;
/**
* @description: 共同异常类
* @author: duanwei
* @create: 2019-08-28 20:07
**/
public class CommonException extends BaseException {
private static final long serialVersionUID = 194906846739586857L;
/**
* 错误码
*/
private int code;
/**
* 错误内容
*/
private String msg;
public CommonException(int code, String msg) {
super(msg);
this.code = code;
this.msg = msg;
}
public CommonException(CommonErrorEnum menuExceptionEnum) {
super(menuExceptionEnum.getMsg());
this.msg = menuExceptionEnum.getMsg();
this.code = menuExceptionEnum.getCode();
}
@Override
public int getCode() {
return code;
}
@Override
public void setCode(int code) {
this.code = code;
}
@Override
public String getMsg() {
return msg;
}
@Override
public void setMsg(String msg) {
this.msg = msg;
}
}
package com.yeejoin.amos.boot.module.ys.api.common;
import org.apache.commons.lang.StringUtils;
import java.util.ArrayList;
import java.util.List;
/**
*
* <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.boot.module.ys.api.common;
import org.springframework.util.Assert;
import java.io.Closeable;
import java.io.Flushable;
import java.io.IOException;
/**
* IO流拓展工具类,补充IOUtils新版本中废弃的closeQuietly
*
* @author King
* @since 2018/12/27 17:56
*/
public class ExtendedIOUtils {
public static void flush(Flushable... resources) throws IOException {
Assert.noNullElements(resources, "resources invalid");
int length = resources.length;
for (int i = 0; i < length; ++i) {
Flushable resource = resources[i];
if (resource != null) {
resource.flush();
}
}
}
public static void closeQuietly(Closeable... resources) {
int length = resources.length;
for (int i = 0; i < length; ++i) {
Closeable resource = resources[i];
if (resource != null) {
try {
resource.close();
} catch (IOException e) {
//ignore exception
}
}
}
}
}
package com.yeejoin.amos.boot.module.ys.api.common;
import java.util.HashMap;
import java.util.Map;
/**
* @Description: 全局单机缓存
* @Author: duanwei
* @Date: 2020/6/30
*/
public class GlobalCache {
/**
* 全局请求头
*/
public static Map<String, String> header = new HashMap<>();
/**
* 依赖参数容器
*/
public static Map<String, String> paramMap = new HashMap<>(1000);
}
package com.yeejoin.amos.boot.module.ys.api.common;
import com.alibaba.fastjson.JSONObject;
import com.yeejoin.amos.boot.module.ys.api.vo.ResponeVo;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
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.TrustStrategy;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContexts;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.*;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
/**
* @description: HTTP HTTPS 二次封装
* @author: duanwei
* @create: 2020-05-28 13:57
**/
public class HttpUtils {
/**
* 连接超时时间
*/
public static final int CONNECTION_TIMEOUT = 5000;
/**
* 请求超时时间
*/
public static final int CONNECTION_REQUEST_TIMEOUT = 5000;
/**
* 数据读取等待超时
*/
public static final int SOCKET_TIMEOUT = 10000;
/**
* http
*/
public static final String HTTP = "http";
/**
* https
*/
public static final String HTTPS = "https";
/**
* http端口
*/
public static final int DEFAULT_HTTP_PORT = 80;
/**
* https端口
*/
public static final int DEFAULT_HTTPS_PORT = 443;
/**
* 默认编码
*/
public static final String DEFAULT_ENCODING = "UTF-8";
private static final Logger log = LoggerFactory.getLogger(HttpUtils.class);
/**
* 根据请求头选择相应的client
* https HttpUtil.createSSLInsecureClient
* http createDefault
*
* @param url (url不带参数,例:http://test.com)
* @return CloseableHttpClient
*/
private static CloseableHttpClient getHttpClient(String url) {
CloseableHttpClient httpClient = null;
try {
if (url.startsWith(HTTPS)) {
// 创建一个SSL信任所有证书的httpClient对象
httpClient = HttpUtils.createSslInsecureClient();
} else {
httpClient = HttpClients.createDefault();
}
} catch (Exception e) {
log.error("请求client 初始化失败 请检查地址是否正确,url=" + url + " error" + e);
throw new RuntimeException(e);
}
return httpClient;
}
/**
* 获取post请求头
*
* @param url (url不带参数,例:http://test.com)
* @return HttpPost
*/
public static HttpPost getHttpPost(String url) {
HttpPost httpPost = new HttpPost(url);
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(CONNECTION_TIMEOUT)
.setConnectionRequestTimeout(CONNECTION_REQUEST_TIMEOUT)
.setSocketTimeout(SOCKET_TIMEOUT)
.setRedirectsEnabled(true)
.build();
httpPost.setConfig(requestConfig);
return httpPost;
}
/**
* get请求(1.处理http请求;2.处理https请求,信任所有证书)
*
* @param url (只能是http或https请求)
*/
public static ResponeVo get(String url) throws IOException {
log.info("----->调用请求 url:" + url);
String result = "";
// 处理参数
HttpGet httpGet;
CloseableHttpClient httpClient = null;
httpClient = getHttpClient(url);
httpGet = new HttpGet(url);
//加入请求头
if (GlobalCache.header != null) {
for (String key : GlobalCache.header.keySet()) {
String value = GlobalCache.header.get(key);
httpGet.setHeader(key, value);
}
}
//加入全局请求令牌权限
httpGet.setHeader("Http-Authorization", GlobalCache.paramMap.get("token"));
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(CONNECTION_TIMEOUT)
.setConnectionRequestTimeout(CONNECTION_REQUEST_TIMEOUT)
.setSocketTimeout(SOCKET_TIMEOUT)
//默认允许自动重定向
.setRedirectsEnabled(true)
.build();
httpGet.setConfig(requestConfig);
return baseRequest(httpClient, httpGet);
}
/**
* post请求(1.处理http请求;2.处理https请求,信任所有证书)
*
* @param url
* @param jsonParams 入参是个json字符串
* @return
*/
public static ResponeVo post(String url, String jsonParams) throws IOException,
NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
Assert.hasText(url, "url invalid");
String result;
CloseableHttpClient httpClient;
if (url.startsWith(HTTPS)) {
// 创建一个SSL信任所有证书的httpClient对象
httpClient = HttpUtils.createSslInsecureClient();
} else {
httpClient = HttpClients.createDefault();
}
CloseableHttpResponse response = null;
HttpPost httpPost = getHttpPost(url);
if (GlobalCache.header != null) {
for (String key : GlobalCache.header.keySet()) {
String value = GlobalCache.header.get(key);
httpPost.setHeader(key, value);
}
}
//加入全局请求令牌权限
httpPost.setHeader("Http-Authorization", GlobalCache.paramMap.get("token"));
if (GlobalCache.header.get("Content-Type") != null) {
String contentType = GlobalCache.header.get("Content-Type");
if ("application/x-www-form-urlencoded".equals(contentType)) {
JSONObject jsonObject = JSONObject.parseObject(jsonParams);
List<NameValuePair> params = new ArrayList<>();
//循环json key value 仅能解决正常对象 若Json对象中嵌套数组 则可能需要单独处理
if (jsonObject != null) {
for (Map.Entry<String, Object> entry : jsonObject.entrySet()) {
params.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
}
httpPost.setEntity(new UrlEncodedFormEntity(params, DEFAULT_ENCODING));
}
}
if ("application/json;charset=UTF-8".equals(contentType)) {
httpPost.setEntity(new StringEntity(jsonParams, ContentType.create("application/json", DEFAULT_ENCODING)));
}
} else {
httpPost.setEntity(new StringEntity(jsonParams, ContentType.create("application/json", DEFAULT_ENCODING)));
}
return baseRequest(httpClient, httpPost);
}
/**
* get请求(1.处理http请求;2.处理https请求,信任所有证书)
*
* @param url (只能是http或https请求)
* @return
*/
public static ResponeVo delete(String url) throws IOException, NoSuchAlgorithmException,
KeyStoreException, KeyManagementException {
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
if (url.startsWith(HTTPS)) {
// 创建一个SSL信任所有证书的httpClient对象
httpClient = HttpUtils.createSslInsecureClient();
} else {
httpClient = HttpClients.createDefault();
}
HttpDelete httpDelete = new HttpDelete(url);
if (GlobalCache.header != null) {
for (String key : GlobalCache.header.keySet()) {
String value = GlobalCache.header.get(key);
httpDelete.setHeader(key, value);
}
}
httpDelete.setHeader("Http-Authorization", GlobalCache.paramMap.get("token"));
return baseRequest(httpClient, httpDelete);
}
/**
* get请求(1.处理http请求;2.处理https请求,信任所有证书)
*
* @param url (只能是http或https请求)
* @return
*/
public static ResponeVo put(String url, String jsonParams) throws IOException, NoSuchAlgorithmException,
KeyStoreException, KeyManagementException {
log.info("----->调用请求 url:" + url + " ---->json参数:" + jsonParams);
CloseableHttpClient httpClient = null;
String content;
if (url.startsWith(HTTPS)) {
// 创建一个SSL信任所有证书的httpClient对象
httpClient = HttpUtils.createSslInsecureClient();
} else {
httpClient = HttpClients.createDefault();
}
CloseableHttpResponse response = null;
HttpPut httpPut = new HttpPut(url);
if (GlobalCache.header != null) {
for (String key : GlobalCache.header.keySet()) {
String value = GlobalCache.header.get(key);
httpPut.setHeader(key, value);
}
}
//加入全局请求令牌权限
httpPut.setHeader("Http-Authorization", GlobalCache.paramMap.get("token"));
if (GlobalCache.header.get("Content-Type") != null) {
String contentType = GlobalCache.header.get("Content-Type");
if ("application/x-www-form-urlencoded".equals(contentType)) {
JSONObject jsonObject = JSONObject.parseObject(jsonParams);
List<NameValuePair> params = new ArrayList<>();
//循环json key value 仅能解决正常对象 若Json对象中嵌套数组 则可能需要单独处理
if (jsonObject != null) {
for (Map.Entry<String, Object> entry : jsonObject.entrySet()) {
params.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
}
httpPut.setEntity(new UrlEncodedFormEntity(params, DEFAULT_ENCODING));
}
}
if ("application/json;charset=UTF-8".equals(contentType)) {
httpPut.setEntity(new StringEntity(jsonParams, ContentType.create("application/json", DEFAULT_ENCODING)));
}
} else {
log.error("请求头为空");
}
return baseRequest(httpClient, httpPut);
}
/**
* 采用绕过验证的方式处理https请求
*
* @param url
* @param reqMap
* @param encoding
* @return
*/
public static ResponeVo postSslUrl(String url, Map<String, Object> reqMap, String encoding) throws IOException,
KeyManagementException, NoSuchAlgorithmException {
String result;
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
ResponeVo responeVo = null;
// 添加参数
List<NameValuePair> params = buildParams(reqMap);
try {
//采用绕过验证的方式处理https请求
HostnameVerifier hostnameVerifier = (hostname, session) -> true;
SSLContext sslcontext = createIgnoreVerifySsl();
//设置协议http和https对应的处理socket链接工厂的对象
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.INSTANCE)
.register("https", new SSLConnectionSocketFactory(sslcontext, hostnameVerifier))
.build();
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
//创建自定义的httpclient对象
httpClient = HttpClients.custom().setConnectionManager(connManager).build();
//创建post方式请求对象
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params, encoding));
//指定报文头Content-type、User-Agent
httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
//执行请求操作,并拿到结果(同步阻塞)
responeVo = baseRequest(httpClient, httpPost);
} finally {
ExtendedIOUtils.closeQuietly(httpClient);
ExtendedIOUtils.closeQuietly(response);
}
return responeVo;
}
private static List<NameValuePair> buildParams(Map<String, Object> reqMap) {
List<NameValuePair> params = new ArrayList<>();
if (reqMap != null && reqMap.keySet().size() > 0) {
Iterator<Map.Entry<String, Object>> iter = reqMap.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry<String, Object> entity = iter.next();
params.add(new BasicNameValuePair(entity.getKey(), entity.getValue().toString()));
}
}
return params;
}
/**
* 创建一个SSL信任所有证书的httpClient对象
*
* @return
*/
public static CloseableHttpClient createSslInsecureClient() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
// 默认信任所有证书
HostnameVerifier hostnameVerifier = (hostname, session) -> true;
SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, (TrustStrategy) (chain, authType) -> true).build();
SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
return HttpClients.custom().setSSLSocketFactory(sslConnectionSocketFactory).build();
}
/**
* 绕过验证
*
* @return
* @throws NoSuchAlgorithmException
* @throws KeyManagementException
*/
public static SSLContext createIgnoreVerifySsl() throws NoSuchAlgorithmException, KeyManagementException {
SSLContext sc = SSLContext.getInstance("SSLv3");
// 实现一个X509TrustManager接口,用于绕过验证,不用修改里面的方法
X509TrustManager trustManager = new X509TrustManager() {
@Override
public void checkClientTrusted(java.security.cert.X509Certificate[] paramArrayOfX509Certificate, String paramString) {
}
@Override
public void checkServerTrusted(java.security.cert.X509Certificate[] paramArrayOfX509Certificate, String paramString) {
}
@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[]{};
}
};
sc.init(null, new TrustManager[]{trustManager}, new java.security.SecureRandom());
return sc;
}
private static String inputStreamToString(InputStream is) {
String line = "";
StringBuilder total = new StringBuilder();
// Wrap a BufferedReader around the InputStream
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
// Read response until the end
while ((line = rd.readLine()) != null) {
total.append(line);
}
} catch (IOException e) {
log.error(e.getLocalizedMessage(), e);
}
// Return full string
return total.toString();
}
public static ResponeVo baseRequest(CloseableHttpClient httpClient, HttpUriRequest request) {
ResponeVo responeVo = new ResponeVo();
CloseableHttpResponse response = null;
try {
String content;
response = httpClient.execute(request);
HttpEntity entity = response.getEntity();
InputStream inputStream = entity.getContent();
responeVo.setInputStream(inputStream);
content = inputStreamToString(inputStream);
responeVo.setCode(response.getStatusLine().getStatusCode());
responeVo.setContent(content);
responeVo.setResponse(response);
log.info("http调用完成,返回数据" + content);
} catch (Exception e) {
log.error(" http调用失败:" + e);
}
ExtendedIOUtils.closeQuietly(httpClient);
ExtendedIOUtils.closeQuietly(response);
return responeVo;
}
static byte[] inputStreamToByteArray(String filePath) throws IOException {
InputStream in = new FileInputStream(filePath);
byte[] data = toByteArray(in);
in.close();
return data;
}
static byte[] toByteArray(InputStream in) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buffer = new byte[1024 * 4];
int n = 0;
while ((n = in.read(buffer)) != -1) {
out.write(buffer, 0, n);
}
return out.toByteArray();
}
public static void inputStreamToFile(InputStream ins, File file) {
OutputStream os = null;
try {
os = new FileOutputStream(file);
int bytesRead = 0;
byte[] buffer = new byte[8192];
while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
os.write(buffer, 0, bytesRead);
}
os.close();
ins.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
package com.yeejoin.amos.boot.module.ys.api.common;
import lombok.Data;
/**
* @Author cpp
* @Description
* @Date 2023/4/23
*/
@Data
public class MobileLoginParam {
/**
* 注册类型:1-微信授权快捷登录;2-手机验证登录
*/
private int registerType;
/**
* 是否需要需要短信验证: true-验证; false-不验证
*/
private Boolean isNeedVerify;
/**
* 注册类型为1时使用:微信用户数据字段1,根据1、2进行数据解密,计算出手机号
*/
private String encryptedData;
/**
* 注册类型为1时使用:微信用户数据字段2,根据1、2进行数据解密,计算出手机号
*/
private String iv;
/**
*注册类型为1时使用:微信用户数据字段3,根据1、2、3进行数据解密,计算出手机号
*/
private String code;
/**
* 账号或手机号
*/
private String phoneNo;
/**
* 密码
*/
private String verifyCode;
}
\ No newline at end of file
package com.yeejoin.amos.boot.module.ys.api.common;
import java.math.BigDecimal;
import java.util.Collection;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* 字符串工具类
*
* @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]*");
private static Pattern NUMBER_PATTERN = Pattern.compile("-?[0-9]+(\\.[0-9]+)?");
/**
* 判断对象是否为空
*
* @param str
* @return
*/
public static boolean isNotEmpty(Object str) {
boolean flag = true;
if (str != null && !"".equals(str)) {
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 str 源字符串
* @return 是否数字的标志
*/
public static boolean isNumeric(String str) {
// 该正则表达式可以匹配所有的数字 包括负数
String bigStr;
try {
bigStr = new BigDecimal(str).toString();
} catch (Exception e) {
return false;//异常 说明包含非数字。
}
Matcher isNum = NUMBER_PATTERN.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;
}
public static boolean isEmpty(Collection collection) {
return collection == null || collection.isEmpty();
}
public static boolean isNotEmpty(Collection collection) {
return collection != null && collection.size() > 0;
}
public static boolean isEmpty(Map map) {
return map == null || map.isEmpty();
}
/**
* 截取前后都不是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 ("0".equals(s)) {
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;
}
}
package com.yeejoin.amos.boot.module.ys.api.dto;
import lombok.Getter;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.nio.file.Files;
@Getter
public class ByteArrayMultipartFile implements MultipartFile {
private byte[] bytes;
private String name;
private String originalFilename;
private String contentType;
public ByteArrayMultipartFile() {
}
public ByteArrayMultipartFile(String name, String originalFilename, String contentType, byte[] bytes) {
super();
this.name = name;
this.originalFilename = originalFilename;
this.contentType = contentType;
this.bytes = bytes;
}
@Override
public boolean isEmpty() {
return bytes.length == 0;
}
@Override
public long getSize() {
return bytes.length;
}
@Override
public InputStream getInputStream() {
return new ByteArrayInputStream(bytes);
}
@Override
public void transferTo(File destination) throws IOException {
try (OutputStream outputStream = Files.newOutputStream(destination.toPath())) {
outputStream.write(bytes);
}
}
}
package com.yeejoin.amos.boot.module.ys.api.enums;
/**
* @description: 基础枚举类
**/
public enum BaseExceptionEnum {
/**
* 请求成功
*/
SUCCESS(0, "请求成功"),
/**
* 系统繁忙
*/
SYSTEM_BUSY(100, "系统繁忙"),
/**
* 请求超时
*/
REQUEST_TIME_OUT(300, "请求超时"),
/**
* 参数错误
*/
PARAMETER_ERROR(400, "参数错误"),
/**
* 网络异常
*/
NETWORK_ERROR(404, "网络异常"),
/**
* 数据不存在
*/
DATA_NOT_EXISTS(600, "数据不存在"),
/**
* 无权访问
*/
ACCESSDENIED_ERROR(501, "无权访问"),
/**
* 请求已经过期
*/
REQUEST_EXPIRATION(406, "请求已经过期"),
/**
* 请求失败
*/
REQUEST_ERROR(407, "请求失败"),
/**
* 未知错误
*/
FAILURE(999, "未知错误");
private Integer code;
private String msg;
BaseExceptionEnum(Integer code, String msg) {
this.code = code;
this.msg = msg;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
package com.yeejoin.amos.boot.module.ys.api.enums;
/**
* 通用错误码,code编码:10000000-10000999
*
* @author King
* @since 2018/12/14 10:30
*/
public enum CommonErrorEnum {
/**
* 服务器核心数据丢失
*/
SERVER_KEY_DATA_MISSING(10000000, "服务器核心数据丢失"),
/**
* 服务器数据查询错误
*/
SERVER_DATA_QUERY_ERROR(10000001, "服务器数据查询错误"),
/**
* 主键查询主键无效
*/
QUERY_PRIMARY_INVALID(10000002, "主键查询主键无效"),
/**
* 主键查询主键无效
*/
QUERY_ONE_PARAM_INVALID(10000003, "唯一性查询参数无效"),
/**
* 序列化异常
*/
SERIALIZATION_EXCEPTION(10000004, "序列化异常"),
/**
* 反序列化异常
*/
DESERIALIZATION_EXCEPTION(10000005, "反序列化异常"),
/**
* 入参无效
*/
PARAM_INVALID(10000006, "入参无效"),
/**
* 核心字段无效
*/
CRUCIAL_FIELD_INVALID(10000007, "核心字段无效"),
/**
* 解压缩异常
*/
DECOMPRESS_EXCEPTION(10000008, "解压缩异常"),
/**
* 缓存查询key值无效
*/
CACHE_QUERY_KEY_INVALID(10000009, "缓存查询key值无效"),
/**
* 缓存失效
*/
CACHE_LOSE_EFFICACY(10000010, "缓存失效"),
/**
* 未知错误
*/
UNKNOWN(10000999, "未知错误");
private Integer code;
private String msg;
CommonErrorEnum(Integer code, String msg) {
this.code = code;
this.msg = msg;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
package com.yeejoin.amos.boot.module.ys.api.enums;
import lombok.Getter;
import org.apache.commons.compress.utils.Lists;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* 业务类型枚举
*
* @author Administrator
*/
@Getter
public enum CompanyTypeEnum {
/**
* 单位类型枚举
*/
SUPERVISION("supervision","supervision", "监管机构"),
USE("company","use", "使用单位"),
DESIGN("company","design", "设计单位"),
MANUFACTURE("company","manufacture", "制造单位"),
FILLING("company","filling", "充装单位"),
INDIVIDUAL("company","individual", "个人主体"),
CONSTRUCTION("company","construction", "安装改造维修单位"),
INSPECTION("company","inspection", "检验检测机构");
private final String level;
private final String code;
private final String name;
CompanyTypeEnum(String level, String code, String name) {
this.level = level;
this.code = code;
this.name = name;
}
public static String getNameByType(String code) {
String name = null;
for (CompanyTypeEnum enumOne : CompanyTypeEnum.values()) {
if (enumOne.getCode().equals(code)) {
name = enumOne.getName();
break;
}
}
return name;
}
public static String decideCompanyLevel(String str) {
List<CompanyTypeEnum> typeList = getCompanyTypeEnums(str);
if (typeList == null) return null;
String result;
Set<String> set = new HashSet<>();
for (CompanyTypeEnum one : typeList) {
set.add(one.getLevel());
}
result = String.join(",", set);
return result;
}
private static List<CompanyTypeEnum> getCompanyTypeEnums(String str) {
if (ValidationUtil.isEmpty(str)) {
return null;
}
List<CompanyTypeEnum> typeList = Lists.newArrayList();
for (CompanyTypeEnum enumOne : CompanyTypeEnum.values()) {
if (str.contains(enumOne.getName())) {
typeList.add(enumOne);
}
}
if (ValidationUtil.isEmpty(typeList)) {
return null;
}
return typeList;
}
public static String decideCompanyCode(String str) {
List<CompanyTypeEnum> typeList = getCompanyTypeEnums(str);
if (typeList == null) return null;
String result;
Set<String> set = new HashSet<>();
for (CompanyTypeEnum one : typeList) {
set.add(one.getCode());
}
result = String.join(",", set);
return result;
}
public static String decideCompanyType(String str) {
List<CompanyTypeEnum> typeList = getCompanyTypeEnums(str);
if (typeList == null) return null;
String result;
Set<String> set = new HashSet<>();
for (CompanyTypeEnum one : typeList) {
set.add(one.getName());
}
result = String.join(",", set);
return result;
}
}
package com.yeejoin.amos.boot.module.ys.api.vo;
import lombok.Data;
import org.apache.http.client.methods.CloseableHttpResponse;
import java.io.InputStream;
/**
* @description: http封装响应对象
* @author: duanwei
* @create: 2019-08-08 13:30
**/
@Data
public class ResponeVo {
int code;
CloseableHttpResponse response;
String content;
byte[] inStream;
InputStream inputStream;
}
<?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">
<parent>
<artifactId>amos-boot-module-ys</artifactId>
<groupId>com.amosframework.boot</groupId>
<version>1.0.1</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>amos-boot-module-ys-biz</artifactId>
<dependencies>
<dependency>
<groupId>com.amosframework.boot</groupId>
<artifactId>amos-boot-module-ys-api</artifactId>
<version>${amos-boot-biz.version}</version>
</dependency>
<dependency>
<groupId>com.amosframework.boot</groupId>
<artifactId>amos-boot-module-common-biz</artifactId>
<version>${amos-boot-biz.version}</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
</dependency>
<dependency>
<groupId>com.aspose</groupId>
<artifactId>aspose-words</artifactId>
<version>19.5jdk</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-httpclient</artifactId>
</dependency>
<dependency>
<groupId>com.esotericsoftware.kryo</groupId>
<artifactId>kryo</artifactId>
<version>2.24.0</version>
</dependency>
<dependency>
<groupId>de.javakaffee</groupId>
<artifactId>kryo-serializers</artifactId>
<version>0.45</version>
</dependency>
<dependency>
<groupId>com.esotericsoftware</groupId>
<artifactId>kryo</artifactId>
<version>4.0.2</version>
</dependency>
<dependency>
<groupId>cn.com.vastdata</groupId>
<artifactId>vastbase-jdbc</artifactId>
<version>2.7p</version>
</dependency>
<dependency>
<groupId>io.seata</groupId>
<artifactId>seata-spring-boot-starter</artifactId>
<version>1.8.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>2.7.8</version>
</plugin>
</plugins>
</build>
</project>
\ No newline at end of file
package com.yeejoin.amos;
import com.yeejoin.amos.boot.biz.common.utils.oConvertUtils;
import net.javacrumbs.shedlock.spring.annotation.EnableSchedulerLock;
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.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.FilterType;
import org.springframework.core.env.Environment;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import springfox.documentation.swagger2.annotations.EnableSwagger2WebMvc;
import java.net.InetAddress;
import java.net.UnknownHostException;
/**
* <pre>
* 特种设备服务启动类
* </pre>
*
* @author DELL
*/
@EnableTransactionManagement
@EnableConfigurationProperties
@ServletComponentScan
@EnableDiscoveryClient
@EnableFeignClients
@EnableAsync
@EnableSwagger2WebMvc
@EnableEurekaClient
@EnableSchedulerLock(defaultLockAtMostFor = "10m")
@MapperScan({"org.typroject.tyboot.demo.face.orm.dao*", "org.typroject.tyboot.face.*.orm.dao*",
"org.typroject.tyboot.core.auth.face.orm.dao*", "org.typroject.tyboot.component.*.face.orm.dao*",
"com.yeejoin.amos.boot.module.**.api.mapper", "com.yeejoin.amos.boot.biz.common.dao.mapper"})
@ComponentScan(basePackages = {"org.typroject", "com.yeejoin.amos"}, excludeFilters = {
@ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, classes = {org.typroject.tyboot.core.restful.exception.GlobalExceptionHandler.class})})
@SpringBootApplication(exclude = {org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration.class})
public class AmosYsApplication {
private static final Logger logger = LoggerFactory.getLogger(AmosYsApplication.class);
public static void main(String[] args) throws UnknownHostException {
ConfigurableApplicationContext context = SpringApplication.run(AmosYsApplication.class, args);
Environment env = context.getEnvironment();
String ip = InetAddress.getLocalHost().getHostAddress();
String port = env.getProperty("server.port");
String path = oConvertUtils.getString(env.getProperty("server.servlet.context-path"));
logger.info("\n----------------------------------------------------------\n\t"
+ "Application Amos-Ys is running! Access URLs:\n\t" + "Swagger文档: \thttp://" + ip + ":" + port
+ path + "/doc.html\n" + "----------------------------------------------------------\n");
}
}
package com.yeejoin.amos.boot.module.ys.biz.config;
import com.baomidou.mybatisplus.autoconfigure.MybatisPlusProperties;
import com.baomidou.mybatisplus.core.config.GlobalConfig;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import com.yeejoin.amos.boot.biz.config.MetaHandler;
import com.yeejoin.amos.boot.biz.config.MybatisSqlInjector;
import com.zaxxer.hikari.HikariDataSource;
import io.seata.rm.datasource.DataSourceProxy;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import javax.sql.DataSource;
/**
* 数据源代理
*
* @author LiuLin
*/
@Configuration
public class DataSourceConfiguration {
@Bean("dataSource")
public DataSourceProxy dataSourceProxy(HikariDataSourceProperties hikariDataSourceProperties, DataSourceProperties dataSourceProperties) {
HikariDataSource dataSource = dataSourceProperties.initializeDataSourceBuilder().type(HikariDataSource.class).build();
dataSource.setMaximumPoolSize(hikariDataSourceProperties.getMaximumPoolSize());
dataSource.setMinimumIdle(hikariDataSourceProperties.getMinimumIdle());
dataSource.setMaxLifetime(hikariDataSourceProperties.getMaxLifetime());
dataSource.setPoolName(hikariDataSourceProperties.getPoolName());
dataSource.setConnectionTestQuery(hikariDataSourceProperties.getConnectionTestQuery());
dataSource.setIdleTimeout(hikariDataSourceProperties.getIdleTimeout());
dataSource.setConnectionTimeout(hikariDataSourceProperties.getConnectionTimeout());
dataSource.setIdleTimeout(hikariDataSourceProperties.getIdleTimeout());
dataSource.setConnectionInitSql(hikariDataSourceProperties.getConnectionInitSql());
return new DataSourceProxy(dataSource);
}
@Bean(name = "sqlSessionFactory")
@Autowired
public SqlSessionFactory sqlSessionFactoryBean(DataSource dataSourceProxy, PaginationInterceptor paginationInterceptor, MetaHandler metaHandler, MybatisPlusProperties mybatisPlusProperties) throws Exception {
MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean();
bean.setDataSource(dataSourceProxy);
ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
bean.setMapperLocations(resolver.getResources("classpath*:mapper/*.xml"));
bean.setConfigurationProperties(mybatisPlusProperties.getConfigurationProperties());
GlobalConfig globalConfig = new GlobalConfig();
globalConfig.setSqlInjector(new MybatisSqlInjector());
globalConfig.setMetaObjectHandler(metaHandler);
bean.setGlobalConfig(globalConfig);
Interceptor[] plugins = {paginationInterceptor};
bean.setPlugins(plugins);
return bean.getObject();
}
@Bean
public MetaHandler metaHandler() {
return new MetaHandler();
}
}
package com.yeejoin.amos.boot.module.ys.biz.config;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.Arrays;
@Configuration
public class ElasticSearchClientConfig {
@Value("${spring.elasticsearch.rest.uris}")
private String uris;
@Value("${elasticsearch.username}")
private String username;
@Value("${elasticsearch.password}")
private String password;
@Bean(destroyMethod = "close")
public RestHighLevelClient restHighLevelClient() {
final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY,
new UsernamePasswordCredentials(username, password));
try {
HttpHost[] httpHosts = Arrays.stream(uris.split(",")).map(HttpHost::create).toArray(HttpHost[]::new);
RestClientBuilder builder = RestClient.builder(httpHosts);
builder.setHttpClientConfigCallback(httpClientBuilder -> {
httpClientBuilder.disableAuthCaching();
return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
});
// 该方法接收一个RequestConfig.Builder对象,对该对象进行修改后然后返回。
builder.setRequestConfigCallback(requestConfigBuilder -> {
// 连接超时(默认为1秒)
return requestConfigBuilder.setConnectTimeout(5000 * 1000)
// 套接字超时(默认为30秒)//更改客户端的超时限制默认30秒现在改为100*1000分钟
.setSocketTimeout(6000 * 1000);
});
return new RestHighLevelClient(builder);
} catch (Exception e) {
throw new IllegalStateException("Invalid ES nodes " + "property '" + uris + "'", e);
}
}
}
package com.yeejoin.amos.boot.module.jg.biz.config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.typroject.tyboot.core.foundation.context.RequestContext;
import org.typroject.tyboot.core.restful.utils.ResponseModel;
import javax.servlet.http.HttpServletRequest;
@RestControllerAdvice
public class GlobalExceptionHandler {
private final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
public GlobalExceptionHandler() {
log.info("GlobalExceptionHandler initialized.");
}
@ExceptionHandler(Exception.class)
public ResponseModel<Object> handleException(Exception exception, HttpServletRequest request) {
log.error("Exception occurred:", exception);
ResponseModel<Object> response = new ResponseModel<>();
response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
response.setDevMessage("FAILED");
response.setMessage(exception.getMessage());
response.setTraceId(RequestContext.getTraceId());
response.setPath(request != null ? request.getServletPath() : null);
if (exception.getMessage() != null && (exception.getMessage().contains("账号已经在其他设备登录") || exception.getMessage().contains("请重新登录"))) {
response.setStatus(HttpStatus.FORBIDDEN.value());
}
return response;
}
}
package com.yeejoin.amos.boot.module.ys.biz.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* @author shg
*/
@Component
@ConfigurationProperties(prefix = "spring.datasource.hikari")
@Data
public class HikariDataSourceProperties {
private int maximumPoolSize;
private int minimumIdle;
private boolean autoCommit;
private long idleTimeout;
private String poolName;
private long maxLifetime;
private long connectionTimeout;
private String connectionTestQuery;
private long validationTimeout;
private String connectionInitSql;
}
package com.yeejoin.amos.boot.module.ys.biz.config;
import org.typroject.tyboot.core.foundation.exception.BaseException;
public class LocalBadRequest extends BaseException {
public LocalBadRequest(String message)
{
super(message, com.yeejoin.amos.component.robot.BadRequest.class.getSimpleName(),message);
this.httpStatus = 500;
}
}
\ No newline at end of file
package com.yeejoin.amos.boot.module.ys.biz.config;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.yeejoin.amos.boot.module.ys.biz.utils.SqlInjectorUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration(value="MybatisPlusConfig")
public class MybatisPlusConfigs {
@Bean
public PaginationInterceptor paginationInterceptor()
{
PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
paginationInterceptor.setLimit(50000);
paginationInterceptor.setDialectType(DbType.POSTGRE_SQL.getDb());
return paginationInterceptor;
}
@Bean
public SqlInjectorUtils sqlInjectorUtils() {
return new SqlInjectorUtils();
}
}
package com.yeejoin.amos.boot.module.ys.biz.config;
import lombok.extern.slf4j.Slf4j;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
@Slf4j
public class RedissonManager {
/**
* 集群环境使用-节点信息
*/
@Value("${spring.redis.cluster.nodes:default}")
private String clusterNodes;
/**
* 公共-密码
*/
@Value("${spring.redis.password}")
private String password;
/**
* 单机环境使用
*/
@Value("${spring.redis.host:default}")
private String host;
/**
* 单机环境使用
*/
@Value("${spring.redis.port:default}")
private String port;
/**
* 单机环境使用
*/
@Value("${spring.redis.database:0}")
private int database;
@Bean
@ConditionalOnProperty(name = "spring.redis.mode", havingValue = "cluster")
public RedissonClient redissonClient() {
// 集群环境使用
Config config = new Config();
config.useClusterServers()
.addNodeAddress(clusterNodes.split(","))
.setPassword(password);
return Redisson.create(config);
}
@Bean
@ConditionalOnProperty(name = "spring.redis.mode", havingValue = "singleton", matchIfMissing = true)
public RedissonClient redissonSingletonClient() {
// 单机环境使用
Config config = new Config();
config.useSingleServer().setAddress(host + ":" + port).setPassword(password).setDatabase(database);
return Redisson.create(config);
}
}
package com.yeejoin.amos.boot.module.ys.biz.config;
import net.javacrumbs.shedlock.core.LockProvider;
import net.javacrumbs.shedlock.provider.redis.spring.RedisLockProvider;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
/**
* @author Administrator
*/
@Configuration
public class ShedLockConfig {
@Bean
public LockProvider lockProvider(RedisConnectionFactory connectionFactory) {
return new RedisLockProvider(connectionFactory);
}
}
package com.yeejoin.amos.boot.module.ys.biz.config;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import feign.codec.Encoder;
import feign.form.spring.SpringFormEncoder;
import io.seata.core.context.RootContext;
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.util.StringUtils;
import org.springframework.web.context.request.RequestContextListener;
@Configuration
public class XidFeignConfiguration implements RequestInterceptor {
@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();
}
@Override
public void apply(RequestTemplate template) {
String xid = RootContext.getXID();
if(StringUtils.hasText(xid)){
template.header(RootContext.KEY_XID, xid);
}
}
}
\ No newline at end of file
package com.yeejoin.amos.boot.module.ys.biz.dao;
import com.yeejoin.amos.boot.module.ymt.api.entity.EsElevator;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.stereotype.Repository;
/**
* @author fengwang
* @date 2021-09-26.
*/
@Repository
public interface ESElavtorRepository extends PagingAndSortingRepository<EsElevator, Long> {
}
package com.yeejoin.amos.boot.module.ys.biz.feign;
import com.yeejoin.amos.boot.biz.common.feign.FeignConfiguration;
import com.yeejoin.amos.component.feign.config.InnerInvokException;
import com.yeejoin.amos.component.feign.model.FeignClientResult;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;
import com.yeejoin.amos.feign.privilege.model.VerifyCodeAuthModel;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.*;
import org.typroject.tyboot.core.restful.utils.ResponseModel;
@FeignClient(value = "AMOS-API-PRIVILEGE", configuration = {FeignConfiguration.class})
public interface PrivilegeFeginService {
@RequestMapping(value = "/privilege/v1/agencyuser/me", method = RequestMethod.GET)
ResponseModel<AgencyUserModel> getMe();
//获取单位树
@RequestMapping(value = "/privilege/v1/company/tree", method = RequestMethod.GET)
FeignClientResult tree(@RequestHeader("token") String token, @RequestHeader("appKey") String appKey, @RequestHeader("product") String product);
@RequestMapping(value = {"/privilege/v1/company/tree/cache"}, method = {RequestMethod.GET})
FeignClientResult queryAgencyTreeForCache(@RequestHeader("token") String token, @RequestHeader("appKey") String appKey, @RequestHeader("product") String product) throws InnerInvokException;
//获取省级行政区划
@RequestMapping(value = "systemctl/v1/region/level", method = RequestMethod.GET)
FeignClientResult getProvince(@RequestParam String level);
//获取行政区划树
@RequestMapping(value = "systemctl/v1/region/tree", method = RequestMethod.GET)
FeignClientResult getTree();
/**
* 手机号验证码登录
*/
@RequestMapping(value = "/privilege/v1/auth/mobile/verifycode", method = RequestMethod.POST)
FeignClientResult mobileVerifyCode(@RequestBody VerifyCodeAuthModel model) throws InnerInvokException;
@RequestMapping(value = "/privilege/v1/agencyuser/list/company/{companyId}", method = RequestMethod.GET)
FeignClientResult getCompanyUser(@PathVariable(value = "companyId")Long companyId);
}
package com.yeejoin.amos.boot.module.ys.biz.feign;
import com.yeejoin.amos.boot.module.ys.biz.config.XidFeignConfiguration;
import com.yeejoin.amos.component.feign.config.InnerInvokException;
import com.yeejoin.amos.component.feign.model.FeignClientResult;
import com.yeejoin.amos.feign.systemctl.model.TaskV2Model;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import java.util.List;
/**
* @author LiuLin
* @apiNote 待办Feign调用
* @date 2024-05-16
*/
@FeignClient(name = "AMOS-API-PRIVILEGE", path = "/systemctl/v2/task", configuration = {XidFeignConfiguration.class})
public interface TaskV2FeignService {
/**
* 批量新增任务
*
* @param modelList 新增待办
* @return TaskV2Model
* @throws InnerInvokException e
*/
@RequestMapping(value = "/batch/add", method = RequestMethod.POST)
FeignClientResult<List<TaskV2Model>> batchAdd(@RequestBody List<TaskV2Model> modelList) throws InnerInvokException;
/**
* 更新任务
*
* @param model 待办信息
* @param sequenceNbr 主键
* @return TaskV2Model
* @throws InnerInvokException e
*/
@RequestMapping(value = "/{sequenceNbr}", method = RequestMethod.PUT)
FeignClientResult<TaskV2Model> update(@RequestBody TaskV2Model model, @PathVariable("sequenceNbr") Long sequenceNbr) throws InnerInvokException;
/**
* 创建任务
*
* @param model 待办
* @return
* @throws InnerInvokException
*/
@RequestMapping(value = "", method = RequestMethod.POST)
FeignClientResult<TaskV2Model> create(@RequestBody TaskV2Model model) throws InnerInvokException;
/**
* 批量删除任务
*
* @param ids 主键
* @return Long
* @throws InnerInvokException e
*/
@RequestMapping(value = "/{ids}", method = RequestMethod.DELETE)
FeignClientResult<List<Long>> delete(@PathVariable("ids") String ids) throws InnerInvokException;
/**
* 查询指定任务
*
* @param relationId 关联Id
* @return List<TaskV2Model>
* @throws InnerInvokException
*/
@RequestMapping(value = "/queryByRelationId/{relationId}", method = RequestMethod.GET)
FeignClientResult<List<TaskV2Model>> selectListByRelationId(@PathVariable("relationId") String relationId) throws InnerInvokException;
/**
* 批量修改任务
*/
@RequestMapping(value = "/batch/update", method = RequestMethod.PUT)
FeignClientResult<List<TaskV2Model>> batchUpdate(@RequestBody List<TaskV2Model> modelList) throws InnerInvokException;
}
package com.yeejoin.amos.boot.module.ys.biz.feign;
import com.yeejoin.amos.boot.biz.common.feign.FeignConfiguration;
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 org.typroject.tyboot.core.restful.utils.ResponseModel;
import java.util.List;
import java.util.Map;
@FeignClient(name = "TZS-YMT", path = "/ymt", configuration =
{FeignConfiguration.class})
public interface TzsServiceFeignClient {
/**
* 创建监管码及96333
*
* @param map 请求体
* @return
*/
@RequestMapping(value = "/equipment-category/createSupervisorCode", method = RequestMethod.POST)
ResponseModel<Map<String, Object>> createCode(@RequestBody Map<String, Object> map);
/**
* 创建监管码及96333
*
* @param paramMap 请求体
* @return
*/
@RequestMapping(value = "/equipment-category/commonUpdateEsData", method = RequestMethod.POST)
ResponseModel<Map<String, Object>> commonUpdateEsDataByIds(@RequestBody Map<String, Map<String, Object>> paramMap);
/**
* 申请单编号生成
* @param type 参考ApplicationFormTypeEnum中的枚举
* @param batchSize batchSize
* @return List
*/
@RequestMapping(value = "/generate-code/applicationFormCode", method = RequestMethod.POST)
ResponseModel<List<String>> applicationFormCode(@RequestParam("type") String type,
@RequestParam("batchSize") int batchSize);
/**
* 生成设备注册编码
* @param key 16位
* @return 生成设备注册编码(20位)
*/
@RequestMapping(value = "/generate-code/deviceRegistrationCode", method = RequestMethod.POST)
ResponseModel<String> deviceRegistrationCode(@RequestParam("key") String key);
/**
* 使用登记证生成
* @param key 起11陕C
* @return 生成使用登记证编号(13位,起11陕C00001(23))
*/
@RequestMapping(value = "/generate-code/useRegistrationCode", method = RequestMethod.POST)
ResponseModel<String> useRegistrationCode(@RequestParam("key") String key);
}
package com.yeejoin.amos.boot.module.ys.biz.feign;
import com.alibaba.fastjson.JSONObject;
import com.yeejoin.amos.boot.module.ys.biz.config.XidFeignConfiguration;
import com.yeejoin.amos.component.feign.model.FeignClientResult;
import com.yeejoin.amos.feign.workflow.model.*;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;
@FeignClient(name = "AMOS-API-WORKFLOW", path = "workflow", configuration = {XidFeignConfiguration.class})
public interface WorkFlowFeignService {
/***
* 根据task_id 获取节点信息
*
* */
@RequestMapping(value = "/history/task/nodeInfo", method = RequestMethod.GET)
FeignClientResult<JSONObject> getNodeInfo(@RequestParam(value = "taskId") String taskId);
/***
*
* 查询当前流程对应的可执行任务,无权限级别
* */
@RequestMapping(value = "/task/getTaskNoAuth/{processInstanceId}", method = RequestMethod.GET)
JSONObject getTaskNoAuth(@PathVariable(value = "processInstanceId") String processInstanceId);
/***
*
* 获取流程审批日志
* */
@RequestMapping(value = "/task/flowLogger/{procInsId}", method = RequestMethod.GET)
FeignClientResult<Map<String, Object>> getFlowLogger(@PathVariable(value = "procInsId") String procInsId);
@RequestMapping(value = "/history/task/nodeInfo", method = RequestMethod.GET)
FeignClientResult<JSONObject> getNodeInfotoken(
@RequestHeader(name = "appKey", required = true) String appKey,
@RequestHeader(name = "product", required = true) String product,
@RequestHeader(name = "token", required = true) String token,
@RequestParam(value = "taskId") String taskId);
/***
*
* 查询当前流程对应的可执行任务,无权限级别
* */
@RequestMapping(value = "/task/getTaskNoAuth/{processInstanceId}", method = RequestMethod.GET)
JSONObject getTaskNoAuthtoken(
@RequestHeader(name = "appKey", required = true) String appKey,
@RequestHeader(name = "product", required = true) String product,
@RequestHeader(name = "token", required = true) String token,
@PathVariable(value = "processInstanceId") String processInstanceId);
@RequestMapping(value = "/v2/task/rollBack/{processInstanceId}", method = RequestMethod.POST)
JSONObject rollBack(@PathVariable(value = "processInstanceId") String processInstanceId);
/**
* 工作流启动接口
*
* @param params 业务参数
* @return ProcessTaskDTO
* @throws Exception e
*/
@RequestMapping(value = "/v2/task/start/batch", method = RequestMethod.POST)
FeignClientResult<List<ProcessTaskDTO>> startForBatch(@RequestBody ActWorkflowBatchDTO params) throws Exception;
/**
* 工作流驳回任务接口
*
* @param taskId 任务Id
* @param data 业务参数
* @return ProcessTaskDTO
* @throws Exception e
*/
@RequestMapping(value = "/v2/task/reject/{taskId}", method = RequestMethod.POST)
FeignClientResult<ProcessTaskDTO> reject(@PathVariable("taskId") String taskId, @RequestBody TaskResultDTO data) throws Exception;
/**
* 工作流完成任务接口
*
* @param taskId 任务Id
* @param data 业务参数
* @return ProcessTaskDTO
* @throws Exception e
*/
@RequestMapping(value = "/v2/task/complete/standard/{taskId}", method = RequestMethod.POST)
FeignClientResult<ProcessTaskDTO> completeByTaskFroStandard(@PathVariable("taskId") String taskId, @RequestBody TaskResultDTO data) throws Exception;
/**
* 工作流撤回
*
* @param processInstanceId processInstanceId
* @return ProcessTaskDTO
*/
@PostMapping(value = "/v2/task/rollBack/standard/{processInstanceId}")
FeignClientResult<ProcessTaskDTO> rollBackTask(@PathVariable("processInstanceId") String processInstanceId);
/**
* 转办任务
*
* @param flowTaskVo flowTaskVo
* @return ProcessTaskDTO
*/
@PostMapping(value = "/v2/task/assign")
FeignClientResult<ProcessTaskDTO> assign(@RequestBody FlowTaskVo flowTaskVo);
/**
* 终止流程
*
* @param processInstanceId processInstanceId
* @return ProcessInstanceDTO
* @throws Exception e
*/
@DeleteMapping(value = "/v2/task/stopProcess/{processInstanceId}")
FeignClientResult<ProcessInstanceDTO> stopProcess(@PathVariable("processInstanceId") String processInstanceId, @RequestParam(required = false, value = "stopReason") String stopReason) throws Exception;
/**
* 处理审批错误历史数据
*
* @param processInstanceId processInstanceId
* @return ProcessTaskDTO
*/
@RequestMapping(value = "/v2/task/error/history/data/{processInstanceId}", method = RequestMethod.GET)
FeignClientResult<ProcessTaskDTO> handleErrorForm(@PathVariable("processInstanceId") String processInstanceId,
@RequestParam(value = "receiveCompanyCode") String receiveCompanyCode);
}
package com.yeejoin.amos.boot.module.ys.biz.service.impl;
import com.yeejoin.amos.boot.module.ys.biz.utils.RedisUtil;
import com.yeejoin.amos.component.robot.AmosRequestContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.typroject.tyboot.core.foundation.context.RequestContext;
@Service
public class StartPlatformTokenService {
@Autowired
RedisUtil redisUtil;
@Autowired
AmosRequestContext amosRequestContext;
public void getToken() {
RequestContext.setProduct(amosRequestContext.getProduct());
RequestContext.setAppKey(amosRequestContext.getAppKey());
RequestContext.setToken(amosRequestContext.getToken());
}
}
package com.yeejoin.amos.boot.module.ys.biz.utils;
import org.apache.commons.lang.StringUtils;
import java.util.ArrayList;
import java.util.List;
/**
*
* <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.boot.module.ys.biz.utils;
import org.typroject.tyboot.core.restful.exception.instance.BadRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
public class FileExporter {
public static void exportFile(FileType fileType, String fileName, byte[] data, HttpServletResponse response) {
try {
response.reset();
response.setCharacterEncoding("utf-8");
response.setContentType(fileType.getContentType());
fileName = fileName.replaceAll("\\..*", "");
fileName = URLEncoder.encode(fileName + fileType.getFileSufix(), "UTF-8");
response.setHeader("Content-Disposition", "attachment; filename=" + fileName + "");
response.getOutputStream().write(data);
response.getOutputStream().flush();
} catch (Exception e) {
throw new BadRequest("导出文档出错");
} finally {
try {
response.getOutputStream().close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 文件类型
*/
public enum FileType {
// word文档
docx(".docx", "application/msword"),
// pdf文档
pdf(".pdf", "application/pdf");
private String fileSufix;
private String contentType;
private FileType(String fileSufix, String contentType) {
this.fileSufix = fileSufix;
this.contentType = contentType;
}
public String getFileSufix() {
return fileSufix;
}
public String getContentType() {
return contentType;
}
public static FileType getInstance(String fileSufix) {
FileType knowledgeRoleName = null;
for (FileType fileType : FileType.values()) {
if (fileType.getFileSufix().equals(fileSufix)) {
knowledgeRoleName = fileType;
}
}
return knowledgeRoleName;
}
}
}
package com.yeejoin.amos.boot.module.ys.biz.utils;
import org.apache.commons.io.IOUtils;
import org.apache.http.*;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.security.GeneralSecurityException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class HttpUtils {
private static PoolingHttpClientConnectionManager connMgr;
private static RequestConfig requestConfig;
private static final int MAX_TIMEOUT = 50000;
private static final Logger logger = LoggerFactory.getLogger(HttpUtils.class);
static {
// 设置连接池
connMgr = new PoolingHttpClientConnectionManager();
// 设置连接池大小
connMgr.setMaxTotal(100);
connMgr.setDefaultMaxPerRoute(connMgr.getMaxTotal());
// Validate connections after 1 sec of inactivity
connMgr.setValidateAfterInactivity(5000);
RequestConfig.Builder configBuilder = RequestConfig.custom();
// 设置连接超时
configBuilder.setConnectTimeout(MAX_TIMEOUT);
// 设置读取超时
configBuilder.setSocketTimeout(MAX_TIMEOUT);
// 设置从连接池获取连接实例的超时
configBuilder.setConnectionRequestTimeout(MAX_TIMEOUT);
requestConfig = configBuilder.build();
}
/**
* 发送 GET 请求(HTTP),不带输入数据
*
* @param url
* @return
*/
public static String doGet(String url) {
return doGet(url, new HashMap<String, Object>());
}
/**
* 发送 GET 请求(HTTP),K-V形式
*
* @param url
* @param params
* @return
*/
public static String doGet(String url, Map<String, Object> params) {
String apiUrl = url;
StringBuffer param = new StringBuffer();
int i = 0;
for (String key : params.keySet()) {
if (i == 0)
param.append("?");
else
param.append("&");
param.append(key).append("=").append(params.get(key));
i++;
}
apiUrl += param;
String result = null;
HttpClient httpClient = null;
if (apiUrl.startsWith("https")) {
httpClient = HttpClients.custom().setSSLSocketFactory(createSSLConnSocketFactory())
.setConnectionManager(connMgr).setDefaultRequestConfig(requestConfig).build();
} else {
httpClient = HttpClients.createDefault();
}
try {
HttpGet httpGet = new HttpGet(apiUrl);
HttpResponse response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
result = IOUtils.toString(instream, "UTF-8");
}
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
/**
* 发送 POST 请求(HTTP),不带输入数据
*
* @param apiUrl
* @return
*/
public static String doPost(String apiUrl) {
return doPost(apiUrl, new HashMap<String, Object>());
}
/**
* 发送 POST 请求,K-V形式
*
* @param apiUrl
* API接口URL
* @param params
* 参数map
* @return
*/
public static String doPost(String apiUrl, Map<String, Object> params) {
CloseableHttpClient httpClient = null;
if (apiUrl.startsWith("https")) {
httpClient = HttpClients.custom().setSSLSocketFactory(createSSLConnSocketFactory())
.setConnectionManager(connMgr).setDefaultRequestConfig(requestConfig).build();
} else {
httpClient = HttpClients.createDefault();
}
String httpStr = null;
HttpPost httpPost = new HttpPost(apiUrl);
CloseableHttpResponse response = null;
try {
httpPost.setConfig(requestConfig);
List<NameValuePair> pairList = new ArrayList<>(params.size());
for (Map.Entry<String, Object> entry : params.entrySet()) {
NameValuePair pair = new BasicNameValuePair(entry.getKey(), entry.getValue()!=null?entry.getValue().toString():"");
pairList.add(pair);
}
httpPost.setEntity(new UrlEncodedFormEntity(pairList, Charset.forName("UTF-8")));
response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
httpStr = EntityUtils.toString(entity, "UTF-8");
} catch (IOException e) {
e.printStackTrace();
} finally {
if (response != null) {
try {
EntityUtils.consume(response.getEntity());
} catch (IOException e) {
e.printStackTrace();
}
}
}
return httpStr;
}
/**
* 发送 POST 请求,K-V形式
*
* @param apiUrl
* API接口URL
* @param params
* 参数map
* @return
*/
public static String doPostWithHeader(String apiUrl, Map<String, Object> params, Map<String, String> headerMap) {
CloseableHttpClient httpClient = null;
if (apiUrl.startsWith("https")) {
httpClient = HttpClients.custom().setSSLSocketFactory(createSSLConnSocketFactory())
.setConnectionManager(connMgr).setDefaultRequestConfig(requestConfig).build();
} else {
httpClient = HttpClients.createDefault();
}
String httpStr = null;
HttpPost httpPost = new HttpPost(apiUrl);
for (Map.Entry<String, String> entry : headerMap.entrySet()) {
httpPost.setHeader(entry.getKey(), entry.getValue());
}
CloseableHttpResponse response = null;
try {
httpPost.setConfig(requestConfig);
List<NameValuePair> pairList = new ArrayList<>(params.size());
for (Map.Entry<String, Object> entry : params.entrySet()) {
NameValuePair pair = new BasicNameValuePair(entry.getKey(), entry.getValue()!=null?entry.getValue().toString():"");
pairList.add(pair);
}
httpPost.setEntity(new UrlEncodedFormEntity(pairList, Charset.forName("UTF-8")));
response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
httpStr = EntityUtils.toString(entity, "UTF-8");
} catch (IOException e) {
e.printStackTrace();
} finally {
if (response != null) {
try {
EntityUtils.consume(response.getEntity());
} catch (IOException e) {
e.printStackTrace();
}
}
}
return httpStr;
}
/**
* 发送 POST 请求,JSON形式,接收端需要支持json形式,否则取不到数据
*
* @param apiUrl
* @param json
* json对象
* @return
*/
public static String doPost(String apiUrl, String json) {
CloseableHttpClient httpClient = null;
if (apiUrl.startsWith("https")) {
httpClient = HttpClients.custom().setSSLSocketFactory(createSSLConnSocketFactory()).setConnectionManager(connMgr).setDefaultRequestConfig(requestConfig).build();
} else {
httpClient = HttpClients.createDefault();
}
String httpStr = null;
HttpPost httpPost = new HttpPost(apiUrl);
CloseableHttpResponse response = null;
try {
httpPost.setConfig(requestConfig);
StringEntity stringEntity = new StringEntity(json, "UTF-8");// 解决中文乱码问题
stringEntity.setContentEncoding("UTF-8");
stringEntity.setContentType("application/json");
httpPost.setEntity(stringEntity);
response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
httpStr = EntityUtils.toString(entity, "UTF-8");
} catch (IOException e) {
e.printStackTrace();
} finally {
if (response != null) {
try {
EntityUtils.consume(response.getEntity());
} catch (IOException e) {
e.printStackTrace();
}
}
}
return httpStr;
}
/**
* 发送 POST 请求,JSON形式,接收端需要支持json形式,否则取不到数据
*
* @param apiUrl
* @param json
* json对象
* @return
*/
public static String doPostWithHeader(String apiUrl, String json, Map<String, String> headerMap) {
CloseableHttpClient httpClient = null;
if (apiUrl.startsWith("https")) {
httpClient = HttpClients.custom().setSSLSocketFactory(createSSLConnSocketFactory()).setConnectionManager(connMgr).setDefaultRequestConfig(requestConfig).build();
} else {
httpClient = HttpClients.createDefault();
}
String httpStr = null;
HttpPost httpPost = new HttpPost(apiUrl);
for (Map.Entry<String, String> entry : headerMap.entrySet()) {
httpPost.setHeader(entry.getKey(), entry.getValue());
}
CloseableHttpResponse response = null;
try {
httpPost.setConfig(requestConfig);
StringEntity stringEntity = new StringEntity(json, "UTF-8");// 解决中文乱码问题
stringEntity.setContentEncoding("UTF-8");
stringEntity.setContentType("application/json");
httpPost.setEntity(stringEntity);
response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
httpStr = EntityUtils.toString(entity, "UTF-8");
} catch (IOException e) {
e.printStackTrace();
} finally {
if (response != null) {
try {
EntityUtils.consume(response.getEntity());
} catch (IOException e) {
e.printStackTrace();
}
}
}
return httpStr;
}
/**
* 发送post 请求并且获取下载字节流
* @param apiUrl
* @param json
* @param headerMap
* @return
*/
public static byte[] doPostWithHeaderDownload(String apiUrl, String json, Map<String, String> headerMap) {
InputStream inputStream = null;
CloseableHttpClient httpClient = null;
if (apiUrl.startsWith("https")) {
httpClient = HttpClients.custom().setSSLSocketFactory(createSSLConnSocketFactory()).setConnectionManager(connMgr).setDefaultRequestConfig(requestConfig).build();
} else {
httpClient = HttpClients.createDefault();
}
String httpStr = null;
HttpPost httpPost = new HttpPost(apiUrl);
for (Map.Entry<String, String> entry : headerMap.entrySet()) {
httpPost.setHeader(entry.getKey(), entry.getValue());
}
CloseableHttpResponse response = null;
ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
try {
httpPost.setConfig(requestConfig);
StringEntity stringEntity = new StringEntity(json, "UTF-8");// 解决中文乱码问题
stringEntity.setContentEncoding("UTF-8");
stringEntity.setContentType("application/json");
httpPost.setEntity(stringEntity);
response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
byte[] buff = new byte[1024];
int rc = 0;
while ((rc = inputStream.read(buff, 0, buff.length)) > 0) {
swapStream.write(buff, 0, rc);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (response != null) {
try {
EntityUtils.consume(response.getEntity());
} catch (IOException e) {
e.printStackTrace();
}
}
}
return swapStream.toByteArray();
}
/**
* 发送get请求并且获取下载字节流
* @param apiUrl
* @return
*/
public static Map<String, Object> doGetDownload(String apiUrl) {
Map<String, Object> result = new HashMap<>();
InputStream inputStream = null;
CloseableHttpClient httpClient = null;
if (apiUrl.startsWith("https")) {
httpClient = HttpClients.custom().setSSLSocketFactory(createSSLConnSocketFactory()).setConnectionManager(connMgr).setDefaultRequestConfig(requestConfig).build();
} else {
httpClient = HttpClients.createDefault();
}
HttpGet httpGet = new HttpGet(apiUrl);
CloseableHttpResponse response = null;
ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
try {
response = httpClient.execute(httpGet);
Header[] heads = response.getHeaders("Content-disposition");
if(heads != null && heads[0] != null) {
HeaderElement[] elements = heads[0].getElements();
for (HeaderElement el : elements) {
NameValuePair pair = el.getParameterByName("filename");
result.put("filename",pair.getValue());
}
}
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
byte[] buff = new byte[1024];
int rc = 0;
while ((rc = inputStream.read(buff, 0, buff.length)) > 0) {
swapStream.write(buff, 0, rc);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (response != null) {
try {
EntityUtils.consume(response.getEntity());
} catch (IOException e) {
e.printStackTrace();
}
}
}
result.put("bytes",swapStream.toByteArray());
return result;
}
/**
* 发送上传post 文件
* @param apiUrl
* @param file
* @return
*/
public static String doPostWithFile(String apiUrl, MultipartFile file, String fileParam, String token , String type) {
CloseableHttpClient httpClient = null;
if (apiUrl.startsWith("https")) {
httpClient = HttpClients.custom().setSSLSocketFactory(createSSLConnSocketFactory())
.setConnectionManager(connMgr).setDefaultRequestConfig(requestConfig).build();
} else {
httpClient = HttpClients.createDefault();
}
String httpStr = null;
HttpPost httpPost = new HttpPost(apiUrl);
CloseableHttpResponse response = null;
try {
httpPost.addHeader("Connection", "keep-alive");
httpPost.addHeader("Accept", "*/*");
httpPost.addHeader("Content-Type", "multipart/form-data;boundary=------------7da2e536604c8");
httpPost.addHeader("User-Agent",
"Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0) ");
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setBoundary("------------7da2e536604c8")
.setCharset(Charset.forName("UTF-8"))
.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addTextBody("type", type);
// 设置access_token,
builder.addTextBody("access_token", token);
String fileName = null;
fileName = file.getOriginalFilename();
builder.addBinaryBody(fileParam, file.getBytes(), ContentType.APPLICATION_OCTET_STREAM, fileName);// 文件流
//解决中文乱码
// for (Map.Entry<String, Object> entry : params.entrySet()) {
// if(entry.getValue() == null) {
// continue;
// }
// // 类似浏览器表单提交,对应input的name和value
// builder.addTextBody(entry.getKey(), entry.getValue().toString());
// }
HttpEntity entity = builder.build();
httpPost.setEntity(entity);
response = httpClient.execute(httpPost);// 执行提交
HttpEntity result = response.getEntity();
httpStr = EntityUtils.toString(result, "UTF-8");
} catch (IOException e) {
e.printStackTrace();
} finally {
if (response != null) {
try {
EntityUtils.consume(response.getEntity());
} catch (IOException e) {
e.printStackTrace();
}
}
}
return httpStr;
}
/**
* 创建SSL安全连接
*
* @return
*/
private static SSLConnectionSocketFactory createSSLConnSocketFactory() {
SSLConnectionSocketFactory sslsf = null;
try {
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
return true;
}
}).build();
sslsf = new SSLConnectionSocketFactory(sslContext, new HostnameVerifier() {
@Override
public boolean verify(String arg0, SSLSession arg1) {
return true;
}
});
} catch (GeneralSecurityException e) {
e.printStackTrace();
}
return sslsf;
}
}
package com.yeejoin.amos.boot.module.ys.biz.utils;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
import com.itextpdf.text.pdf.qrcode.ErrorCorrectionLevel;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URLEncoder;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class ImageUtils {
private static final int QRCOLOR = 0x201f1f; // 二维码颜色:黑色
private static final int BGWHITE = 0xFFFFFF; //二维码背景颜色:白色
private static Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>() {
private static final long serialVersionUID = 1L;
{
put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);// 设置QR二维码的纠错级别(H为最高级别)
put(EncodeHintType.CHARACTER_SET, "utf-8");// 设置编码方式
put(EncodeHintType.MARGIN, 0);// 白边
}
};
/**
* 生成二维码图片+背景+文字描述
*
* @param codeFile 生成图地址
* @param bgImgFile 背景图地址
* @param width 二维码宽度
* @param height 二维码高度
* @param qrUrl 内容
* @param note 文字说明
* @param tui 文字说明2
* @param size 文字大小
* @param imagesX 二维码x轴方向
* @param imagesY 二维码y轴方向
* @param text1X 文字描述1x轴方向
* @param text1Y 文字描述1y轴方向
* @param text2X 文字描述2x轴方向
* @param text2Y 文字描述2y轴方向
*/
public static void creatQRCode(File codeFile, InputStream bgImgFile, Integer width, Integer height, String qrUrl,
String note, String tui, Integer size, Integer imagesX, Integer imagesY, Integer text1X, Integer text1Y
, Integer text2X, Integer text2Y) throws IOException {
try {
MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
BitMatrix bm = multiFormatWriter.encode(qrUrl, BarcodeFormat.QR_CODE, width, height, hints);
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
image.setRGB(x, y, bm.get(x, y) ? QRCOLOR : BGWHITE);
}
}
BufferedImage backgroundImage = ImageIO.read(bgImgFile);
int bgWidth = backgroundImage.getWidth();
int qrWidth = image.getWidth();
int disx = (bgWidth - qrWidth) - imagesX;
int disy = imagesY;
Graphics2D rng = backgroundImage.createGraphics();
rng.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP));
rng.drawImage(image, disx, disy, width, height, null);
// 抗锯齿
rng.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
// 文字描述参数设置
Color textColor = Color.white;
rng.setColor(textColor);
rng.drawImage(backgroundImage, 0, 0, null);
// 设置字体类型和大小(BOLD加粗/ PLAIN平常)
rng.setFont(new Font("Microsoft YaHei", Font.BOLD, size));
// 设置字体颜色
rng.setColor(Color.black);
int strWidth = rng.getFontMetrics().stringWidth(note);
// 文字1显示位置
int disx1 = (bgWidth - strWidth) - text1X;//左右
rng.drawString(note, disx1, text1Y);//上下
// 文字2显示位置
int disx2 = (bgWidth - strWidth) - text2X;//左右
rng.drawString(tui, disx2, text2Y);//上下
rng.dispose();
image = backgroundImage;
image.flush();
ImageIO.write(image, "png", codeFile);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != bgImgFile) {
bgImgFile.close();
}
}
}
/**
* 下载图片
*
* @param fileName
* @param resourceName
* @param response
*/
public static void downloadResource(String fileName, String resourceName, HttpServletResponse response) {
DataInputStream in = null;
OutputStream out = null;
InputStream fileInputStream = null;
try {
response.reset();
response.setCharacterEncoding("UTF-8");
response.setHeader("content-Type", "image/png");
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
fileInputStream = new FileInputStream(resourceName);
in = new DataInputStream(fileInputStream);
out = response.getOutputStream();
int bytes = 0;
byte[] bufferOut = new byte[1024];
while ((bytes = in.read(bufferOut)) != -1) {
out.write(bufferOut, 0, bytes);
}
} catch (Exception e) {
e.printStackTrace();
response.reset();
} finally {
try {
if (out != null) {
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if (in != null) {
in.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if (fileInputStream != null) {
fileInputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 下载压缩包
*
* @param fileName
* @param resourceName
* @param response
*/
public static void downloadResourceZip(String fileName, String resourceName, HttpServletResponse response) {
DataInputStream in = null;
OutputStream out = null;
InputStream fileInputStream = null;
try {
response.reset();
response.setCharacterEncoding("UTF-8");
response.setHeader("content-Type", "application/zip");
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
fileInputStream = new FileInputStream(resourceName);
in = new DataInputStream(fileInputStream);
out = response.getOutputStream();
int bytes = 0;
byte[] bufferOut = new byte[1024];
while ((bytes = in.read(bufferOut)) != -1) {
out.write(bufferOut, 0, bytes);
}
} catch (Exception e) {
e.printStackTrace();
response.reset();
} finally {
try {
if (out != null) {
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if (in != null) {
in.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if (fileInputStream != null) {
fileInputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 压缩文件
*
* @param srcFiles
* @param zipFile
*/
public static void zipFiles(List<File> srcFiles, File zipFile) {
try {
if (srcFiles.size() != 0) {
// 判断压缩后的文件存在不,不存在则创建
if (!zipFile.exists()) {
zipFile.createNewFile();
} else {
zipFile.delete();
zipFile.createNewFile();
}
// 创建 FileInputStream 对象
InputStream fileInputStream = null;
// 实例化 FileOutputStream 对象
FileOutputStream fileOutputStream = new FileOutputStream(zipFile);
// 实例化 ZipOutputStream 对象
ZipOutputStream zipOutputStream = new ZipOutputStream(fileOutputStream);
// 创建 ZipEntry 对象
ZipEntry zipEntry = null;
// 遍历源文件数组
// for (int i = 0; i < srcFiles.size(); i++) {
// // 将源文件数组中的当前文件读入 FileInputStream 流中
// File file = srcFiles.get(i);
// fileInputStream = new FileInputStream(file);
// // 实例化 ZipEntry 对象,源文件数组中的当前文件
// zipEntry = new ZipEntry(i + ".jpg");
// zipOutputStream.putNextEntry(zipEntry);
// // 该变量记录每次真正读的字节个数
// int len;
// // 定义每次读取的字节数组
// byte[] buffer = new byte[1024];
// while ((len = fileInputStream.read(buffer)) > 0) {
// zipOutputStream.write(buffer, 0, len);
// }
// }
for (File srcFile : srcFiles) {
fileInputStream = new FileInputStream(srcFile);
// 实例化 ZipEntry 对象,源文件数组中的当前文件
zipEntry = new ZipEntry(srcFile.getName());
zipOutputStream.putNextEntry(zipEntry);
// 该变量记录每次真正读的字节个数
int len;
// 定义每次读取的字节数组
byte[] buffer = new byte[1024];
while ((len = fileInputStream.read(buffer)) > 0) {
zipOutputStream.write(buffer, 0, len);
}
}
zipOutputStream.closeEntry();
zipOutputStream.close();
fileInputStream.close();
fileOutputStream.close();
System.out.println("下载完成");
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 删除文件夹(强制删除)
*
* @param file
*/
public static void deleteAllFilesOfDir(File file) {
if (null != file) {
if (!file.exists())
return;
if (file.isFile()) {
boolean result = file.delete();
int tryCount = 0;
while (!result && tryCount++ < 10) {
System.gc(); // 回收资源
result = file.delete();
}
}
File[] files = file.listFiles();
if (null != files) {
for (int i = 0; i < files.length; i++) {
deleteAllFilesOfDir(files[i]);
}
}
file.delete();
}
}
/**
* 生成二维码(白色背景),并将其转换成base64
*
* @param text 二维码内容
* @param width 二维码宽度
* @param height 二维码高度
* @return base64
*/
public static String generateQRCode(String text, int width, int height) {
try {
MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
BitMatrix bm = multiFormatWriter.encode(text, BarcodeFormat.QR_CODE, width, height, hints);
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
// 二维码颜色:黑色
int QRCOLOR = 0x201f1f;
//二维码背景颜色:白色
int BGWHITE = 0xFFFFFF;
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
image.setRGB(x, y, bm.get(x, y) ? QRCOLOR : BGWHITE);
}
}
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ImageIO.write(image, "png", outputStream);
return Base64.getEncoder().encodeToString(outputStream.toByteArray());
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
package com.yeejoin.amos.boot.module.ys.biz.utils;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.io.IOUtils;
import org.springframework.core.io.Resource;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import static com.alibaba.fastjson.JSON.parseArray;
public class JsonUtils {
//将json文件转化为Map<list<Map<>>>
public static Map getResourceJson(Resource resource) {
String json = null;
try {
json = IOUtils.toString(resource.getInputStream(), String.valueOf(StandardCharsets.UTF_8));
} catch (IOException e) {
throw new RuntimeException(resource + "json文件转化失败");
}
return JSONObject.parseObject(json, Map.class);
}
//将json文件转化为List<Map>
public static List<Map> getResourceList(Resource resource) {
String json = null;
try {
json = IOUtils.toString(resource.getInputStream(), String.valueOf(StandardCharsets.UTF_8));
} catch (IOException e) {
throw new RuntimeException(resource + "json文件转化失败");
}
List<Map> list = parseArray(json, Map.class);
return list;
}
}
package com.yeejoin.amos.boot.module.ys.biz.utils;
import com.itextpdf.text.Image;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import lombok.SneakyThrows;
import javax.imageio.ImageIO;
import java.awt.Font;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* @author Administrator
*/
public class PdfUtils {
@SneakyThrows
public static File addImageToPdf(String inputPdfPath, int width, int height, String imagePath) {
PdfReader reader = null;
PdfStamper stamper = null;
File outputPdfFile = null;
try {
reader = new PdfReader(inputPdfPath);
outputPdfFile = File.createTempFile("output", ".pdf");
stamper = new PdfStamper(reader, new FileOutputStream(outputPdfFile));
Image img = Image.getInstance(imagePath);
img.scaleToFit(width, height);
PdfContentByte content = stamper.getOverContent(1);
img.setAbsolutePosition(reader.getPageSize(1).getWidth() - width, reader.getPageSize(1).getHeight() - height);
content.addImage(img);
} catch (IOException | DocumentException e) {
e.printStackTrace();
} finally {
if (stamper != null) {
try {
stamper.close();
} catch (DocumentException | IOException e) {
e.printStackTrace();
}
}
if (reader != null) {
reader.close();
}
}
return outputPdfFile;
}
public static void generatorImageWithText(File imageFile, int width, int height, String text, Color color) {
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = image.createGraphics();
// 设置背景为透明
image = g2d.getDeviceConfiguration().createCompatibleImage(width, height, Transparency.TRANSLUCENT);
g2d.dispose();
g2d = image.createGraphics();
// 设置抗锯齿
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
// 写入字符串
Font font = new Font("Microsoft YaHei", Font.BOLD, 20);
g2d.setFont(font);
FontMetrics fm = g2d.getFontMetrics();
int textWidth = fm.stringWidth(text);
int textHeight = fm.getHeight();
int x = (width - textWidth) / 2;
int y = (height - textHeight) / 2 + fm.getAscent();
g2d.setColor(color);
g2d.drawString(text, x, y);
g2d.dispose();
try {
ImageIO.write(image, "PNG", imageFile);
} catch (IOException e) {
e.printStackTrace();
}
}
@SneakyThrows
public static File addFullPageWatermark(String src, String watermarkText) {
PdfReader reader = null;
PdfStamper stamper = null;
File outputPdfFile = null;
try {
outputPdfFile = File.createTempFile("output", ".pdf");
reader = new PdfReader(src);
stamper = new PdfStamper(reader, new FileOutputStream(outputPdfFile));
PdfGState gs = new PdfGState();
// 设置透明度为0.1
gs.setFillOpacity(0.5f);
int n = reader.getNumberOfPages();
// 创建一个BaseFont实例,用于水印文本
BaseFont bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);
// 设置水印文本大小
float fontSize = 40;
// 设置水印文本的间距、根据字体大小调整行间距
float lineSpacing = fontSize + 2;
// 设置水印文本的起始位置
float x = 0;
// 遍历PDF的每一页
for (int i = 1; i <= n; i++) {
PdfContentByte over = stamper.getOverContent(i);
// 获取页面尺寸
Rectangle pageSize = reader.getPageSizeWithRotation(i);
float pageWidth = pageSize.getWidth();
float pageHeight = pageSize.getHeight();
// 从页面底部开始
float y = pageHeight;
// 计算文本宽度
float textWidth = bf.getWidthPoint(watermarkText, fontSize);
// 添加水印文本到页面
while (y > 0) {
// 文本从页面左侧开始
x = 60;
while (x < pageWidth) {
over.beginText();
over.setFontAndSize(bf, fontSize);
//水印颜色
over.setColorFill(BaseColor.LIGHT_GRAY);
over.setGState(gs);
// 设置文本渲染模式为填充,使文本不可选择
over.setTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_FILL);
over.setTextMatrix(x, y);
over.showTextAligned(Element.ALIGN_CENTER, watermarkText, x, y, 45);
over.endText();
// 更新x坐标以跳过当前行的文本宽度
x += textWidth + lineSpacing;
}
// 当一行文本添加完毕后,减少y坐标以开始新的一行
y -= (lineSpacing + 50);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (stamper != null) {
stamper.close();
}
if (reader != null) {
reader.close();
}
}
return outputPdfFile;
}
}
package com.yeejoin.amos.boot.module.ys.biz.utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
/**
* @program: redis工具类
* @description:
* @author: duanwei
* @create: 2019-04-12 14:16
**/
@Component
public class RedisUtil {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
/**
* 指定缓存失效时间
*
* @param key 键
* @param time 时间(秒)
* @return
*/
public boolean expire(String key, long time) {
try {
if (time > 0) {
redisTemplate.expire(key, time, TimeUnit.SECONDS);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 根据key 获取过期时间
*
* @param key 键 不能为null
* @return 时间(秒) 返回0代表为永久有效
*/
public long getExpire(String key) {
return redisTemplate.getExpire(key, TimeUnit.SECONDS);
}
/**
* 判断key是否存在
*
* @param key 键
* @return true 存在 false不存在
*/
public boolean hasKey(String key) {
try {
return redisTemplate.hasKey(key);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 删除缓存
*
* @param key 可以传一个值 或多个
*/
@SuppressWarnings("unchecked")
public void del(String... key) {
if (key != null && key.length > 0) {
if (key.length == 1) {
redisTemplate.delete(key[0]);
} else {
redisTemplate.delete(CollectionUtils.arrayToList(key));
}
}
}
//============================String=============================
/**
* 普通缓存获取
*
* @param key 键
* @return 值
*/
public Object get(String key) {
return key == null ? null : redisTemplate.opsForValue().get(key);
}
/**
* 普通缓存放入
*
* @param key 键
* @param value 值
* @return true成功 false失败
*/
public boolean set(String key, Object value) {
try {
redisTemplate.opsForValue().set(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 普通缓存放入并设置时间
*
* @param key 键
* @param value 值
* @param time 时间(秒) time要大于0 如果time小于等于0 将设置无限期
* @return true成功 false 失败
*/
public boolean set(String key, Object value, long time) {
try {
if (time > 0) {
redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
} else {
set(key, value);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 递增
*
* @param key 键
* @param delta 要增加几(大于0)
* @return
*/
public long incr(String key, long delta) {
if (delta < 0) {
throw new RuntimeException("递增因子必须大于0");
}
return redisTemplate.opsForValue().increment(key, delta);
}
/**
* 递减
*
* @param key 键
* @param delta 要减少几(小于0)
* @return
*/
public long decr(String key, long delta) {
if (delta < 0) {
throw new RuntimeException("递减因子必须大于0");
}
return redisTemplate.opsForValue().increment(key, -delta);
}
//================================Map=================================
/**
* HashGet
*
* @param key 键 不能为null
* @param item 项 不能为null
* @return 值
*/
public Object hget(String key, String item) {
return redisTemplate.opsForHash().get(key, item);
}
/**
* 获取hashKey对应的所有键值
*
* @param key 键
* @return 对应的多个键值
*/
public Map<Object, Object> hmget(String key) {
return redisTemplate.opsForHash().entries(key);
}
/**
* HashSet
*
* @param key 键
* @param map 对应多个键值
* @return true 成功 false 失败
*/
public boolean hmset(String key, Map<String, Object> map) {
try {
redisTemplate.opsForHash().putAll(key, map);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* HashSet 并设置时间
*
* @param key 键
* @param map 对应多个键值
* @param time 时间(秒)
* @return true成功 false失败
*/
public boolean hmset(String key, Map<String, Object> map, long time) {
try {
redisTemplate.opsForHash().putAll(key, map);
if (time > 0) {
expire(key, time);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 向一张hash表中放入数据,如果不存在将创建
*
* @param key 键
* @param item 项
* @param value 值
* @return true 成功 false失败
*/
public boolean hset(String key, String item, Object value) {
try {
redisTemplate.opsForHash().put(key, item, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 向一张hash表中放入数据,如果不存在将创建
*
* @param key 键
* @param item 项
* @param value 值
* @param time 时间(秒) 注意:如果已存在的hash表有时间,这里将会替换原有的时间
* @return true 成功 false失败
*/
public boolean hset(String key, String item, Object value, long time) {
try {
redisTemplate.opsForHash().put(key, item, value);
if (time > 0) {
expire(key, time);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 删除hash表中的值
*
* @param key 键 不能为null
* @param item 项 可以使多个 不能为null
*/
public void hdel(String key, Object... item) {
redisTemplate.opsForHash().delete(key, item);
}
/**
* 判断hash表中是否有该项的值
*
* @param key 键 不能为null
* @param item 项 不能为null
* @return true 存在 false不存在
*/
public boolean hHasKey(String key, String item) {
return redisTemplate.opsForHash().hasKey(key, item);
}
/**
* hash递增 如果不存在,就会创建一个 并把新增后的值返回
*
* @param key 键
* @param item 项
* @param by 要增加几(大于0)
* @return
*/
public double hincr(String key, String item, double by) {
return redisTemplate.opsForHash().increment(key, item, by);
}
/**
* hash递减
*
* @param key 键
* @param item 项
* @param by 要减少记(小于0)
* @return
*/
public double hdecr(String key, String item, double by) {
return redisTemplate.opsForHash().increment(key, item, -by);
}
//============================set=============================
/**
* 根据key获取Set中的所有值
*
* @param key 键
* @return
*/
public Set<Object> sGet(String key) {
try {
return redisTemplate.opsForSet().members(key);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 根据value从一个set中查询,是否存在
*
* @param key 键
* @param value 值
* @return true 存在 false不存在
*/
public boolean sHasKey(String key, Object value) {
try {
return redisTemplate.opsForSet().isMember(key, value);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 将数据放入set缓存
*
* @param key 键
* @param values 值 可以是多个
* @return 成功个数
*/
public long sSet(String key, Object... values) {
try {
return redisTemplate.opsForSet().add(key, values);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* 将set数据放入缓存
*
* @param key 键
* @param time 时间(秒)
* @param values 值 可以是多个
* @return 成功个数
*/
public long sSetAndTime(String key, long time, Object... values) {
try {
Long count = redisTemplate.opsForSet().add(key, values);
if (time > 0) {
expire(key, time);
}
return count;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* 获取set缓存的长度
*
* @param key 键
* @return
*/
public long sGetSetSize(String key) {
try {
return redisTemplate.opsForSet().size(key);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* 移除值为value的
*
* @param key 键
* @param values 值 可以是多个
* @return 移除的个数
*/
public long setRemove(String key, Object... values) {
try {
Long count = redisTemplate.opsForSet().remove(key, values);
return count;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
//===============================list=================================
/**
* 获取list缓存的内容
*
* @param key 键
* @param start 开始
* @param end 结束 0 到 -1代表所有值
* @return
*/
public List<Object> lGet(String key, long start, long end) {
try {
return redisTemplate.opsForList().range(key, start, end);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 获取list缓存的长度
*
* @param key 键
* @return
*/
public long lGetListSize(String key) {
try {
return redisTemplate.opsForList().size(key);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* 通过索引 获取list中的值
*
* @param key 键
* @param index 索引 index>=0时, 0 表头,1 第二个元素,依次类推;index<0时,-1,表尾,-2倒数第二个元素,依次类推
* @return
*/
public Object lGetIndex(String key, long index) {
try {
return redisTemplate.opsForList().index(key, index);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 将list放入缓存
*
* @param key 键
* @param value 值
* @return
*/
public boolean lSet(String key, Object value) {
try {
redisTemplate.opsForList().rightPush(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 将list放入缓存
*
* @param key 键
* @param value 值
* @param time 时间(秒)
* @return
*/
public boolean lSet(String key, Object value, long time) {
try {
redisTemplate.opsForList().rightPush(key, value);
if (time > 0) {
expire(key, time);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 将list放入缓存
*
* @param key 键
* @param value 值
* @return
*/
public boolean lSet(String key, List<Object> value) {
try {
redisTemplate.opsForList().rightPushAll(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 将list放入缓存
*
* @param key 键
* @param value 值
* @param time 时间(秒)
* @return
*/
public boolean lSet(String key, List<Object> value, long time) {
try {
redisTemplate.opsForList().rightPushAll(key, value);
if (time > 0) {
expire(key, time);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 根据索引修改list中的某条数据
*
* @param key 键
* @param index 索引
* @param value 值
* @return
*/
public boolean lUpdateIndex(String key, long index, Object value) {
try {
redisTemplate.opsForList().set(key, index, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 移除N个值为value
*
* @param key 键
* @param count 移除多少个
* @param value 值
* @return 移除的个数
*/
public long lRemove(String key, long count, Object value) {
try {
Long remove = redisTemplate.opsForList().remove(key, count, value);
return remove;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
}
package com.yeejoin.amos.boot.module.ys.biz.utils;
import com.baomidou.mybatisplus.core.injector.AbstractMethod;
import com.baomidou.mybatisplus.core.injector.DefaultSqlInjector;
import com.baomidou.mybatisplus.extension.injector.methods.additional.InsertBatchSomeColumn;
import org.springframework.stereotype.Component;
import java.util.List;
/**
* @author DELL
*/
@Component
public class SqlInjectorUtils extends DefaultSqlInjector {
@Override
public List<AbstractMethod> getMethodList(Class<?> mapperClass) {
List<AbstractMethod> methodList = super.getMethodList(mapperClass);
// 添加批量插入方法
methodList.add(new InsertBatchSomeColumn());
return methodList;
}
}
package com.yeejoin.amos.boot.module.ys.biz.utils;
import com.aspose.words.Document;
import com.aspose.words.License;
import com.aspose.words.SaveFormat;
import com.yeejoin.amos.boot.module.ys.api.dto.ByteArrayMultipartFile;
import com.yeejoin.amos.component.feign.model.FeignClientResult;
import com.yeejoin.amos.feign.systemctl.Systemctl;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import org.typroject.tyboot.core.restful.exception.instance.BadRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;
@Slf4j
public class WordTemplateUtils {
public static final String BASE_PACKAGE_PATH = "/templates";
private static WordTemplateUtils wordTemplateUtils;
private final Configuration configuration;
private WordTemplateUtils() {
configuration = new Configuration(Configuration.VERSION_2_3_23);
}
public static synchronized WordTemplateUtils getInstance() {
if (wordTemplateUtils == null) {
wordTemplateUtils = new WordTemplateUtils();
}
return wordTemplateUtils;
}
/**
* 创建doc并写入内容
*
* @param templatePath doc模板文件路径
* @param dataMap 内容
* @param template 模板
* @return doc文件
*/
public static File createDoc(String templatePath, Map<String, ?> dataMap, Template template) throws TemplateException, IOException {
// templatePath在后缀之前加上UUID是为了防止并发时多个线程使用同一个模板文件而导致生成的Word文档内容不一致
int i = templatePath.lastIndexOf(".");
templatePath = UUID.randomUUID() + templatePath.substring(i);
if (templatePath.endsWith(".ftl")) {
templatePath = templatePath.replace(".ftl", ".doc");
}
File docFile = new File(templatePath);
try (
// 这个地方不能使用FileWriter因为需要指定编码类型否则生成的Word文档会因为有无法识别的编码而无法打开
Writer writer = new OutputStreamWriter(Files.newOutputStream(docFile.toPath()), StandardCharsets.UTF_8)
) {
template.process(escapeSpecialCharacters(dataMap), writer);
}
return docFile;
}
public File fillAndConvertDocFile(String templatePath, String targetFileName, Map<String, ?> map, int saveFormat) throws Exception {
// 指定模板所在包路径
configuration.setClassForTemplateLoading(this.getClass(), BASE_PACKAGE_PATH);
// 获取模板, 生成Word文档
Template freemarkerTemplate = configuration.getTemplate(templatePath, "UTF-8");
File docFile = createDoc(templatePath, map, freemarkerTemplate);
// 转换Word文档
File converedFile = converDocFile(docFile.getAbsolutePath(), targetFileName, saveFormat);
// 删除临时文件
Files.deleteIfExists(docFile.toPath());
return converedFile;
}
/**
* word转换
*
* @param docPath word文件路径
* @param targetPath 转换后文件路径
* @param saveFormat 目标文件类型 取自 com.aspose.words.SaveFormat
*/
private File converDocFile(String docPath, String targetPath, int saveFormat) throws Exception {
// 验证License 若不验证则转化出的pdf文档会有水印产生
if (!getLicense()) {
throw new RuntimeException("验证License失败");
}
if (StringUtils.isEmpty(docPath)) {
throw new FileNotFoundException("文档文件不存在");
}
try (
InputStream inputStream = Files.newInputStream(Paths.get(docPath));
OutputStream outputStream = Files.newOutputStream(Paths.get(targetPath));
) {
File targetFile = new File(targetPath);
Document doc = new Document(inputStream);
doc.save(outputStream, saveFormat);
return targetFile;
}
}
/**
* 获取License
*
* @return boolean
*/
private boolean getLicense() {
boolean result = false;
try {
String s = "<License><Data><Products><Product>Aspose.Total for Java</Product><Product>Aspose.Words for Java</Product></Products><EditionType>Enterprise</EditionType><SubscriptionExpiry>20991231</SubscriptionExpiry><LicenseExpiry>20991231</LicenseExpiry><SerialNumber>8bfe198c-7f0c-4ef8-8ff0-acc3237bf0d7</SerialNumber></Data><Signature>sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=</Signature></License>";
ByteArrayInputStream is = new ByteArrayInputStream(s.getBytes());
License license = new License();
license.setLicense(is);
result = true;
} catch (Exception e) {
log.error("获取License失败", e);
}
return result;
}
public static String templateToPdf(String pdfName, String wordPath, Map<String, Object> placeholders) {
// word转pdf
File pdfFile;
try {
pdfFile = wordToPdf(pdfName, wordPath, placeholders);
} catch (Exception e) {
throw new RuntimeException(e);
}
// 上传pdf至文件服务器
String url = uploadFile(pdfFile);
// 删除临时文件
try {
Files.deleteIfExists(pdfFile.toPath());
} catch (IOException e) {
log.error("删除临时文件失败:{}", e);
}
return url;
}
public static void templateToPdfDownload(String pdfName, String wordPath, Map<String, Object> placeholders, HttpServletResponse response) {
// word转pdf
File pdfFile;
try {
pdfFile = wordToPdf(pdfName, wordPath, placeholders);
} catch (Exception e) {
log.error("模板转pdf失败:", e);
throw new BadRequest("模板转pdf失败");
}
try {
byte[] bytes = file2byte(pdfFile);
String docTitle = pdfFile.getName();
FileExporter.exportFile(FileExporter.FileType.valueOf("pdf"), docTitle, bytes, response);
} catch (Exception e) {
log.error("文档导出失败:", e);
} finally {
try {
Files.deleteIfExists(pdfFile.toPath());
} catch (Exception e) {
log.error("文件找不到,删除失败:", e);
}
}
}
private static byte[] file2byte(File file) {
try {
FileInputStream in = new FileInputStream(file);
//当文件没有结束时,每次读取一个字节显示
byte[] data = new byte[in.available()];
in.read(data);
in.close();
return data;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 上传文件至文件服务器
*
* @param file 文件
*/
private static String uploadFile(File file) {
Assert.notNull(file, "文件不能为空");
MultipartFile multipartFile = new ByteArrayMultipartFile("file", "file.pdf", "application/pdf", file2byte(file));
FeignClientResult<Map<String, String>> result = Systemctl.fileStorageClient.updateCommonFile(multipartFile);
String urlString = "";
if (result != null) {
for (String s : result.getResult().keySet()) {
urlString = s;
}
}
return urlString;
}
/**
* word 转 pdf
*
* @param wordPath word文件路径
*/
private static File wordToPdf(String pdfName, String wordPath, Map<String, Object> placeholders) throws Exception {
Assert.hasText(wordPath, "word文件路径不能为空");
WordTemplateUtils instance = WordTemplateUtils.getInstance();
return instance.fillAndConvertDocFile(wordPath, pdfName, placeholders, SaveFormat.PDF);
}
/**
* 下载填充模板的字段,特殊符号转义
*/
public static Map<String, Object> escapeSpecialCharacters(Map<String, ?> inputMap) {
Map<String, Object> escapedMap = new HashMap<>();
for (Map.Entry<String, ?> entry : inputMap.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
if (value instanceof String) {
escapedMap.put(key, escapeValue((String) value));
} else if (value instanceof Map) {
escapedMap.put(key, escapeSpecialCharacters((Map<String, Object>) value));
} else if (value instanceof List) {
escapedMap.put(key, escapeList((List<?>) value));
} else {
escapedMap.put(key, value);
}
}
return escapedMap;
}
private static List<Object> escapeList(List<?> inputList) {
List<Object> escapedList = new ArrayList<>();
for (Object value : inputList) {
if (value instanceof String) {
escapedList.add(escapeValue((String) value));
} else if (value instanceof Map) {
escapedList.add(escapeSpecialCharacters((Map<String, Object>) value));
} else if (value instanceof List) {
escapedList.add(escapeList((List<?>) value));
} else {
escapedList.add(value);
}
}
return escapedList;
}
private static String escapeValue(String value) {
if (value == null) {
return null;
}
return value.replace("&", "&amp;")
.replace("<", "&lt;")
.replace(">", "&gt;")
.replace("\"", "&quot;")
.replace("'", "&apos;")
.replace("(", "&#40;")
.replace(")", "&#41;");
}
}
spring.datasource.url=jdbc:vastbase://${POSTGRESQL_IP_port}/${POSTGRESQL_NAME}?currentSchema=${TZS_IDX_BIZ_DATABASE}&serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8&autoReconnect=true&useSSL=false&noAccessToProcedureBodies=true&allowMultiQueries=true
spring.datasource.username=${POSTGRESQL_USER}
spring.datasource.password=${POSTGRESQL_PASSWORD}
#注册中心地址
eureka.client.service-url.defaultZone =http://admin:a1234560@192.168.249.13:10001/eureka/,http://admin:a1234560@192.168.249.139:10001/eureka/
eureka.instance.prefer-ip-address=true
eureka.instance.ip-address = 192.168.249.139
management.endpoint.health.show-details=always
management.endpoints.web.exposure.include=*
eureka.instance.health-check-url=http://elevator:${server.port}${server.servlet.context-path}/actuator/health
eureka.instance.metadata-map.management.context-path=${server.servlet.context-path}/actuator
eureka.instance.status-page-url=http://elevator:${server.port}${server.servlet.context-path}/actuator/info
eureka.instance.metadata-map.management.api-docs=http://elevator:${server.port}${server.servlet.context-path}/doc.html
## ES properties:
spring.elasticsearch.rest.uris=${ELASTICSEARCH_REST_URIS}
elasticsearch.username=${ELASTICSEARCH_USERNAME}
elasticsearch.password= ${ELASTICSEARCH_PASSWORD}
## unit(h)
alertcall.es.synchrony.time=48
#redis properties:
spring.redis.cluster.nodes=${REDIS_CLUSTER_NODES}
spring.redis.password=${REDIS_PASSWORD}
spring.redis.cluster.max-redirects=3
spring.redis.timeout=10000
spring.redis.lettuce.cluster.refresh.adaptive=true
spring.redis.lettuce.cluster.refresh.period=2000
spring.redis.mode=cluster
#springboot指标显示器不使用默认的,使用自定义的MyRedisHealthIndicator
management.health.redis.enabled=false
##emqx
emqx.clean-session=true
emqx.client-id=${spring.application.name}-${random.int[1024,65536]}
emqx.broker=${EMQX_BROKER}
emqx.client-user-name=${EMQX_USER}
emqx.client-password=${EMQX_PASSWORD}
tzs.cti.appkey=0a1b1cf1-a55b-447a-d275-02931f13b2fa
tzs.cti.secretkey=cae7c0f8-a7b8-9876-d69b-3eba8262898a
tzs.cti.url=http://192.168.249.178:8000
##wechatToken
tzs.wechat.token=yeejoin_2021
##wechatTicketUrl
tzs.wechat.ticketurl=https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=
#tzs.wechat.tempId.kr=rjW8x9rRitIpa21Jekyx2nzBzpJy7tycssCXSN4YhWw
tzs.wechat.tempId.kr=bxchKYhYW7aHbGKM2pVyR_yY2-bG4sRMNU3ZRQbMKYM
tzs.wechat.url.kr=tzs.yeeamos.com/persondetail.html
#tzs.wechat.tempId.wx=ofBIZS8Bup9s0zKbrGa8BfhVhS18H_hyC_OYXuBN6hI
tzs.wechat.tempId.wx=rags-expfNSBB-h2WenuBI2c6pCEndH4uwTtOqlHqDM
tzs.wechat.url.wx=tzs.yeeamos.com/repairPersondetail.html
#tzs.wechat.tempId.ts=Kr7lcV8g4g_lgyW_RpwnNgw_HDxxRuVx759EoFWrIfU
tzs.wechat.tempId.ts=VWqgY-lXFt4dg2EL4pLjfDCBAU49Z0mRxVaQhAMMW8Q
tzs.wechat.url.ts=tzs.yeeamos.com/taskComplaintDetail.html
mqtt.topic.task.newtask=tzs-task-newtask
mqtt.topic.task.personinfo=tzs-task-personinfo
mqtt.topic.elevator.push=/tzs/tcb_elevator
mqtt.topic.alertInfo.push=/tzs/tcb_alertInfo
mqtt.topic.alertReport.push=/tzs/tcb_alertReport
mqtt.topic.alertHeart.push=/tzs/tcb_alertHeart
mqtt.topic.alertMatrix.push=/tzs/tcb_alertMatrix
mqtt.topic.cti.push=/cti/record
cti.user.name=tzs_cti
cti.user.pwd=a1234567
flc.sms.tempCode=SMS_TZS_0001
## 预警通知模板id
tzs.wechat.tempId.warning=-pHsHLIjW8j-_AemoZycf6Dmu6iYc-YWWaJ0cAPGeUY
##督查整改通知
tzs.wechat.tempId.supervise=P5XGbszS2Pc6kynvGjzPpZ--ikAwDZo6O7WdJ2EUxtE
## 公众号测试用户id(平台userId)
tzs.wechat.test.userId=3413513
fileserver.domain=https://rpm.yeeamos.com:8888/
org.filter.group.seq=1564150103147573249
duty.seats.role.ids=1585956200472674305,1585956257590706177
## 规则配置 properties:
rule.definition.load=false
##rule.definition.model-package=com.yeejoin.amos.boot.module.jcs.api.dto
rule.definition.default-agency=tzs
rule.definition.local-ip=192.168.249.139
tzs.auth.user.photo=/public/common/userPic.png
minio.url.path=${MINIO_FILESERVER_DOMAIN}/
#### 管理员变更机器人账号
tzs.admin.name=tzs_robot
tzs.admin.pwd=a1234567
##小程序appid
tzs.WxApp.appId=wx48a1b1915b10d14b
tzs.WxApp.secret=ac4f4a9d3c97676badb70c19a2f37b16
tzs.WxApp.grant-type=authorization_code
#气瓶充装信息定时同步至es
tzs.cylinder.fill.cron=0 0 12 * * ?
#气瓶基本信息定时同步至es
tzs.cylinder.info.cron=0 0 1 * * ?
outSystem.user.password=a1234560
amos.system.user.app-key=AMOS_STUDIO
amos.system.user.product=STUDIO_APP_WEB
##生成监管码前缀域名
regulatory_code_prefix=https://nav.sspai.top/tzs?code=
#DB properties:
spring.datasource.url=jdbc:postgresql://172.16.10.243:5432/tzs_amos_tzs_biz_init?currentSchema=amos_tzs_biz&allowMultiQueries=true
spring.datasource.username=admin
spring.datasource.password=Yeejoin@2023
eureka.client.service-url.defaultZone=http://172.16.10.243:10001/eureka/
eureka.instance.prefer-ip-address=true
management.endpoint.health.show-details=always
management.endpoints.web.exposure.include=*
eureka.instance.health-check-url=http://172.16.3.68:${server.port}${server.servlet.context-path}/actuator/health
eureka.instance.metadata-map.management.context-path=${server.servlet.context-path}/actuator
eureka.instance.status-page-url=http://172.16.3.68:${server.port}${server.servlet.context-path}/actuator/info
eureka.instance.metadata-map.management.api-docs=http://172.16.3.68:${server.port}${server.servlet.context-path}/doc.html
eureka.instance.ip-address=172.16.3.68
## ES properties:
elasticsearch.username=elastic
elasticsearch.password=a123456
spring.elasticsearch.rest.uris=http://172.16.10.243:9200
## unit(h)
alertcall.es.synchrony.time=48
#redis properties:
spring.redis.database=1
spring.redis.host=172.16.10.243
spring.redis.port=6379
spring.redis.password=yeejoin@2020
spring.redis.lettuce.pool.max-active=200
spring.redis.lettuce.pool.max-wait=-1
spring.redis.lettuce.pool.max-idle=10
spring.redis.lettuce.pool.min-idle=0
## emqx properties:
emqx.clean-session=true
emqx.client-id=${spring.application.name}-${random.int[1024,65536]}
emqx.broker=tcp://172.16.10.243:2883
emqx.client-user-name=super
emqx.client-password=123456
emqx.keepAliveInterval=1000
tzs.cti.appkey=4e805006-3fef-ae43-3915-a153731007c4
tzs.cti.secretkey=7bd29115-99ee-4f7d-1fb1-7c4719d5f43a
tzs.cti.url=http://36.41.172.83:8000
##wechatToken
tzs.wechat.token=yeejoin_2021
##wechatTicketUrl
tzs.wechat.ticketurl=https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=
#tzs.wechat.tempId.kr=rjW8x9rRitIpa21Jekyx2nzBzpJy7tycssCXSN4YhWw
tzs.wechat.tempId.kr=bxchKYhYW7aHbGKM2pVyR_yY2-bG4sRMNU3ZRQbMKYM
tzs.wechat.url.kr=tzs.yeeamos.com/persondetail.html
#tzs.wechat.tempId.wx=ofBIZS8Bup9s0zKbrGa8BfhVhS18H_hyC_OYXuBN6hI
tzs.wechat.tempId.wx=rags-expfNSBB-h2WenuBI2c6pCEndH4uwTtOqlHqDM
tzs.wechat.url.wx=tzs.yeeamos.com/repairPersondetail.html
#tzs.wechat.tempId.ts=Kr7lcV8g4g_lgyW_RpwnNgw_HDxxRuVx759EoFWrIfU
tzs.wechat.tempId.ts=VWqgY-lXFt4dg2EL4pLjfDCBAU49Z0mRxVaQhAMMW8Q
tzs.wechat.url.ts=tzs.yeeamos.com/taskComplaintDetail.html
mqtt.topic.task.newtask=tzs-task-newtask
mqtt.topic.task.personinfo=tzs-task-personinfo
mqtt.topic.elevator.push=/tzs/tcb_elevator
mqtt.topic.alertInfo.push=/tzs/tcb_alertInfo
mqtt.topic.alertReport.push=/tzs/tcb_alertReport
mqtt.topic.alertHeart.push=/tzs/tcb_alertHeart
mqtt.topic.alertMatrix.push=/tzs/tcb_alertMatrix
mqtt.topic.cti.push=/cti/record
cti.user.name=tzs_cti
cti.user.pwd=a1234567
flc.sms.tempCode=SMS_TZS_0001
## ??????id
tzs.wechat.tempId.warning=-pHsHLIjW8j-_AemoZycf6Dmu6iYc-YWWaJ0cAPGeUY
##??????
tzs.wechat.tempId.supervise=P5XGbszS2Pc6kynvGjzPpZ--ikAwDZo6O7WdJ2EUxtE
## ???????id???userId?
tzs.wechat.test.userId=3413513
##new properties
org.filter.group.seq=1564150103147573249
fileserver.domain=http://172.16.10.243:19000/
log.level=INFO
duty.seats.role.ids=1585956200472674305,1585956257590706177
## ???? properties:
rule.definition.load=false
##rule.definition.model-package=com.yeejoin.amos.boot.module.jcs.api.dto
rule.definition.default-agency=tzs
rule.definition.local-ip=172.16.10.243
# minio ??
minio.endpoint=http://172.16.10.243:9000
minio.accessKey=root
minio.secretKey=Yeejoin@2020
## \u7279\u79CD\u8BBE\u5907\u57DF\u540D
tzs.domain=http://sxtzsb.sxsei.com
outSystem.user.password=a1234560
amos.system.user.app-key=AMOS_STUDIO
amos.system.user.product=STUDIO_APP_WEB
#Seata Config
seata.tx-service-group= tzs-seata
seata.service.grouplist.tzs-seata=172.16.10.243:8091
\ No newline at end of file
spring.application.name=TZS-YS
server.servlet.context-path=/ys
server.port=11008
spring.profiles.active=dev
spring.feign.client.config.default.clockSkew=0m
spring.jackson.time-zone=GMT+8
spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
logging.config=classpath:logback-${spring.profiles.active}.xml
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
logging.level.net.javacrumbs.shedlock=DEBUG
##liquibase
spring.liquibase.change-log = classpath:/db/changelog/changelog-master.xml
spring.liquibase.enabled= false
feign.client.config.default.connect-timeout=30000
feign.client.config.default.read-timeout=30000
## eureka properties:
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
eureka.instance.metadata-map.management.api-docs=http://localhost:${server.port}${server.servlet.context-path}/doc.html
#DB properties:
spring.datasource.driver-class-name=org.postgresql.Driver
spring.datasource.type=com.zaxxer.hikari.HikariDataSource
spring.datasource.hikari.minimum-idle=10
spring.datasource.hikari.maximum-pool-size=25
spring.datasource.hikari.auto-commit=true
spring.datasource.hikari.idle-timeout=30000
spring.datasource.hikari.pool-name=DatebookHikariCP
spring.datasource.hikari.max-lifetime=120000
spring.datasource.hikari.connection-timeout=30000
spring.datasource.hikari.connection-test-query=SELECT 1
spring.datasource.schema=amos_tzs_biz
spring.main.allow-bean-definition-overriding=true
iot.fegin.name=AMOS-API-IOT
equip.fegin.name=AMOS-EQUIPMANAGE
supervision.feign.name = AMOS-SUPERVISION-API
security.systemctl.name=AMOS-API-SYSTEMCTL
jcs.company.topic.add=jcs/company/topic/add
jcs.company.topic.delete=jcs/company/topic/delete
## \uFFFD\u8C78\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uD94E\uDE33\uFFFD\uFFFD\uFFFD\uFFFD\u0161\uFFFD\uFFFD\u3CA5\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u58E9
control.fegin.name=JCS-API-CONTROL
## redis\uFFFD\uFFFD\u02B1\u02B1\uFFFD\uFFFD
redis.cache.failure.time=10800
failure.work.flow.processDefinitionKey=malfunction_repair
video.fegin.name=video
latentDanger.feign.name=AMOS-LATENT-DANGER
Knowledgebase.fegin.name=AMOS-API-KNOWLEDGEBASE
## \uFFFD\u8C78\uFFFD\uFFFD\u05AA\uFFFD\uFFFD\uFFFD\uFFFDv1
inform.work.flow.processDefinitionKey=equipment_inform_process_v1
## \uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u052E\uFFFD\uFFFD\uFFFD\u03F2\uFFFDID
fire-rescue=1432549862557130753
tzs.cti.appkey=4e805006-3fef-ae43-3915-a153731007c4
tzs.cti.secretkey=7bd29115-99ee-4f7d-1fb1-7c4719d5f43a
tzs.wechat.url=https://api.weixin.qq.com
tzs.wechat.appid=wx79aca5bb1cb4af92
tzs.wechat.secret=f3a12323ba731d282c3d4698c27c3e97
##wechatToken
tzs.wechat.token=yeejoin_2021
##wechatTicketUrl
tzs.wechat.ticketurl=https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=
#tzs.wechat.tempId.kr=rjW8x9rRitIpa21Jekyx2nzBzpJy7tycssCXSN4YhWw
tzs.wechat.tempId.kr=bxchKYhYW7aHbGKM2pVyR_yY2-bG4sRMNU3ZRQbMKYM
tzs.wechat.url.kr=tzs.yeeamos.com/persondetail.html
#tzs.wechat.tempId.wx=ofBIZS8Bup9s0zKbrGa8BfhVhS18H_hyC_OYXuBN6hI
tzs.wechat.tempId.wx=rags-expfNSBB-h2WenuBI2c6pCEndH4uwTtOqlHqDM
tzs.wechat.url.wx=tzs.yeeamos.com/repairPersondetail.html
#tzs.wechat.tempId.ts=Kr7lcV8g4g_lgyW_RpwnNgw_HDxxRuVx759EoFWrIfU
tzs.wechat.tempId.ts=VWqgY-lXFt4dg2EL4pLjfDCBAU49Z0mRxVaQhAMMW8Q
tzs.wechat.url.ts=tzs.yeeamos.com/taskComplaintDetail.html
mqtt.topic.task.newtask=tzs-task-newtask
mqtt.topic.task.personinfo=tzs-task-personinfo
mqtt.topic.elevator.push=/tzs/tcb_elevator
mqtt.topic.alertInfo.push=/tzs/tcb_alertInfo
mqtt.topic.alertReport.push=/tzs/tcb_alertReport
mqtt.topic.alertHeart.push=/tzs/tcb_alertHeart
mqtt.topic.alertMatrix.push=/tzs/tcb_alertMatrix
mqtt.topic.cti.push=/cti/record
mqtt.topic.cyl.warning.push=/tzs/cyl_cyl_warning
cti.user.name=tzs_cti
cti.user.pwd=a1234567
flc.sms.tempCode=SMS_TZS_0001
### \u7BA1\u7406\u5458\u53D8\u66F4\u673A\u5668\u4EBA\u8D26\u53F7
#tzs.admin.name=tzs_admin
## \u0524\uFFFD\uFFFD\u0368\u05AA\u0123\uFFFD\uFFFDid
tzs.wechat.tempId.warning=-pHsHLIjW8j-_AemoZycf6Dmu6iYc-YWWaJ0cAPGeUY
##\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u0368\u05AA
tzs.wechat.tempId.supervise=P5XGbszS2Pc6kynvGjzPpZ--ikAwDZo6O7WdJ2EUxtE
## \uFFFD\uFFFD\uFFFD\u06BA\u0172\uFFFD\uFFFD\uFFFD\uFFFD\u00FB\uFFFDid\uFFFD\uFFFD\u01BD\u0328userId\uFFFD\uFFFD
tzs.wechat.test.userId=3393279
amos.secret.key=qazknife4j.production=false
knife4j.production=false
knife4j.enable=true
knife4j.basic.enable=true
knife4j.basic.username=admin
knife4j.basic.password=a1234560
spring.security.user.name=admin
spring.security.user.password=a1234560
spring.security.user.roles=SBA_ADMIN
## \u540E\u53F0\u6267\u884C\u673A\u5668\u4EBA\u8D26\u53F7\u914D\u7F6E
amos.system.user.user-name=jyjg04
amos.system.user.password=a1234560
amos.system.user.app-key=AMOS_STUDIO
amos.system.user.product=AMOS_STUDIO_WEB
## ??????????????topic
amos.operation.log=$share/${spring.application.name}//amos/operation/log
amos.agency.code=tzs
## ?????orgCode
regulator.unit.code=50
# \u82E5tzs\u548Cugp\u4E00\u8D77\uFF0C\u5219true
is.ugp=false
#\u5DE5\u4F5C\u53F0\u7528\u6237\u7EDF\u4E00\u663E\u793A\u5934\u50CF
tzs.auth.user.photo=/public/common/userPic.png
tzs.WxApp.appId=wx48a1b1915b10d14b
tzs.WxApp.secret=ac4f4a9d3c97676badb70c19a2f37b16
tzs.WxApp.grant-type=authorization_code
amos.wechat.robot.user=we_robot
amos.wechat.robot.password=a1234567
feign.okhttp.enabled= true
\ No newline at end of file
transport {
# tcp udt unix-domain-socket
type = "TCP"
#NIO NATIVE
server = "NIO"
#enable heartbeat
heartbeat = true
# the client batch send request enable
enableClientBatchSendRequest = true
#thread factory for netty
threadFactory {
bossThreadPrefix = "NettyBoss"
workerThreadPrefix = "NettyServerNIOWorker"
serverExecutorThread-prefix = "NettyServerBizHandler"
shareBossWorker = false
clientSelectorThreadPrefix = "NettyClientSelector"
clientSelectorThreadSize = 1
clientWorkerThreadPrefix = "NettyClientWorkerThread"
# netty boss thread size,will not be used for UDT
bossThreadSize = 1
#auto default pin or 8
workerThreadSize = "8"
}
shutdown {
# when destroy server, wait seconds
wait = 3
}
serialization = "seata"
compressor = "none"
}
service {
#transaction service group mapping
vgroupMapping.tzs-seata = "tzs-seata"
#only support when registry.type=file, please don't set multiple addresses
default.grouplist = "172.16.10.243:8091"
#degrade, current not support
enableDegrade = false
#disable seata
disableGlobalTransaction = false
}
client {
rm {
asyncCommitBufferLimit = 10000
lock {
retryInterval = 10
retryTimes = 30
retryPolicyBranchRollbackOnConflict = true
}
reportRetryCount = 5
tableMetaCheckEnable = false
reportSuccessEnable = false
}
tm {
commitRetryCount = 5
rollbackRetryCount = 5
default-global-transaction-timeout = 600 # 600秒
}
undo {
dataValidation = true
logSerialization = "protostuff"
logTable = "undo_log"
}
log {
exceptionRate = 100
}
}
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<configuration debug="false">
<!--定义日志文件的存储地址 勿在 LogBack 的配置中使用相对路径-->
<property name="LOG_HOME" value="log" />
<!--格式化输出:%d表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度%msg:日志消息,%n是换行符-->
<property name="LOG_PATTERN" value="%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %-50.50logger{50} - %msg [%file:%line] %n" />
<!-- 按照每天生成日志文件 -->
<appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<!--日志文件输出的文件名-->
<FileNamePattern>${LOG_HOME}/Tcm.log.%d{yyyy-MM-dd}.%i.log</FileNamePattern>
<!--日志文件保留天数-->
<MaxHistory>30</MaxHistory>
<!--日志文件大小-->
<MaxFileSize>30mb</MaxFileSize>
</rollingPolicy>
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<pattern>${LOG_PATTERN}</pattern>
</encoder>
</appender>
<!-- 控制台输出 -->
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<pattern>${LOG_PATTERN}</pattern>
</encoder>
</appender>
<!-- &lt;!&ndash; ELK管理 &ndash;&gt;-->
<!-- <appender name="ELK" class="net.logstash.logback.appender.LogstashTcpSocketAppender">-->
<!-- <destination>172.16.10.210:4560</destination>-->
<!-- <encoder charset="UTF-8" class="net.logstash.logback.encoder.LogstashEncoder"/>-->
<!-- </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"/>
<logger name="com.baomidou.mybatisplus" level="debug"/>
<logger name="org.apache.activemq" level="debug"/>
<logger name="org.typroject" level="debug"/>
<logger name="com.yeejoin" level="debug"/>
<!-- 日志输出级别 -->
<root level="error">
<!-- <appender-ref ref="FILE" /> -->
<appender-ref ref="STDOUT" />
<!-- <appender-ref ref="ELK" />-->
</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" />
<!--格式化输出:%d表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度%msg:日志消息,%n是换行符-->
<property name="LOG_PATTERN" value="%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %-50.50logger{50} - %msg [%file:%line] %n" />
<!-- 按照每天生成日志文件 -->
<appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<!--日志文件输出的文件名-->
<FileNamePattern>${LOG_HOME}/ys.log.%d{yyyy-MM-dd}.%i.log</FileNamePattern>
<!--日志文件保留天数-->
<MaxHistory>30</MaxHistory>
<!--日志文件大小-->
<MaxFileSize>30mb</MaxFileSize>
</rollingPolicy>
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<pattern>${LOG_PATTERN}</pattern>
</encoder>
</appender>
<!-- 控制台输出 -->
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<pattern>${LOG_PATTERN}</pattern>
</encoder>
</appender>
<!-- &lt;!&ndash; ELK管理 &ndash;&gt;-->
<!-- <appender name="ELK" class="net.logstash.logback.appender.LogstashTcpSocketAppender">-->
<!-- <destination>172.16.10.210:4560</destination>-->
<!-- <encoder charset="UTF-8" class="net.logstash.logback.encoder.LogstashEncoder"/>-->
<!-- </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="INFO"/>
<logger name="org.mybatis" level="INFO" />
<logger name="java.sql.Connection" level="INFO"/>
<logger name="java.sql.Statement" level="INFO"/>
<logger name="java.sql.PreparedStatement" level="INFO"/>
<logger name="org.springframework" level="INFO"/>
<logger name="com.baomidou.mybatisplus" level="INFO"/>
<logger name="org.apache.activemq" level="INFO"/>
<logger name="org.typroject" level="INFO"/>
<logger name="com.yeejoin" level="INFO"/>
<!-- 日志输出级别 -->
<root level="INFO">
<!-- <appender-ref ref="FILE" /> -->
<appender-ref ref="STDOUT" />
<!-- <appender-ref ref="ELK" />-->
</root>
</configuration>
\ No newline at end of file
registry {
# file 、nacos 、eureka、redis、zk、consul、etcd3、sofa
type = "eureka"
nacos {
serverAddr = "localhost"
namespace = ""
cluster = "default"
}
eureka {
serviceUrl = "http://172.16.10.243:10001/eureka"
application = "default"
weight = "1"
}
redis {
serverAddr = "localhost:6379"
db = "0"
password = ""
cluster = "default"
timeout = "0"
}
zk {
cluster = "default"
serverAddr = "127.0.0.1:2181"
session.timeout = 6000
connect.timeout = 2000
username = ""
password = ""
}
consul {
cluster = "default"
serverAddr = "127.0.0.1:8500"
}
etcd3 {
cluster = "default"
serverAddr = "http://localhost:2379"
}
sofa {
serverAddr = "127.0.0.1:9603"
application = "default"
region = "DEFAULT_ZONE"
datacenter = "DefaultDataCenter"
cluster = "default"
group = "SEATA_GROUP"
addressWaitTime = "3000"
}
file {
name = "file.conf"
}
}
config {
# file、nacos 、apollo、zk、consul、etcd3、springCloudConfig
type = "file"
nacos {
serverAddr = "localhost"
namespace = ""
group = "SEATA_GROUP"
}
consul {
serverAddr = "127.0.0.1:8500"
}
apollo {
app.id = "seata-server"
apollo.meta = "http://192.168.1.204:8801"
namespace = "application"
}
zk {
serverAddr = "127.0.0.1:2181"
session.timeout = 6000
connect.timeout = 2000
username = ""
password = ""
}
etcd3 {
serverAddr = "http://localhost:2379"
}
file {
name = "file.conf"
}
}
<?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">
<parent>
<artifactId>amos-boot-system-tzs</artifactId>
<groupId>com.amosframework.boot</groupId>
<version>1.0.1</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>amos-boot-module-ys</artifactId>
<description>验收模块</description>
<packaging>pom</packaging>
<version>1.0.1</version>
<modules>
<module>amos-boot-module-ys-api</module>
<module>amos-boot-module-ys-biz</module>
</modules>
</project>
\ No newline at end of file
...@@ -20,6 +20,7 @@ ...@@ -20,6 +20,7 @@
<module>amos-boot-module-app</module> <module>amos-boot-module-app</module>
<module>amos-boot-module-tzspatrol</module> <module>amos-boot-module-tzspatrol</module>
<module>amos-boot-module-statistics</module> <module>amos-boot-module-statistics</module>
<module>amos-boot-module-ys</module>
</modules> </modules>
<properties> <properties>
<amos.version.tzs>1.10.8-TZS</amos.version.tzs> <amos.version.tzs>1.10.8-TZS</amos.version.tzs>
......
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